jatr49a
jatr49a

Reputation: 65

How to add Script to instantiated object at runtime?

I have a Script in my main Assets folder called BezierWalk.cs

In another script, Spawn, I'm trying to instantiate objects from Prefab Sphere and attach BezierWalk.cs to them.

Spawn script:

public class Spawn : MonoBehaviour
{

  public GameObject Sphere;
  //string ScriptName = "BezierWalk";

  void Start()
  {  
      Vector3 vSpawnPos = transform.position;

      for (int i = 0; i < 20; i++)
        {
          var objectYouCreate = Instantiate(Sphere, vSpawnPos, transform.rotation);
          //objectYouCreate.AddComponent<T>("Assets/BezierWalk.cs");
          //objectYouCreate.AddComponent(typeof(ScriptName)) as ScriptName;
          //objectYouCreate.AddComponent<ScriptName>();
          //var myScript = Sphere.AddComponent<BezierWalk.cs>();
          vSpawnPos.z += 20;
        }       
   }

You can see commented out attempts...

How I am supposed to do this properly? Thank you.

Upvotes: 4

Views: 10820

Answers (2)

Issatay Sissemali
Issatay Sissemali

Reputation: 1

If your script lies within certain namespace, you should follow the following format

GameObject.AddComponent(typeof(namespace.className));

Upvotes: 0

BugFinder
BugFinder

Reputation: 17858

If you look at how you reference components in unity, the answer should be clear - did you try any of the ones you listed?

Reference: https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

The normally used is as it is easy reading

objectYouCreate.AddComponent<ClassName>();

You can use

objectYouCreate.AddComponent(typeof(ClassName));

the .cs is for humans, its your readable version. so you would never need the .cs reference in your code.

note: I mentioned it as ClassName rather than scriptname, as while they are the same in monobehaviors in unity, it isnt the same anywhere else in c# so, the important bit is not the name of the file you made, but the name of the class within it.

Another way is to have prefabs, make a prefab of your object with all the components you need already on it.

Upvotes: 6

Related Questions