First and foremost, use code tags:
foreach (Collider c in HitCollider.Length)
{
// Made a Array of MonoBehaviours
MonoBehaviour[] mono;
// add scripts mine target have.
mono = c.GetComponents <MonoBehaviour> ();
// then checking each of them
foreach (MonoBehaviour m in mono)
{
// finding script i want
if (m.name.Contains ("Ai"))
{
// now i want to access this Script M's variables, Game objects and Methods i want to know how to do that.
}
}
}
Next, is there some consistent name of the variables from script to script? Like is it no matter if it’s AiX or AiY, is the variable the same name? Or is it different depending the script?
In the former there’s a clear answer.
In the ladder, well… that’s weird. It logically falls apart very fast algorithmically.
SO…
In the former, the best way to do this is via polymorphism. And there are 2 basic ways to do this.
- have a base type from which your various AI script inherit from which defines the methods
- have an interface that each AI script implements
Personally I prefer option 2, since it allows for a lot more wiggle room in the implementation, instead of restricting you to a class hierarchy.
But I’ll give examples of both…
Option 1:
public class AIBase : MonoBehaviour
{
public string SomeProperty;
public virtual void Foo()
{
}
}
public class AITypeA : AIBase
{
public override void Foo()
{
//do unique stuff
}
}
foreach(Collider c in HitCollider.Length)
{
foreach(var ai in c.GetComponents<AIBase>())
{
ai.DoStuff();
}
}
Option 2:
public interface IAIScript
{
string SomeProperty { get; set; }
void Foo();
}
public class AITypeA : MonoBehaviour, IAIScript
{
[SerializeField()]
private string _someProperty;
public string SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; }
}
public void Foo()
{
//do unique stuff
}
}
foreach(Collider c in HitCollider.Length)
{
foreach(var ai in c.GetComponents<IAIScript>())
{
ai.Foo();
ai.SomeProperty = "BLARGH"; //manipulating the property SomeProperty
}
}
(note - the ‘Collider in HitCollider.Length’ is realy weird… I’m assuming you sort of mixed up for(int i = 0; i < HitColliders.Length; i++) and a foreach setup… but I just copied your syntax cause… yeah)