- Home /
Creating instance of GameObject(Holding component) at same location as object that holds the script
GameObject particleSystemInstance = Instantiate(Resources.Load("DeathParticles")) as GameObject;
GameObject temp = Instantiate(particleSystemInstance, this.transform.position ,Quaternion.identity) as GameObject;
temp.transform.position = this.gameObject.transform.position;
I am using unity 2d version 5.x
Hey all, I have a gameobject in my resources folder which has a particle system attached.
The code you see above is in a script attached to the player.
When he dies the above code is triggered.
My final line of code shows my attempt to set the location of the instantiated particle effects to the location of the player object.
However this does not seem to be working.
In game it shows the particle effects when the player dies, just in the space place and does not take into account the position of the player.
Thanks for any help!
EDIT:
The following works now: GameObject particleSystemInstance = Instantiate(Resources.Load("DeathParticles")) as GameObject;
GameObject temp = Instantiate(particleSystemInstance, this.transform.position ,Quaternion.identity) as GameObject;
temp.transform.position = this.gameObject.transform.position;
However when the death happens the particle effects also seemingly appear in a random position as well as where the player is??
GameObject temp = Instantiate(Resources.Load("DeathParticles"), transform.position , Quaternion.identity) as GameObject;
just this should work fine?
To properly format your code use the 101 010 button. For more information on how to effectively use Unity Answers watch the Unity Answers tutorial https://www.youtube.com/watch?v=ezAPpViLs2Q and read the faq: http://answers.unity3d.com/page/faq.html.
Answer by maccabbe · Jan 04, 2016 at 03:25 AM
The issue is that you're instantiating the particles twice.
First you load the prefab using Resource.Load. Then a gameObject is instantiated from the prefab and set to particleSystemInstance. Then you instantiate a second time from the gameobject particleSystemInstance and assign it the gameobject temp.
Change
GameObject particleSystemInstance = Instantiate(Resources.Load("DeathParticles")) as GameObject;
GameObject temp = Instantiate(particleSystemInstance, this.transform.position ,Quaternion.identity) as GameObject;
temp.transform.position = this.gameObject.transform.position;
to
GameObject temp = Instantiate(Resources.Load("DeathParticles"), this.transform.position, Quaternion.identity) as GameObject;