I’m just getting into using UnityEvent and am trying to create a UnityEvent that receives a single bool parameter. However the function I invoke through the UnityEvent always receives a value of false.
I am running on Android. I have three scripts
ObjectTouch raycasts from the touch location and calls the function ActionOnTouch.DoIT(someBool) if the object has that script.
public class ObjectTouch : MonoBehaviour
{
private Ray ray;
private RaycastHit hit;
private Touch touch;
Camera cam;
bool trueFalse = true;
ActionOnTouch action;
void Start()
{
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
ray = cam.ScreenPointToRay(touch.position);
Physics.Raycast(ray, out hit, 100);
if (hit.collider != null)
{
if (hit.collider.transform.gameObject.TryGetComponent<ActionOnTouch>(out action))
{
Debug.Log("will pass " + trueFalse.ToString());
action.DoIt(trueFalse);
if (trueFalse)
{
trueFalse = false;
Debug.Log("setting to " + trueFalse.ToString());
}
else
{
trueFalse = true;
Debug.Log("setting to " + trueFalse.ToString());
}
}
else
{
Debug.Log("object has no action");
}
}
else
{
Debug.Log("nothing touched");
}
}
}
}
}
ActionOnTouch is placed on objects that have colliders. I have a single cube that has this script on it in my test scene.
[System.Serializable]
public class BoolEvent : UnityEvent<bool>
{
}
public class ActionOnTouch : MonoBehaviour
{
public BoolEvent boolEvent;
private void Start()
{
if(boolEvent == null)
{
boolEvent = new BoolEvent();
}
}
public void DoIt(bool highLow)
{
Debug.Log("invoker received and passed " + highLow.ToString());
boolEvent.Invoke(highLow);
}
}
The following script is what is registered using the Inspector.
public class testRegistrant : MonoBehaviour
{
public void RegisterThis(bool highLow)
{
Debug.Log("registrant received " + highLow.ToString());
}
}
Everything but the value that the registered function receives behaves as expected. The registered function always receives false no matter what.
Example execution:
User touches the cube.
Logcat: will pass True
Logcat: invoker received and passed True
Logcat: registrant received False
Logcat: setting False
User touches the cube
Logcat: will pass False
Logcat: invoker received and passed False
Logcat: registrant received False
Logcat: setting True
and so on back and forth…
What am I doing wrong?