- Home /
Is it possible to load a script to a gameobject, run it then destory it? (Onetime script)
Is it possible to load a script to a gameobject, run it then destory it?
if(Input.GetButton("Fire1")){
if(spell = fireball){
//load fireball.cs to player
//Run fireball.cs
//delete fireball.cs from player
}
else if(spell = frostshield){
//load frostshield.cs to player
//run frostshield.cs
//delete frostshield.cs from player
}
}
Something like that im gonna have many diffrent spells so i dont wanna add scripts to the player that not gonna get used. Sorry for my bad explanation.
Answer by Statement · Mar 16, 2011 at 05:35 PM
You can do something like:
if(Input.GetButton("Fire1")) { if(spell = fireball) { var fireballScript = gameObject.AddComponent<Fireball>(); Destroy(fireballScript, 4); // Destroy it after 4 seconds
}
else if (spell = frostshield)
{
var frostshieldScript = gameObject.AddComponent<Frostshield>();
Destroy(frostshieldScript, 4); // Destroy it after 4 seconds
}
}
However for some circumstances it could be better if the Fireball and Frostshield scripts themselves delete themselves according to some rules. In those scripts they can call Destroy on themselves.
If you want to wait executing until the script is deleted and you're inside a coroutine you could do something like:
var frostshieldScript = gameObject.AddComponent<Frostshield>();
// Destroy it after 4 seconds Destroy(frostshieldScript, 4);
// Wait for it to be destroyed. while (frostshieldScript) yield return null;
Or if you only want to wait 4 seconds:
var frostshieldScript = gameObject.AddComponent<Frostshield>();
// Destroy it after 4 seconds Destroy(frostshieldScript, 4);
// Wait for it to be destroyed. yield return new WaitForSeconds(4);
Thanks for the fast answer, but im writing in c# so i need to define what frostshieldScript is.
No you don't. C# support type inference so var is just a shortcut for typing out Frostshield or Fireball. The Frostshield and Fireball scripts must derive from $$anonymous$$onobehaviour by the way.
See this post about type inference. It's just the same as typing out Fireball or Frostshield in the above example. It replaces "var" with "Fireball" etc compile time it will replace it with Fireball (even intellisense picks it up beautifully). So there is no performance costs or anything to do with dynamic objects. http://geekswithblogs.net/sdorman/archive/2007/04/06/111034.aspx
Your answer
Follow this Question
Related Questions
Create a ball then launch it 3 Answers
Instantiated object don't recognize MouseClick. 0 Answers
Instantiate A Prefab 1 Answer
Manipulating a prefab from within the script that instantiated it 3 Answers
Checking if object intersects? 1 Answer