Answer the question
In order to leave comments, you need to log in
(Example from Unity3d) Problem with understanding types in C#, how does it work?
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
When the script starts, the unit will put into your moveObject what you dragged there in the inspector. Hidden and inconspicuous.
and we did not use the new operator
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 questionAsk a Question
731 491 924 answers to any question