Domanda

I know this is easy and I can do it if it's a GameObject, but how do I instantiate a new script?

Instantiate(FleeScript);

I get errors for that.

È stato utile?

Soluzione

Remember: a script must be in a GameObject.

So, to get an instance of a new script you either add it to a GameObject:

GameObject myGameObject = ...
FleeScript fleeScript = myGameObject.AddComponent<FleeScript>();
// do something with fleeScript

or you have a prefab that already contains that script and instantiate that prefab:

public class MyOtherScript
{
    public FleeScript prefabWithFleeScript; // Linked from the Editor

    void Awake()
    {
        FleeScript fleeScript= Instantiate(prefabWithFleeScript);
        // do something with fleeScript
    }
}

Altri suggerimenti

Instead of destroying and instantiating new script, I enable and disable them using GetComponent.enabled = true/false.

public static void AttachScript(GameObject obj, string scriptClassName)
{
    if (obj != null)
        obj.AddComponent(scriptClassName);
}

public static void AttachScript(string gameObjectName, string scriptClassName)
{
    var obj = GameObject.Find(gameObjectName);
    if (obj != null)
        obj.AddComponent(scriptClassName);
}

Note:

  1. the argument "scriptClassName" is the class name, not "scriptClassName.cs"
  2. You should make sure the script class file exists in the project folder or subfolders
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top