- Home /
How do I get a prefab to know who made it?
var spellOne : Transform;
var coolDownOne : float;
var timerOne : float;
function Update () {
timerOne++;
if (Input.GetButton ("Cast1")) {
if(coolDownOne < timerOne) {
var instanceBulletOne = Instantiate(spellOne, transform.position, transform.rotation);
timerOne = 0;
}
else
{
if(coolDownOne > timerOne) {
print("Nope!");
}
}
}
So this is the basis of my spell system. It works beautifully. I press a button I've called Cast1 and it instantiates a prefab that functions as whatever spell I would like. I have one that acts as a fireball, another that works as a wall, and some others I'm toying with. I have a turret and two players using these spells right now, and I would like to use them with enemies once I get to that point as well, ideally.
What I need, though, is the ability for those prefabs to know who cast them. If Player1 casts a homing missile, I want it to be able to check for the nearest enemy and put that enemy into its Target variable. If Player2 casts a Blink spell, I want it to know that Player2 is the one who needs to move forward by a few feet. You get the idea.
How would I go about approaching that?
Do you have some sort of script that is attatched to each player? You could have a variable in the spell that holds a reference to that player script.
Answer by getyour411 · Apr 09, 2014 at 04:57 AM
One thought:
instanceBulletOne.SetInitator(this.gameObject);
on the prefab add a script/method named SetInitiator that accepts a GameObject parameter; you can of course call those whatever you want. The prefab now knows what GameObject called it.
That sounds like a good option, but I'm a little fuzzy on the interaction between the bits of code (I'm new to coding).
So in your suggestion I would have instanceBulletOne.SetInitiator(this.gameObject), which will basically create the prefab and define itself as the person who instantiated that prefab. But on the prefab itself, what would I use to call back to the SetInitiator? How would the prefab know where to look for its mommy?
The Instantiate line (as you have it) is what creates the instance of the prefab, my line just makes a call to the instance and passes the reference gameobject;
Within the prefab, you could then use the passed reference (as it came into SetInitiator) to do whatever you want.
Ff you just want to set a parent/child relationship you could create that via instanceBulletOne.transform = gameObject.transform (after the Instantiate) though I'm not sure that's what you asked for.