- Home /
Prefab Objects all reacting to the collision of one
still pretty new to unity so I might be missing something simple here but... I am making a simple platformer and on a few of my levels I am putting in some enemy's(from a prefab) which will kill the player on contact and on contact with the world will bounce and go the other way. Only for some reason they all seem to react as if they've hit the world at the exact same time, even if only one of them has hit something, resulting in enemy's moving back and forward without hitting anything because the enemy's on either ends of the line are hitting. My code is below and I just cant understand why this is happening. As said probably just missing something simple but would appreciate any help.
using UnityEngine;
using System.Collections;
public class EnemyBasic : MonoBehaviour {
public static float maxspeed = 5f;
public bool facingright = true;
public AudioClip[] audioClip;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
rigidbody2D.velocity = new Vector2 (maxspeed, rigidbody2D.velocity.y);
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "World")
{
Debug.Log ("World hit detected");
maxspeed *= -1;
}
else if(other.gameObject.tag == "Player")
{
Debug.Log ("player hit detected");
EnemyPlaySound (0);
Destroy(other.gameObject);
Application.LoadLevel(Application.loadedLevelName);
}
}
void Flip()
{
facingright = !facingright;
Vector2 thescale = transform.localScale;
thescale.x *= -1;
transform.localScale = thescale;
}
void EnemyPlaySound(int clip)
{
audio.clip = audioClip [clip];
audio.Play ();
}
Ah, as said still pretty new to C so was wondering what exactly the static word did, however is there a way to fix the problem without changing the word static, or else another way to allow the variable to be accessed from another script
You access components on other objects using GetComponent(), not static
. Learn how to use it - you'll need it a lot :) http://unity3d.com/learn/tutorials/modules/beginner/scripting/getcomponent
Answer by tanoshimi · Feb 13, 2015 at 06:59 AM
Because you've declared maxspeed as static
, set by the class rather than an instance of the class.