how to get variables from a script my player is colliding with?

so i have my player standing next to a cube. the player has a script, which is empty aside from an int which is 43. the same applies to the cube except the int in the cube’s script is 42. how do i get(or detect) the int in the cube’s script and print it in the console using OnCollisionEnter(or OnTriggerEnter if it is better) like this: (“the cube has the number 42”)?

There are a few ways of doing this. The easier and dirtier way would be to attach a script to your cube with a OnTriggerEnter() method, however, this would trigger every time your cube collided with something, not needing to be a player.

The better and slightly more abstract way of doing this so it’s exclusive to the player would be to attach a new script to the player (or create a OnTriggerEnter()) method where you make your cube gameobject a parameter. From there on, you can first check if the object you collided with is your Cube (by checking tags, for an example), and then since by colliding you are passing the reference to your player’s script, you can load its script if you know the script’s name (type), and Debug.Log the number.

The code would look something like this:

void OnTriggerEnter2D (Collider2D other)
	{
		CubeScript cs = other.GetComponent<CubeScript>();

		if(other.tag == "Cube")
		Debug.Log("the cube has the number " + cs.integer);
	}

If you have 3D colliders, just remove the 2D (I tested this in a 2D game, but it should work the same, really). Also, I presume your Cube has the tag “Cube”, and that the integer in the cube’s script is defined as public int integer = 42;.