0
votes

I have a very annoying bug, and I can't get rid of it. The situation is, that I have a parent with the following script attached, and a trigger box2d collider. It has a child, with a rigidbody2d(kinematic, gravity=0, freeze position x, and rotation z), a sprite renderer and a polygon collider (with 4 edges). My problem is, when the scene is loaded, sometimes my child objects (always random how much of them and which ones), jumps to transform.position 0,0,0.

I link the script, that is attached to the parent

using UnityEngine;
using System.Collections;

public class FallingSpikeHazard : MonoBehaviour
{
    public GameObject spike;
    private Rigidbody2D spikeRigidbody;
    [SerializeField]
    private Vector3 startPosition;

    void Awake ()
    {       
        startPosition = spike.transform.localPosition; 
    }

    void Start ()
    {
        spikeRigidbody = spike.GetComponent<Rigidbody2D> ();
        
        Helper.JustReset += ResetMe;
        Invoke ("CheckPosition", Time.deltaTime);
    }

    void CheckPosition ()
    {
        if (spike.transform.localPosition != startPosition) {
            Debug.LogError ("t1" + spike.transform.localPosition);
            spike.transform.localPosition = startPosition;
            Debug.LogError ("t2" + spike.transform.localPosition);
        }
    }

    void OnDestroy ()
    {
        
        Helper.JustReset -= ResetMe;
    }

    void ResetMe ()
    {
        spikeRigidbody.gravityScale = 0;
        spikeRigidbody.isKinematic = true;
        if (startPosition != Vector3.zero) {
            spike.transform.localPosition = startPosition;
        }
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.tag.Equals ("Player")) {
            spikeRigidbody.isKinematic = false;
            spikeRigidbody.gravityScale = 1;
        }
    }
}

Events are not called, in other hand, if I disable the script, it keeps happening. Nothing have reference to these GameObjects. I don't have animations, or animator attached.

What could cause my problem?

1
Ok guys, there is nothing wrong with the code. The problem is with the RigidBody2d Component. Basically, if you tick the fixed x or y position, it will break your game. Literally. I put a video here to show you what is the actual bug. youtube.com/watch?v=HweD8A-q34Y - BazsBazs
The solution is really simple: if you have to use fixed angles write your own script for it. for the x angle do this: public Rigidbody2d myRigidB; public float fixedX; void FixedUpdate(){ Vector2 myVeloc = myRigidB.velocity; myVeloc = new Vector2(0,myVeloc.y); myRigidB.velocity=myVeloc; transform.position=new vector2(fixedX,transform.position.y); } This script is not tested, but the solution is something like this :) - BazsBazs

1 Answers

1
votes

You need to have a Rigidbody2D component in the parent GameObject in order for the OnTriggerEnter function to be called.