Personaly, I like to make a Singleton and cache some importante variables in it like player, points, list of enemies and etc.
The upside is that you make sure that there will be only one instance of the Singleton in your scene, therefore you will not have this problem of accessing other instances instead of the one you want.
The code for a Singleton is:
using UnityEngine;
using System.Collections;
public class SingletonExample : MonoBehaviour
{
private static SingletonExample _instance;
public static SingletonExample instance
{
get{
if(_instance == null)
{
GameObject singletonHolder = new GameObject("[SingletonExample]");
_instance= singletonHolder.AddComponent();
}
return _instance;
}
}
public void Awake()
{
//ONLY IF YOU WANT IT TO NOT EVER BE DESTROYED
DontDestroyOnLoad(gameObject);
}
}
And you call like this:
**SingletonExample.instance.someVariableYouCreated.ActionYouWantItToTake();**
Or in your case:
**SingletonExample.instance.player** instead of **GameObject.FindWithTag("Player");**
Dont forget to declare your variables and assign them onto the Singleton.
If you want to learn more about check this link:
http://en.wikipedia.org/wiki/Singleton_pattern
↧