So i have a pretty simple situation that for reason seems to not be working in C#.
GameObjectA with ScriptA attached, GameObjectB with ScriptB attached. The following SHOULD work right? Or am i missing something (which obviously i am, otherwise it would just work).
Been banging my head all weekend and i cant figure out why this isn’t working via a script call, but does work if i assign the function to a button
Help please??
ScriptA:
public GameObject GameObjectB; //Where the GameObjectB has been assigned in the Editor
void Start()
{
doSomethingA();
}
public void doSomethingA()
{
ScriptB foo = GameObjectB.GetComponent<ScriptB>();
foo.PrintSomething();
}
ScriptB:
public GameObject GameObjectA; //Where the GameObjectA has been assigned in the Editor
public void PrintSomething()
{
Debug.Log("This Works!");
}
Your code seems to be correct.
Is there a error when executing?
No, no error, it just wont execute the function for some reason.
I actually found this code example that seems to work in ScriptA, is there a reason that message passing like this would be programmatically correct or cause issues?
GameObjectB.gameObject.SendMessage("PrintSomething");
You above code worked just fine for my self.
For ScriptA you can also do this.
public void doSomethingA(){
GameObjectB.GetComponent<ScriptB>().PrintSomething();
}
This way your not declaring a var. Unless you really need it.
ScriptA
using UnityEngine;
using System.Collections;
public class ScriptA : MonoBehaviour {
public GameObject GameObjectB;
void Start () {
doSomethingA();
}
public void doSomethingA(){
GameObjectB.GetComponent<ScriptB>().PrintSomething();
}
}
Script B
using UnityEngine;
using System.Collections;
public class ScriptB : MonoBehaviour {
public void PrintSomething(){
Debug.Log("This Works!");
}
}