- Home /
How do I prevent my original projectile object from being destroyed?
I have a script for a projectile but there are two problems.
After the Destroy Timer ends, the actual game object in the scene gets destroyed and I can no longer spawn the item. The thing is, I had a previous projectile script which is exactly the same but for some reason, in the other project which is an older version of Unity, doesn't have the prefab displayed as a game-object so the projectile works fine. Here, I cannot get the game-object to be removed from the hierarchy so it doesn't get destroyed as one.
When I fire the projectile before it gets removed from reality, it simply flashes in and out of existence at the spawn point but doesn't actually move.
Here is the code:
using UnityEngine;
public class Projectile : MonoBehaviour { public float speed = 2f;
//This is our timer until destruction
public float DestroyTimer = 4f;
// Update is called once per frame
void Update()
{
transform.Translate(new Vector3(0f, 0f, speed));
DestroyTimer -= Time.deltaTime;
if (DestroyTimer <= 0f)
{
Destroy(gameObject);
}
}
}
This is the code for my PlayerController, which the Projectile script is connected to. The projectile segment is the last one, at the very bottom.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI;
public class PlayerControl : MonoBehaviour {
//We will need to have access to our player itself.
public Transform Player;
public Text ScoreCounter;
public Text HealthCounter;
public AudioSource healthSound;
//Ball Projectile
public GameObject ShotgunPellet;
//Spawn Location of the ball
public GameObject PelletSpawn;
//Let's also create some publically accessible movement values while we're here.
public float rotationSpeed = .1f;
public float movementSpeed = .2f;
public float jumpForce = 10f;
public Image PlayerHealth;
int score = 0;
public void AddScore()
{
score++;
ScoreCounter.text = "Score: " + score;
if (score > PlayerPrefs.GetInt("HighScore"))
{
PlayerPrefs.SetInt("HighScore", score);
}
}
// Use this for initialization
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
HealthCounter.text = "Health: " + startingHealth;
}
int health = 5;
int startingHealth = 5;
void changePlayerHealthBar()
{
PlayerHealth.transform.localScale = new
Vector2((float)((float)health / (float)startingHealth), 1f);
}
void OnCollisionEnter(Collision collision)
{
if (collision.collider.gameObject.tag == "Health")
{
AudioSource sound = Instantiate(healthSound, transform.parent);
sound.Play();
health ++;
HealthCounter.text = "Health: " + health;
}
if (collision.collider.gameObject.tag == "Enemy")
{
health--;
HealthCounter.text = "Health: " + health;
changePlayerHealthBar();
}
if (health <= 0)
{
Debug.Log("You lose");
ExitToMenu();
}
}
void ExitToMenu()
{
SceneManager.LoadScene("Menu");
}
// Update is called once per frame
void Update()
{
//Just to get an intro to how this works, we will start by just rotating the player around so they can see more of the screen
//Since we just want to rotate around while standing straight up, we want to only rotate in the Y-Axis
//Player.Rotate(0f, rotationSpeed, 0f);
if (Input.GetKey(KeyCode.W))
{
//Move us one movementSpeed into the forward direction
Player.Translate(0f, 0f, movementSpeed);
}
if (Input.GetKey(KeyCode.A))
{
//Move us one movementSpeed into the left direction
Player.Translate(-movementSpeed, 0f, 0f);
}
if (Input.GetKey(KeyCode.S))
{
//Move us one movementSpeed into the backward direction
Player.Translate(0f, 0f, -movementSpeed);
}
if (Input.GetKey(KeyCode.D))
{
//Move us one movementSpeed into the right direction
Player.Translate(movementSpeed, 0f, 0f);
}
if (Input.GetKeyDown(KeyCode.Space) && GetComponent<Rigidbody>().velocity.y > -.3f && GetComponent<Rigidbody>().velocity.y < .3f)
{
//This will give us a RigidBody component that is assigned to the same object as this script
Rigidbody PlayerRigidBody = GetComponent<Rigidbody>();
PlayerRigidBody.AddForce(0f, jumpForce, 0f);
}
Player.Rotate(0f, Input.GetAxis("Mouse X") * rotationSpeed, 0f);
//GetMouseButtonUp means the left click was released on this frame. This is what we want for a "click"
if (Input.GetMouseButtonUp(0))
{
//GameObject.Instantiate creates a new "Instance" of the object we pass it, in this case that's our ball
//By overriding Instantiate we can assign a parent transform for our ball
GameObject newShotgunPellet = GameObject.Instantiate(ShotgunPellet, PelletSpawn.transform);
newShotgunPellet.transform.localPosition = Vector3.zero;
newShotgunPellet.transform.SetParent(transform.parent);
}
}
}
Apologies for the massive code wall.
Answer by rampagingswine · Feb 29, 2020 at 06:57 PM
Obligatory: The coding headers were kept in the text wall instead of the code tab for some reason.
Correction: The projectiles spawn and simply fall to the floor and roll around for a few seconds and do despawn after the given time for the destroy object command, but the original game-object gets destroyed, preventing me from spawning anymore and that, specifically, is the problem I'm having.
Your answer
Follow this Question
Related Questions
Instantiate creating object far off the screen 0 Answers
How do I get the Player's Health Script as Component? 1 Answer
Projectile over network problem 1 Answer
How to destroy bullet upon colliding with another object instead of bouncing off of it 3 Answers
Bullet Always fires down the Z Axis using Bullet Drop/Trajectory Formula? 1 Answer