Accessing variables from objects/scripts

OK, we are entering serious noob territory here so be fore warned. I want to be able to play different “walk” sounds based on the object that the player is colliding with.

I have a script containing variables attached to object 1, and I want to be able to read those variables and use them in object 2 when both objects are colliding.

I have the following in a script for object 1 (the floor object):

var materialType = "wood";

and I have the following in a script in object 2 (the Player):

var walkSound_default: AudioClip;

private var collisionOverlap=false;
private var playsound: AudioClip;
private var collObjectType="default";


function Update () {

   if(collisionOverlap==true){	
      if (GetComponent(ThirdPersonController).moveSpeed>0.3){
      playsound=walkSound_default;
      if (collObjectType=="wood"){		 playsound=collObject.gameObject.GetComponent(Sound_object_collision).walkSound;		
      }
      PlayWalkSound(playsound, transform.position, 1);
}
	collisionOverlap=false;
}


// CHECK FOR COLLISION
function OnCollisionStay(collision : Collision) {
   if (collision.relativeVelocity.magnitude>3){
		collisionOverlap=true;
collObjectType=collision.gameObject.GetComponent(Sound_object_collision).materialType;
	}

}


//PLAY SOUND
function PlayWalkSound (clip : AudioClip, position : Vector3, volume : float)
{
   if (!audio.isPlaying){
      audio.clip = clip;
      audio.volume = volume;
      audio.Play();
   }
}

There are two lines that give me a problem: the “playsound=” declaration in Update, and the “collObjectType=” line under the collision check.

Both of these lines give me NullReferenceExceptions.

This is a piece of code I’ve been staring at for a few days now. I’m giving up my ego and admitting that I just don’t have a clue. Anyone care to offer some advice?

We already have dozens of topics on this subject…I think you can find your answer in one of those. Really, there are dozens of topics on this subject. :slight_smile: Plus there’s the page in the docs about accessing other game objects.

–Eric

Hmm… well yes I have been searching, but nothing that I’ve found addresses my problem specifically.

I’ve learned how to call an object using Find…

collObjectType = GameObject.Find("Cube").GetComponent(Sound_object_collision).materialType;

the above works fine, however I want to be able to find the variables in the collided game Object, and I won’t know what that object is until collision. Everytime I change the code to reflect this I end up with problems.

function OnCollisionStay(collision : Collision) {
	if (collision.relativeVelocity.magnitude>3){
		collisionOverlap=true;
		collObject=collision.gameObject; 
	}
}


collObjectType = collObject.GetComponent(Sound_object_collision).materialType;

…trying saving the collided object into a gameObject reference and then trying to find info on collObject returns errors.