I’m trying to create a static gameobject that can be used in any script. I’m trying to make it so my prefab can use the data from that objects location but for some reason I can’t access this object. Do I need to add more to this ?
static var asset : GameObject;
2 Answers
2
This is a good situation to use a singleton pattern:
public class MyGameObject : MonoBehaviour
{
// A static instance of this class that we can reference
private static MyGameObject singletonInstance = null;
// Use this property to get hold of the singleton instance.
public static MyGameObject instance
{
get
{
if (singletonInstance == null)
{
// The first time this is called, look for an instance of this
// class in the scene and cache/return it
singletonInstance = FindObjectOfType(typeof(MyGameObject)) as MyGameObject;
if (singletonInstance == null)
Debug.LogError("Could not locate a singletonInstance object in the scene.");
}
return singletonInstance;
}
}
}
public class MyGameObject : MonoBehaviour
{
// A static instance of this class that we can reference
private static MyGameObject singletonInstance = null;
// Use this property to get hold of the singleton instance.
public static MyGameObject instance
{
get
{
if (singletonInstance == null)
{
// The first time this is called, look for an instance of this
// class in the scene and cache/return it
singletonInstance = FindObjectOfType(typeof(MyGameObject)) as MyGameObject;
if (singletonInstance == null)
Debug.LogError("Could not locate a singletonInstance object in the scene.");
}
return singletonInstance;
}
}
//shoud i add this? : )
void Start(){
instance = this;
}
}
Would I just need to rewrite the functions since I'm programming in javascript ?
– jessee03Oh Javascript! Oops. In that case you can find a good example here, it looks like: http://answers.unity3d.com/questions/26491/javascript-singleton.html
– uberhamster