- Home /
tracking ownership of shots
For shooting I create shots via Instantiate(prefab, ... , ...). But I need to know which object created the shot. I have a script attached to the bullet prefab that manages to destroy the shot after a while.
So far I have several ideas:
using SendMessage()... I guess that is not so good on performance
create a class for the shot and instantiate that instead of the prefab and instantiate the prefab in its Start() method... appears a bit complicated
is there another/easier solution?
I am asking cause for me it appears a bit more complicated than it should be. Also I am bit out of practice ;)
thx in advance
Answer by sneftel · Jul 15, 2011 at 09:02 PM
Yep, I think you're overcomplicating it. :-) Have a script on the prefab with an owner field. Set that field after you Instantiate the prefab.
yep, I have a script with an owner field on my prefab, but how do I: a) access that script from the object (owner) where I called Instantiate? OR b) get the object that created the prefab (owner) within the script?
Instantiate will return an Object, which you can cast to GameObject. Then use GetComponent to get the particular component with the owner field.
BLING! A script is a Component! That insight was missing, thx!!!
hmmm it did the GetComponent stuff, but now I have a weird problem... the script for the bullet logic is running two times... once with the owner set and once without... I merely found this out by pure luck. Is this a result of GetComponent? Cause I couldn't find, where I would create the script a second time at least not for one shot.
I'm not sure under what circumstances your script runs, so I can't really help you there. I can tell you, though, that Instantiate causes the constructor and Awake to be run before it returns, but Start isn't called until the next frame. I don't know if that's helpful.... if it isn't, you might start a new question and post the script there.
Your answer
Follow this Question
Related Questions
How to randomly instantiate other prefabs parallel? 1 Answer
Instantiate prefab within parameters?(Javascript) 1 Answer
Destorying prefab and instanstiating again? 0 Answers
Instantiate PreFab with C# Script 5 Answers
Instantiate A Prefab 1 Answer