- Home /
Instantiate prefab and passing parameter
There is a way to instantiate a prefab and acess a component from it ?
I want to instantiate a bullet, and then i say to the bullet for e.g: "Hey, your power is this and your range is this".
Hope you understand my question
Answer by Mike-Geig · Feb 09, 2014 at 12:42 AM
Sure, do this:
var obj = (GameObject)Instantiate(...);
obj.GetComponent<WhatComponent>().DoSomething();
Replace DoSomething with whatever you want to do, or store the result of GetComponent in a variable if you need to do more than one thing.
This works for me:
//Use this code inside your script that instantiate the bullets:
var obj = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
//Do not forget to set correct position and rotation wich you want.
//Sending to instantiated bulletPrefab the parameters bulletSpeed and bulletrange:
obj.GetComponent<ScriptInYourBullet>().RecieveBulletParameter(bulletSpeed, bulletrange);
Inside ScriptInYourBullet you need this public void method:
public void RecieveBulletParameter(float speed, float range)
{
bulletSpeed = speed;
bulletRange = range;
}
Your answer
Follow this Question
Related Questions
Unet NetworkServer.Spawn() not working 5 Answers
How can I spawn a GameObject on all players in my multiplayer game? 0 Answers
Players Not Showing 0 Answers
RPC sync issues 0 Answers
Networking: how to sync NetworkViewIDs for level objects on peers? 4 Answers