- Home /
How to use functions in a script associated with a prefab?
Hi, I'm new to unity and some concepts are still new to me, especially this prefab business. I'm creating a game and I have a prefab called 'knight' with a script attached to it called "Knight", and inside this script is a function called "MoveTowardsMouse". I want to create instances of the knight dynamically so I have an empty Game Object with a script that goes like this:
public GameObject kk;
public GameObject knight;
void Start () {
kk = (GameObject) Instantiate (knight, transform.position, transform.rotation);
}
Now my kk object was defined to be a GameObject so there is no way I can tell it to use "MoveTowardsMouse", but the instantiate code is the only way I've found to create prefabs with code. What's the better way to do this (without just dragging 100 knight prefabs on the screen when i need them)?
"...so there is no way I can tell it to use "$$anonymous$$oveTowards$$anonymous$$ouse"
Explain that bit in a little more detail? Script to script or GameObject to GameObject communication is a cornerstone of the system.
well in my Game Object the code 'kk.$$anonymous$$oveTowards$$anonymous$$ouse()' would return an error since the type GameObject does not have the method $$anonymous$$oveTowards$$anonymous$$ouse. Essentially, how can I call this method from my empty Game Object?
Answer by GiyomuGames · Jul 29, 2015 at 12:23 AM
If you do:
kk.GetComponent<Knight>().MoveTowardsMouse()
it should work.
Thanks, works perfectly! Is this the way it's usually done?
Yes, this is the way to access scripts from gameobjects.
I think you should mark the answer as correct if it solved your problem :)
Your answer
![](https://koobas.hobune.stream/wayback/20220611233459im_/https://answers.unity.com/themes/thub/images/avi.jpg)