I have a class (EnemyBehaviour) which extends MonoBehaviour, this class has the following two methods:
private Enemy enemy;
public void set(Enemy enemy)
{
this.enemy = enemy;
}
public Enemy get()
{
return this.enemy;
}
This class also has the unity method:
public void Update()
{
Debug.Log(this.enemy);
}
This method always prints Null.
But, If I call the get() method outside the self MonoBehaviour it returns the right instance.
var eb = enemy.getGameObject().GetComponent<EnemyBehaviour>();
Debug.Log(eb.get()); // it returns UnityEngine.Debug:Log(Object)
The Enemy class is a class which encapsulates the EnemyBehaviour.
public class Enemy
{
private GameObject gameObject;
...
Then, I don't understand why inside the Update(), Start(), OnMouseDown(), or any "Unity method" the enemy property is Null. But if I access the property outside these methods (enemy.getGameObject().GetComponent().get()) it works.
I suspect that Unity MonoBehavour has it's own scope and the GetComponent() other scope.
Another strange thing is if instead of storing the "Enemy" class inside the Behaviour I store a string or Vector3, it works like a charm.
Any idea? Thanks
Edit:
Simplification of the problem: I have an Empty Game Object (Kernel) which instantiates all the other game objects, this has a Kernel class which extends the MonoBehaviour:
public void Start()
{
var enemyGameObject = Resources.Load<GameObject>("Prefab/Enemy");
var enemyBehaviour = enemyGameObject.transform.GetComponent<EnemyBehaviour>();
var foo = new Foo();
enemyBehaviour.Foo = foo;
Instantiate(enemyGameObject);
Debug.Log(enemyBehaviour.Foo); // OK, This one works
}
Foo is a dummy class.
public class Foo
{
}
EnemyBehaviour just does:
public class EnemyBehaviour : MonoBehaviour
{
public Foo Foo;
public void OnMouseDown()
{
Debug.Log(Foo); // When I click on the GameObject, prints Null, it's not working
}
Strange thing: If I replace the var foo = new Foo(); by var foo new Vector3(5,5,5); (Including chaning the type in EnemyBehaviour of course (public Foo Foo; -> public Vector3 Foo;)) everything works fine :S
Edit 2:
Found the issue, was related with the prefab, I was setting the Foo to the Prefab instead of the instance, Fix:
var instance = Instantiate(enemyGameObject);
var enemyBehaviour = instance.transform.GetComponent<EnemyBehaviour>();
Enemy
class to theenemy
member variable, as expected. Once I've assigned a reference to that member variable, the Update method prints non-null from then on. Can you try to construct a complete verifiable test case? \$\endgroup\$