Im a beginner in unity so code doesnt look great but I would appreciate any explination on how to get the variable personClicked into a different script called peopleMovement.
1 Like
This seems like a good use-case for events. Check out System.Action.
In short you add a public Action to your current script and subscribe to it in the other script (peopleMovement)
public class CameraScript: MonoBehaviour {
public event Action OnPersonClicked;
...
void Update()
{
...
OnPersonClicked?.Invoke(); // the ? prevents nullpointer issues if no other script has subscribed
}
...
}
And in the other script:
public class PeopleMovement: Monobehaviour{
public CameraScript camerascript; // don't forget to link this in the inspector
Start()
{
cameraScript.OnPersonClicked += HandlePersonClicked; // no () here
...
}
private void HandlePersonClicked()
{
Debug.Log("Person clicked");
}
...
} // end of peoplemovement
Some general comments:
- usually class names are in Pascal case: CameraScript, PeopleMovement
- using name comparisons can be error-prone (typos, changing the names does not propagate well). Better to check for attached scripts or the tag.
- public fields are usually better used as [SerializeField] private CameraScript cameraScript;. The [SerializeField] makes it possible to assign in the inspector.
1 Like