1

I have a gameobject two scripts are attached with it. I want to get the name of second script from first script. Remember:

  1. I don't want direct assignment (i know it very well).
  2. First Script name can not be hard coded causes it will change.

Consequently, I want to get the script name and set that script property ?

0

2 Answers 2

9

I am not sure what do you mean by "I want to get the name of second script from first script", but take a look at this:

enter image description here

I have to scripts attached to Main Camera gameObject.

Here is the code of Test.cs:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour 
{

    void Start()
    {
        MonoBehaviour[] scripts = this.GetComponents<MonoBehaviour> ();

        foreach (MonoBehaviour mb in scripts)
        {
            Debug.Log (mb.GetType ().Name);
        }
    }
}

On start it prints the names of all MonoBehaviours on it:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

now I have got the name of script it is in string format. how do i use it in getComponenet?
1

This, while not straight-forward is a fairly easy way to do what you need.

Since AddComponent no longer accepts a string (the docs indicate otherwise, but I assume it's because Unity hasn't gotten around to update it), what you can do is

  1. Get the Type using Type.GetType
  2. Use AddComponent(System.Type)

Code below

var type = Type.GetType("SomeClassName");
gameObject.AddComponent(type);

Comments

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.