简体   繁体   中英

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.

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

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:

在此处输入图片说明

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 MonoBehaviour s on it:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM