- Home /
Getting instantiated clone's coordinates from the same script
In my program, I'm supposed to create an instantiated particle-system, and then translate it to the location of a certain clone. However, I have found no good way of doing this; the idea I had was called "obsolete" by Visual Studio, and I don't know how (Or if) I can use GetComponent <>() in this situation either.
Here's the code I have now:
(To instantiate the Clone)
Rigidbody rb;
rb = Instantiate(fallingObject,position,rotation);
rb.name = "Clone";
(To move the particle-system to it's location)
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name =="FallingObjects")
{
Destroy(this.gameObject);
}
if(collision.gameObject.name == "Ground"||collision.gameObject.name == "Player")
{
Rigidbody rb = gameObject.rigidbody;
Destroy(Instantiate(particles, rb.position, rb.rotation));
Destroy(this.gameObject);
}
}
Again, my main issue is with the "Rigidbody rb = gameObject.rigidbody;" line of code; it says that it's obsolete and that there's a better answer than just that, however I need to get an instantiated clone, so GetComponent<>(); wouldn't be able to pick up the precise clone that I need to do that to.
Thanks a million for your help
Yes, trying to use the rigidbody property of a gameObject is obsolete. What you should be doing is using
GetComponent<Rigidbody>();
Like you said. Also you should do that on the Start method and save that to a Rigidbody field ("cache it") so you don't have do keep calling GetComponent every time, you use the saved reference ins$$anonymous$$d.
Also, just a quick question. What's up with this line?
Destroy(Instantiate(particles, rb.position, rb.rotation));
Why create something (Instantiate) and then destroy it in the exact same instant (Well maybe not the exact same instant since destroy takes at least one frame I think, but you get what I mean :P)?
Answer by felipin · Jul 06, 2018 at 06:55 PM
Destroy(Instantiate(particles, transform.position, transform.rotation));
Destroy(this.gameObject);
The unique component (I guess) that you can access as a MonoBehaviour property is transform, otherwise every property that should access a component is obsolete. If you want to access a specific compoent use GetComponent.