I have a problem with a game that I'm creating in Unity. The player controls a character that is getting attacked by a horde of zombies. I've created a spawner for all the zombies and that works great, the only problem is that once the player kills one zombie all the zombies disappear from the gameworld. I've posted the enemy script that is attached to each zombie below. I can't work out why every zombie is destroyed instead of just the one that has been attacked. Any help would be great!
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public static float Damage = 10.0f;
public static float Health = 10.0f;
public Transform target;
public float Speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Destroy the enemy if it's health reaches 0
if(Health <= 0){
Destroy(this.gameObject);
Debug.Log ("Enemy Destroyed!");
}
//Constantly move the enemy towards the centre of the gamespace (where the base is)
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
The way the scene is set up is that I have an empty game object that contains a series of position objects and a spawner script that places the enemy sprite into the position object. This all seems to work fine but I can't find whats causing them to all disappear.
The problem is that you have declared Health as a static variable. This means Health will have the same value across all of your enemy instances. Declare health like this instead:
public float Health = 10.0f;
This way, each instantiated enemy will be able to have its own unique Health value.
Related
Hey I just want my bullet to destroy itself when it touch Ground i tried to destroy after 2 seconds but it has the same problem That's My Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBullet : MonoBehaviour
{
GameObject target;
public float speed;
Rigidbody2D bulletRB;
void Start()
{
bulletRB = GetComponent<Rigidbody2D>();
target = GameObject.FindGameObjectWithTag("Player");
Vector2 moveDir = (target.transform.position - transform.position).normalized * speed;
bulletRB.velocity = new Vector2(moveDir.x, moveDir.y);
Destroy(this.gameObject, 2);
}
}
Destroy the bullet object using the Destroy method.The bullet is destroyed after flying a certain distance.
public float speed;
public float destoryDistance;
private Rigidbody2D rg2d;
private Vector3 startPos;
// Start is called before the first frame update
void Start()
{
rg2d = GetComponent<Rigidbody2D>();
rg2d.velocity = transform.right * speed;
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
float distance = (transform.position - startPos).sqrMagnitude;
if (distance > destoryDistance)
{
Destroy(gameObject);
}
}
Use OnCollisionEnter() to destroy to bullet
void OnCollisionEnter(Collision collider)
{
if (collider.GameObject.tag == "Ground")
{
Destroy (this.GameObject)
}
}
What's happening here is that this function gets called every time it collides with an object, so we put the destroy code here. It takes the collider as a parameter, and then checks if the GameObject has the tag "Ground", and if it does, destroy itself.
Note that you will also have to add a tag to your ground objects in the hiearchy. You can name them anything else too, but make sure to change "Ground" in the code when you do set the tag to anything other than it.
You will probably also have other colliders like walls in your game so you should make a universal tag that destroys bullets and name it something like "Destroy Projectiles" or something.
Edit: You can have multiple functions that destroy the GameObject.
I am trying to build a flappy bird like game and I am trying to spawn enemy birds and gold coins so I have written the C# code and the made the prefabs, but when I run the bird and the coins are not respawning.
This is the respawn code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPlayer : MonoBehaviour
{
public GameObject GameObjectToSpawn;
private GameObject Clone;
public float timeToSpawn = 4f;
public float FirstSpawn = 10f;
// Update is called once per frame
void Update()
{
FirstSpawn -= Time.deltaTime;
if (FirstSpawn <= 0f)
{
Clone = Instantiate(GameObjectToSpawn, gameObject.transform.localPosition, Quaternion.identity) as GameObject;
FirstSpawn = timeToSpawn;
}
}
}
screenshot of unity:
This where i am respawning the first enemy bird:
From your second screenshot it seems to be spawned but way off the screen! You can still see the tiny little island in the bottom left corner.
You thought seems to be that you have to spawn it in the Canvas pixel space using the spawn point's localPosition. But this is not the case since Instantiate places it into the scene root (without any parent) with absolute world-space position into the scene.
You should rather actually place the spawn point to the absolute world position where the spawn should happen and rather use
Clone = Instantiate(GameObjectToSpawn, transform.position, Quaternion.identity);
Btw no need for the as GameObject since Instantiate already returns the type of the given prefab.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveProjectile : MonoBehaviour
{
public Rigidbody2D projectile;
public float moveSpeed = 10.0f;
// Start is called before the first frame update
void Start()
{
projectile = this.gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
projectile.velocity = new Vector2(0,1) * moveSpeed;
}
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.name == "Enemy"){
gameObject.name == "EnemyHeart5".SetActive(false);
}
if(col.gameObject.name == "Top"){
DestroyObject (this.gameObject);
}
}
}
This is the code to my player projectile. On collision i tried to reference it to a game object i have called playerheart and it doesnt seem to work out the way i wanted it to.
Im trying to make a health system where if my bullet collides with the enemy game object the health would decrease by one. Im pretty new to Unity and im confused on how to target the hearts when the bullets collide.
I'm assuming "EnemyHeart5" is a GameObject inside Enemy as child gameobject. Correct?
Issue here is when the collision takes place, it recognize "Enemy" gameobject and won't have access to "EnemyHeart5" for disabling it. I'd suggest you to add simple EnemyManager script into your enemy which manages your enemy health and health related gameobject (ie. EnemyHearts which you are displaying). When collision takes place, access that EnemyManager component and change health value.
void OnCollisionEnter2D(Collision2D col){
if(col.gameObject.tag == "Enemy"){
col.gameObject.GetComponent<EnemyManager>().health =-1;
}
Now, in the update method of EnemyManager you check the health value and disable EnemyHealth5 component.
Also, use "tag" in collision instead of "name". name will create issues when you have multiple enemies in the game. Make sure you add tag in enemy gameobject if you are using it.
Hope this helps, let me know how it goes.
I am making a simple 2d shooter in unity. I have made a prefab for my weapons and a script to shoot. When I enter the game mode I can see the bullet objects being created, but the bullets don't show on the screen. When I pause it and enter the scene mode they show (most of the time) any idea what could be causing this??
Here is the various settings on my bullet :
Thanks in advance for your help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
//variable to handle what progectile to spawn
public GameObject projectile;
//from where does the bullet coem from
public Transform shotPoint;
//How much time should be taken between shots
public float timeBetweenShots;
//time to shoot another bullet
private float shotTime;
// Update is called once per frame
private void Update()
{
//Callculating the the current mouse position to the current weapon position
//Input.mouse position returns a screenpoint
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = rotation;
//if the left mouse button is pressed
if(Input.GetMouseButton(0)){
//if the current time in the game is greater than the shot time
if (Time.time >= shotTime)
{
//shoot projectile
Instantiate(projectile, shotPoint.position, transform.rotation);
//recalculate shot time current time + time between shots
shotTime = Time.time + timeBetweenShots;
}
}
}
}
Check the order layer if you're by mistake not covering your bullets with the background image. Just make your bullet prefab layer higher then background equivalent.
Moreover, move the background node out of the scope of Player (currently you have it in the Player node), it should be equally set as your Main Camera and Player nodes in the tree. Then check the layering order and make sure order value in background is the lowest of all of your sprites.
Basically you are creating bullets inside of the weapon thats why you are not able to see your bullets. I create simple scene and adding sphere as a bullet then I realized sphere spawning in the gun(for me in the cube). If you will adding force everything will be okay.
Assume the shootPoint is somewhere over the gun barrel,
Instantiate(projectile, shotPoint.position, transform.rotation);
You should give them force,
GameObject projectile= Instantiate (prefab, position, rotation) as GameObject;
rb = projectile.GetComponent<Rigidbody>();
rb.AddForce (direction * speed);
Dont forget to add rigidbody to the bullet
Ok - I'm super new at Unity (just learning for fun) and wanted to have an enemy cube fall as the player gets within 15 on the Z. I can get the rigidbody function of the enemy cube to 'sleep' but then when I get within 15 or less, it will not awaken and start to fall. Can you help me with my code? The Debug.Log is telling me what I want as I run it, but the rigidbody is not reactivating on the enemy cube. Sorry if this is a super simple request...just trying to learn!
using UnityEngine;
public class activatefall : MonoBehaviour
{
public Transform Player;
public Rigidbody rbgo;
private float coolnumber;
private float badtogood;
// Update is called once per frame
void FixedUpdate()
{
coolnumber = transform.position.z;
badtogood = coolnumber - Player.position.z;
Debug.Log(badtogood);
if (badtogood < 15f)
{
rbgo.WakeUp();
Debug.Log("Falling!");
}
else
{
rbgo.Sleep();
Debug.Log("Frozen");
}
}
}
If you want a Rigidbody to be stopped and then fall, you can just use rbgo.useGravity = false/true.
There are other ways though, you can play with RigidbodyConstraints, making the Rigidbody freeze in Y axis and then remove this constraint.
If you want to stop a Rigidbody completely after it moves, you can just do rbgo.constraints = RigidbodyConstraints.FreezeAll or rbgo.velocity = Vector3.zero (and then, if you want to disable the gravity, you do rbgo.useGravity = false.
You can also use transform.position and/or transform.Translate if you don't want to deal with the Rigidbody itself.