A
A
Artem Tarkovsky2017-06-21 14:39:33
C++ / C#
Artem Tarkovsky, 2017-06-21 14:39:33

(Example from Unity3d) Problem with understanding types in C#, how does it work?

f3f61c470f04428b89b1646c3035cf96.jpg
I can't understand a few lines of code, here's an example:
public GameObject moveObject; - As I understand it, here we declared a variable moveObject of a reference type (because GameObject is a class), but how should it work? After all, this is not an Int or String, but we did not use the new operator to allocate memory and get an object. I don't understand how it works! Help me figure this out...

public class MoveObject : MonoBehaviour
{
    public GameObject moveObject;
    public Transform targetPosition;
    public float speed;
  // Use this for initialization
  void Start ()
    {
    
  }
  
  // Update is called once per frame
  void Update ()
    {
        moveObject.transform.position = Vector3.MoveTowards(moveObject.transform.position, targetPosition.position, Time.deltaTime*speed);
        moveObject.transform.LookAt(targetPosition);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2017-06-21
@Diciptikon

When the script starts, the unit will put into your moveObject what you dragged there in the inspector. Hidden and inconspicuous.

F
Fat Lorrie, 2017-06-21
@Free_ze

and we did not use the new operator

For example, like this:
using System;
using System.Reflection;

public class Program
{
  public static void Main()
  {
    MoveObject obj = UnityFactory.GetInstance<MoveObject>();
    
    obj.moveObject.SayHello();
  }
}


public class GameObject
{
  private string name;
  
  public GameObject()
  {
    name = "John";
  }
  
  public void SayHello() {
    Console.WriteLine("Hello! My name is " + name );
  }
}


public class MoveObject
{
    public GameObject moveObject;
}


public class UnityFactory {
    public static T GetInstance<T>() where T: new()
  {
    
    // Создадим экземпляр основного класса
        T instance = (T)Activator.CreateInstance(typeof(T));
    
    // Инициализируем его открытые поля
        FieldInfo[] fields = typeof(T).GetFields();
    
        foreach (FieldInfo field in fields)
        {
            object fieldValue = Activator.CreateInstance(field.FieldType);
            field.SetValue(instance, fieldValue);
        }
    
    return instance;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question