- Home /
Acessing scripts in other game objects with prefabs, without using GameObject.Find
Hi everyone.
I'm trying to learn more about scripting in Unity and I'm coming across a problem.
I have a small text-based game, and I'm trying to achieve this result:
1) Click a button to spawn a bee. 2) After 2 seconds(this time can be variable), a bee adds nectar to the hive.
The first part that I had with this, was assigning a game object that I called a "resourceBank" to my bee, which is a prefab. I'm not able to set it up without using a GameObject.Find, and having it access it through my game controller.\\
There is a method in resourceBank that called addNectar, adds nectar to itself, and keeps track of how much collected nectar is in the hive. I am accessing this method by way of the bee, and in the future, it can perform other functions such as buildWax, addPollen, and all that.
I was wondering if I am approaching this the correct way, am I limited to using GameObject.Find, I've heard it would be slow, and am planning to spawn several bees as this game progresses.
You can assign the reference in the inspector before you ever run the game.
Answer by smallbit · Jul 25, 2014 at 02:06 AM
Firstly Find is slow but if you are going to use it every now and then only its acceptable.
In your case you could use singleton code pattern for your hive. Singleton can be used for class that can only have one instance (like your hive i assume). Than you can access it from anyplace in your code without the reference to the actual gameobject on which the script is.
For example your hive script code
public class Hive : MonoBehaviour
{
//declare instance
public static Hive instance;
void Start()
{
//very important to initialize your instance
instance = this;
}
// must be public to be accessible
public void AddNectar(int amount)
{
//your code
}
//you can also use static method (this can operate only on static members)
public static void AddPollen(int amount)
{
}
than in your bee script you just call like this ( no need to know the game object, so no need to use find)
Hive.instance.AddNectar(20); need to call via instance
Hive.AddPollen(30); //method is static no need to call instance
I suggest you google about singleton pattern (and static methods) its a very simple to use and can save a lot of time !!! Since i started using it my life is much easier :)
I'm pretty new to this and I've never heard of singleton code patterns, I will look this up. Thanks!
Your answer
Follow this Question
Related Questions
How to order newly created Objects? 1 Answer
prefab query 1 Answer
[Solved]Instantiating prefab from a script and destroy it from another one 2 Answers
Instantiate A Prefab 1 Answer
How to attach a prefab to a script that is added dynamically 0 Answers