- Home /
Instantiate a destoyed object? Or instantiate an Object that is not on the Scene?
Hey! sorry for the noob question, just getting started:
I have a canon that shoots cannonballs,when they hit something they explode.
1)In order to instantiate the cannonball, Do i have to have the cannonball somewhere in the scene?
If i do this, because the cannonball is triggered to explode on contact, as soon as it spawns, it explodes and I cannot instantiate it again.
Is it posible to instantiate an object that is not on the scene?
Help much much apreciated
function HoldToShoot (){
if (Input.GetButtonDown("Fire1")) {
StartX = Time.time;
}
if (Input.GetButtonUp("Fire1")){
EndX = Time.time;
force = (EndX-StartX)*20;
clone = Instantiate(clone, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (Vector3.forward * force);
}
}
Answer by xortrox · Apr 22, 2014 at 08:19 PM
If you got the cannon ball in your scene view right now, drag and drop it into your project window/tab, this will create a prefab (a copy of your cannon ball), drag and drop this into a script with a public GameObject variable to hold it and use this variable when instantiating.
Answer by Fearthefrozt · Apr 23, 2014 at 05:31 PM
You're going to want to create a prefab of the cannon ball just like xortrox said. Here is a video on how to create them.
https://www.youtube.com/watch?v=HECGcwwRM64
You will then want to use the Instantiate() function to create a clone of the prefab in the scene whenever you shoot the cannon ball. This means when it's destroyed it simply destroys the clone and you can easily use Instantiate() to create another one. For information on this function look at:
http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html
I typically put my prefabs in a prefab folder in a Resources folder in Assets so that I can load it into the scene through code. Say you created a prefab called cannonball and after placing it in the prefabs folder the code would look something like this:
Instantiate(Resources.Load("prefabs/cannonball"), new Vector3(0,0,0), Quaternion.identity);
That would instantiate the cannonball at position 0,0,0 in the world.
Answer by murkertrer · Apr 24, 2014 at 04:35 PM
Thank you guys!! XD
function HoldToShoot (){
if (ammoCount > 0){
if (Input.GetButtonDown("Fire1")) {
StartX = Time.time;
ammoCount-=1;
}
if (Input.GetButtonUp("Fire1")&& Time.time > nextFire){
nextFire = Time.time + fireRate;
EndX = Time.time;
force = (EndX-StartX)*20;
if (force>45){
force=45;}
shootingForce.text ="Max45.Force:" + force;
var clone : Rigidbody;
clone = Instantiate(regular, transform.position, transform.rotation);
clone.velocity = ransform.TransformDirection(Vector3.forward * force);
}}}