Hi, I have a collision script on my Player object that detects when it collides with my other Obstacle object. They are both sitting on top of my moving Platform object. What I need to do is to stop the Platform’s Vector3.left method when Player and Obstacle collision is detected. What s the best way to do this??? None of the objects are triggers.
There are a couple of ways to do this, each depending on how exactly the logic ought to work.
Most likely: is your “obstacle” object attached to the platform (e.g. it’s a switch that works on that platform only)? Put a reference to the platform on the obstacle.
//Obstacle.cs
public class Obstacle : MonoBehaviour {
public GameObject myPlatform;
}
Now, look at the obstacle in the inspector - you’ll see a “slot” into which you can drag your Platform GameObject. From there, you can use myPlatform in any function on the obstacle script.
Ok, I’ve done that. So how can I stop the platform movement when I get a collision? Or just stop the Platform script from running all together?
Use OnCollisionEnter; if you use col.gameObject.GetComponent(), you can access scripts on the object you collided with.
What if you want to access a script on an unrelated object? And then stop a method within that script?
How unrelated?
Sorry I mean, how do I stop a script in the object I have put in the slot?.. lol sorry if this is confusing for you guys
pseudo code
class Platform
{
public boolean stopped = false; --or private is you are using the stopfunction approach
void Update()
{
if(!stopped)
{
<movementcode>
}
}
void StopPlatform()
{
stopped = true;
<other stuff that happens when the platform stops>
}
}
then to use
myPlatform.StopPlatform()
or
myPlatform.stopped = true
allowing other object to access variables without functions is a bit of a debate; you don’t have to have the StopPlatform() function, but I think it’s preferable since you can handle effects, sounds etc. in there when the platform is stopped.
or i suppose literally “stop the script” would be to set it to inactive; Unity - Scripting API: GameObject.SetActive
oOk think I got it. Thanks guys! No doubt I’ll be back …