I am receiving error CS0246: “The type or namespace name ‘t’ could not be found. Are you missing a using directive or an assembly reference?” on the following code and I can’t figure out why.
using UnityEngine;
using System;
using System.Collections;
public class EventController : MonoBehaviour {
public string[] scripts;
void OnTriggerEnter(Collider c) {
if(c.tag == "Player") {
for (int i=0; i < scripts.Length; i++) {
UnityEngine.Object s = gameObject.GetComponent(scripts*);*
_ Type t = Type.GetType(scripts*);_
_ ((t)s).Run(); // This is the error line._
_ }_
_ }_
_ }_
_}*_
This doesn't work the way you do it here. System.Type is part of the runtime type information system. It's a special class that describe a certain type. .NET / Mono is a compiled language so it's impossible to compile your code above since the t is not a type, it's a class instance which holds the descriptor of a certain type.
If all those different scripts have a function Run() you should implement an interface in al those types.
Another way would be to use reflection, but it's kinda slow, messy programming style and hard to debug.
edit
Here’s an example how to use an interface:
public interface IRunable
{
void Run();
}
public class SomeScript : MonoBehaviour, IRunable
{
void Update()
{
// ...
}
// This is the interface function. Because we derived our class from IRunable,
// this class must implement the Run() method.
public void Run()
{
}
}
// In your triggering class:
void OnTriggerEnter(Collider c)
{
if(c.tag == "Player")
{
IRunable[] scripts = (IRunable[])gameObject.GetComponents(typeof(IRunable));
foreach (IRunable s in scripts)
{
s.Run();
}
}
}
void OnTriggerEnter(Collider c)
{
if(c.tag == "Player")
{
for (int i=0; i < scripts.Length; i++)
{
MonoBehaviour s = gameObject.GetComponent(scripts*);*
*Type t = s.GetType();*
*System.Reflection.MethodInfo MI = t.GetMethod("Run");*
*MI.Invoke(s);*
*}*
*}*
*}*
*```*
*<p>Of course you should check all those things against "null". If the desired script isn't attached to the object, GetComponent will return null so accessing "s" afterwards yields to a null-ref-exception. If the script type doesn't have a method called "Run", GetMethod will also return null.</p>*