0

Greeting,

I was wondering is it possible to add multiple different scripts using array to same game object at the beginning of runtime.

This is a pseudo-code I think of:

public GameObject TargetObject;
public string[] ScriptsToAdd;

void Start(){
     for(int i = 0; i < ScriptsToAdd.Length; i++){
           TargetObject.addComponent<ScriptsToAdd[i]>();
     }
}

If I did something wrong here, please do let me know.

1
  • First, AddComponent instead of addComponent. Second, you need a type, not a string. It won't work imo. adding-component - you need to get a type using its literal name. Commented Aug 6, 2020 at 9:11

1 Answer 1

1

There some things you're doing wrong :

  • first : use AddComponent instead of addComponent.
  • second : you can't add string as component you use type for example List<Type> components.
Sign up to request clarification or add additional context in comments.

1 Comment

The alternative that OP seems to want to use would be AddComponent(string) but agree one should prefer AddComponent<TComponent>() whenever possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.