- Home /
How to create a variable in which I can put scripts
Hy! How can I make a variable in which I can put scripts. I have atleast 5 scripts in which a function is named ActivateMode(). In this variable I would like to put one of these scripts. For example, If the name of the variable is a, then i would like to call the function like this: a.ActivateMode(); How can I make it, any suggestion?
Simple questions are usually answered in turorials. Please google before asking a question.
https://unity3d.com/learn/tutorials/topics/scripting/how-communicate-between-scripts-and-gameobjects
Hello TreyH. The question is ok, please dont send to moderation this easy. As you can imagine he is givin enough info to know he is not just asking the first problem he had. He is not asking how to comunicate. As tutorials show, you should declare a variable by its type. But in this case he is asking a type that can have diferents class. I made a whole project without knowing this. So is normal he ask it. :D
This question has been answered in depth hundreds of other times on this forum (https://answers.unity.com/questions/1277116/public-script-variable-in-inspector.html was found immediately from googling). You're welcome to approve this in the moderator queue, but my understanding is that duplicate questions should redirect to similar, already-answered questions.
Answer by tormentoarmagedoom · Apr 05, 2018 at 12:26 PM
Good day.
Yea, you can create a variable of type Object, wich can be any type of class script when you define it, its like a joker ;D
And later assign a script to tjat variable. Like this, first declare it:
Object Scripts;
And later (example)
Scripts = GameObject.FindObjectWithTag("Player"). GetComponent<PlayerScript1>();
Scripts.PlayerMethod();
And more later change it if you need
Scripts = GameObject.FindObjectWithTag("Enemy"). GetComponent<EnemyScrpt1>();
Scripts.EnemyMethod();
If helped, accept/upvote the answerrr Byee :D
Ty for your response! I understand what you did here, but I get an error: 'UnityEngine.Object' does not contain a definition for 'Player$$anonymous$$ethod' and no extension method 'Player$$anonymous$$ethod' of type 'UnityEngine.Object' could be found. Are you missing an assembly reference? Any idea?
After I assign to a component, the Object dont know the component`s functions.
$$anonymous$$mm investigate a litttle, maybe i write something wrong, but is possible to do it, i did it ina project last year but i cant be sure if was exactly this way. And confirm it in unity api help. And check versions of Unity too
As TreyH said, make some research, i just opened the door :D
If you suceed, post the solution as a coment and accept the answer!
Bye!
Answer by kskjadav007 · Apr 05, 2018 at 01:49 PM
Like This
private GameObject m_one;
// Use this for initialization
void Start ()
{
m_one = GameObject.FindGameObjectWithTag ("one");
m_one.gameObject.AddComponent<PlayerControl> ();
}