So i made a script that instantiates a prefab(cube) onto an empty game object when i press the space button
and adds a force to it. It works as expected but my question is is there anyway to have it so the Instantiate function returns a Rigidbody on the clone instead of having to store a reference to it?
public class Force : MonoBehaviour {
public GameObject Prefab;
public float power;
public int objLimit;
int objAdd;
GameObject instance;
void Update () {
if (Input.GetButtonUp ("Jump")) {
if(objAdd != objLimit){
instance = Instantiate (Prefab, transform.position, transform.rotation)as GameObject;
Rigidbody rb=instance.GetComponent<Rigidbody>();
rb.AddForce (transform.forward*power,ForceMode.Impulse);
objAdd++;
}
}
}
}
The object is instantiated at runtime but it does not add the force i get the error object reference not set to an instance of an object
here is the modified script:
public class Force : MonoBehaviour {
public Rigidbody Prefab;
public float power;
public int objLimit;
Rigidbody instance;
int objAdd;
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonUp ("Jump")) {
if(objAdd != objLimit){
instance = Instantiate (Prefab, transform.position, transform.rotation)as Rigidbody;
instance.AddForce (-transform.right*power,ForceMode.Impulse);
objAdd++;
}
}
}
}
No. Instantiate() returns the same type as you put into it. Give it a GameObject, and it returns a GameObject. So you will have to use GetComponent() to get your rigidbody from it.
As to the second part of your question, why not simply declare the “instance” variable local?
If you’re not going to need a reference to the instantiated object, you can do a GetComponent right away:
public class Force : MonoBehaviour {
public GameObject Prefab;
public float power;
public int objLimit;
int numAdded;
void Update() {
if (Input.GetButtonUp("Jump")) {
if (numAdded < objLimit) {
var rb = ((GameObject) Instantiate(Prefab, transform.position, transform.rotation)).GetComponent<Rigidbody>();
rb.AddForce(transform.forward * power, ForceMode.Impulse);
numAdded++;
}
}
}
}
Not exactly, you actually can instantiate a rigidbody as part of some prefab (just put a prefab with rigidbody component to the rigidbody serialize field) and it will create that prefab’s clone with this rigidbody attached and Instantiate will return you rigidbody ref (after as Rigidbody / (Rigidbody) tricks).
That’s why I expanded on my answer to say that it will return what you gave it. The initial “no” was more targeted to OP’s original situation in where he wanted to invoke Instantiate() with a GameObject.