jh.fards
jh.fards

Reputation: 11

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")?

Upvotes: 0

Views: 1667

Answers (2)

Anthony Fasano
Anthony Fasano

Reputation: 71

if you got two collider (player and object who collide the player) you can convex the collider and set isTrigger to true

Then call the function OnTriggerEnter()

void OnTriggerEnter(Collider other) {
    Debug.Log(other.name);
}

Upvotes: 0

Clonkex
Clonkex

Reputation: 3637

Well you should definitely go through some tutorials before continuing since you don't seem to know even very basic stuff, but to at least point you in the right direction, you would do something like this (assuming C#, not UnityScript):

void OnCollisionEnter(Collision collision)
{
  int numberOfCollidedObject = collision.gameObject.GetComponent<objectsScriptNameHere>().variableNameHere;
  Debug.Log(numberOfCollidedObject);
}

How did I know how to do that? I looked at the documentation. I can see that when OnCollisionEnter is called it's passed a variable of type Collision. It's hyperlinked in the documentation, so I clicked on Collision and found that it contains a variable called gameObject that contains a reference to the game object of the collider we just hit. I happen to know that to get into another script, you called GetComponent<scriptName>(), and from there any public variables and functions can be accessed.

Upvotes: 1

Related Questions