I have multiple empty box colliders with a script attached to it. I want the speed of a car to change every time it hits one of these colliders. The speed has to be editable in the script attached to each collider so I can put in a unique amount for the speed.
Problem is, I want to access the variable for speed in a seperate script attached to the car. It was my understanding that a variable must be static to do this, but you cannot edit a static variable.
So how would I go about doing this?
I assume you mean you have some triggers which the car should go through? In that case, you could add something like this to a script on the triggers GameObjects:
public void OnTriggerEnter( Collider other )
{
CarSpeedScript theCarSpeedScript;
if( other.gameObject.tag == "TheCar" )
// Just an example of how you could identify the car
{
theCarSpeedScript = other.gameObject.GetComponent( typeof( CarSpeedScript ) ) as CarSpeedScript;
if( theCarSpeedScript != null )
{
theCarSpeedScript.speed = theNewSpeedValue;
}
else
{
Debug.LogError( "The car has no speed script attached!" );
}
}
}
This topic has come up dozens of times, twice in the last week in fact.
http://forum.unity3d.com/viewtopic.php?p=123408
http://forum.unity3d.com/viewtopic.php?t=18978
It’s also covered well in the documentation.
http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
Essentially what you want to do is expose a non static variable for each collider containing your speed modification metric. If you use static for this, then they will all share the -same- value as detailed in the first link I provided. That doesn’t sound like it’s what you want!
Then as you have a link to your ‘car’ via the collision info, use that to grab a link to it’s speed script and modify the variable you want.
Alternately, if there is one one car in existence you can cache the link to the car on startup or expose a variable to link the car in the inspector beforehand. That’s a function of how many colliders you really have.
I read through the posts as well as documentation and am still a bit confused.
If I have a script named Speed.js attached to box colliders with separate, editable, speeds. Then I have a gameobject called car with a script attached telling it to drive called drive.js, why wouldn’t the following work.
In Speed.js
var speed = 10;
In drive.js
var speed : Speed;
CarSpeed = GetComponent(Speed).speed;
Rigidbody.AddRelativeForce (CarSpeed, 0, 0);
[/code]
Scripts are components themselves and attach to GameObjects - not other components. Your Speed component is attached to GameObjects which also have box collider components attached.
Your code in drive.js should be changed to the following and will only work if the two scripts are attached to the same GameObject as specified by the GetComponent documentation:
var CarSpeed = GetComponent(Speed).speed;
Rigidbody.AddRelativeForce (CarSpeed, 0, 0);