Enemies Floating Away At Runtime

After adding the AddRigidbody component to the script, even after setting it up to ensure gravity is turned off with the rb.useGravity = false; my older placeholder cube enemies start slowly driving apart from each other when I hit play.

This was initially happening with my new prefab enemy before where it would slowly rotate. However, after I slightly moved the ship, it stopped moving. The cubes are still moving though.

Everything is set up the same as Rick unless I’m missing something somewhere?

Can you post a screenshot of the inspector window with the GameObject in question selected? A code snippet would help too.

Hi HaggardMelon,

In addition to what Raistlin_Majere suggested, check if there are any colliders near the enemies which might be pushing the enemies away. A common mistake is a collider attached to the camera.

Okay here’s the code from my Enemy C# script and a screen shots of the inspector for one of the cubes exhibiting the issue before and during runtime.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Enemy : MonoBehaviour

{

[SerializeField] GameObject deathVFX;

[SerializeField] GameObject hitVFX;

[SerializeField] Transform parent;

[SerializeField] int scorePerHit = 15;

[SerializeField] int hitPoints = 4;



ScoreBoard scoreBoard;

 void Start()

{

    scoreBoard = FindObjectOfType<ScoreBoard>();

    AddRigidbody();

}

void AddRigidbody()

{

    Rigidbody rb = gameObject.AddComponent<Rigidbody>();

    rb.useGravity = false;

}

void OnParticleCollision(GameObject other)

{

    ProcessHit();

    if (hitPoints <1)

    {

        KillEnemy();

    }

}



void ProcessHit()

{

    GameObject vfx = Instantiate(hitVFX, transform.position, Quaternion.identity);

    vfx.transform.parent = parent;

    hitPoints--;

    scoreBoard.IncreaseScore(scorePerHit);

}

void KillEnemy()

{

    GameObject vfx = Instantiate(deathVFX, transform.position, Quaternion.identity);

    vfx.transform.parent = parent;

    Destroy(gameObject);

}

}


InspectorCubeTest_Runtime

The enemies do not have a collider attached, do they? If they don’t have any, they could either be moving away due to some code or due to the timeline animation. That’s hard to tell just by looking at the code. Have you already tried to add Debug.Logs to your code to see what is going on during runtime?

Privacy & Terms