Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10571

Get the script name from game object

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 ?

Upvotes: 1

Views: 7242

Answers (2)

Venkat at Axiom Studios
Venkat at Axiom Studios

Reputation: 2516

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);

Upvotes: 1

Jerry Switalski
Jerry Switalski

Reputation: 2720

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

Upvotes: 9

Related Questions