- Home /
Adding script during runtime
So basically what I am trying to accomplish here is a script that adds a specific behavior script to the gameobject when I click. I have another script called behavior that does all of the general stuff an object should do, and different scripts that inherit from behavior. I want to add one of the different scripts to the gameobject when I click.
Unity gives me the error that Placer.PScript is a field but a type was expected.
Placer is the name of this script btw.
public Behavior PScript;
void Update () {
if(Input.GetMouseButton(0)){
gameObject.AddComponent<PScript>();
Destroy(this);
}
}
Answer by xxmariofer · Apr 01, 2019 at 07:16 PM
PScript is the name of a variable, you need to pass the type, also try avoid overriding unity component names
gameObject.AddComponent<Behavior>();
That adds the script called Behavior. I need to add PScript which is a script I attach in the editor. It inherits Behavior.
never call a variable the same as a class, then change to
public PScript pScript;
gameObject.AddComponent<PScript>();
//or
gameObject.AddComponent<typeof(pScript)>();