Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 983
jatr49a Avatar asked Nov 15 '25 16:11

jatr49a


1 Answers

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.

like image 180
BugFinder Avatar answered Nov 18 '25 06:11

BugFinder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!