Home>

I'm developing a game with Unity and have questions about GetComponent.
Suppose that there is a game object with the name name and tag attached to it, and a script with the same name as name is attached to this game object. Is it possible to access the script using GetComponent if the name is unknown until the game starts?

What I tried and problems

The tag is known to be a Tag, so you can use FindWithTag to access the game object, but
Since you don't know the name of the script, you cannot prepare a variable in the field as the type name. In other words, I don't know how to write the script name with the following code. Is this possible in the first place?
Thanks for your answer.

GameObject gameObject = GameObject.FindWithTag ("Tag");
Script name gameScript = gameObject.GetComponent<script name>();


I thought about using the var type, but I couldn't use gameScript in the first place because I wanted to write it in the field.

  • Answer # 1

    It's a good idea to think of "How to make scripts common?" instead of "How to find script names".

    For example, create a script called Actor and attach it to the object to be GetComponent.
    Actor has Think and implements object-specific processing here.

    It looks like this when written in code.

    var actor = obj.GetComponent  ();
    // Script to attach to the object
    public class Actor: MonoBehaviour {
      public Think think;
    }
    // common class
    public abstract class Think {
      // interface
      // common processing
    }
    public class Player: Think {
      // Player specific processing
    }
    public class Enemy: Think {
      // specific processing of the enemy
    }