Enemy Shooting

I understood that you want the enemy to kill the player. However, the player does not get killed.

My problem is the following: I already asked you twice to check the Player class. I neither got an answer nor have I ever seen the class that is responsible for processing the collision happening to the player game object. I don’t even know if the messages in your console are related to my questions.

Before I’m repeating myself again, I’d like you to write down the description of the problem you want to solve. Plus the next steps you are going to take. I’d like to see a list.

I already suggested to you all the relevant steps in this thread as well as in the private messages. I also solved some of the issues for you and uploaded the fixes to your Git repository.

1 Like

Nina, I sorry I don’t want to be a bother the reason why I didn’t answer you is that, I thought I already answered you about the player class. In fact, I don’t know where is the player class. I’m a hopeless case I’ll never get this to work. It wouldn’t make sense to explain what I trying to do then I would be repeating myself. I know you fixed some issues in the repository I already download that fixes to my desktop. for some reason, the enemy doesn’t shoot and kill the player anymore. Nevermind the health bar not working. No worries Nina.

Thank you for all you did.

1 Like

I’m sure you will get this work if you stick with it. You’ve always been polite, and you’ve worked on this for months. Other people would have given up after a few minutes. That’s why I’m still helping you because I want you to make this work.

It wouldn’t make sense to explain what I trying to do then I would be repeating myself.

The problem is the following: You had a problem with the GameController. Then, suddenly, you had another problem. I don’t even remember if you ever told me whether the initial issue is fixed. Since I reply to lots of students on a daily basis, I sometimes lose track of a student’s current issue when there are multiple issues in the same thread. For this reason, I asked you to briefly describe your current problem. It’ll help me because I don’t have to guess what your issue is/was. And it’ll help you because we can focus on your current issue.

When I want to solve an issue in my project, I always break the problem down into single, managable tasks/problems. I complete each task step by step, and that automatically fixes the initial problem. (Hopefully.)

Your health bar is a complex problem. You already have the relevant components, which is half of the solution. However, they don’t interact with one another correctly yet, which is the missing half. Do you really want to give up even though you already solved half of your problem?

Here are a few steps:

  1. Click on the Player game object.
  2. Check its Inspector.
  3. Does its Inspector have a script attached that is supposed to handle the incoming collision? If not, add one.
  4. Open that script.
  5. Check the spelling of the OnParticleCollision method. Compare it to the API, not to my answer.
  6. Add a meaningful Debug.Log to that method.
  7. Test your game.
  8. Does the message appear? If not, check the collider of the Player game object. Is it enabled? Is it a non-trigger? If so, continue with step 9.
  9. Make sure the “Player” tag attached to the same game object as the Player’s collider.
  10. Make sure the enemy’s particle system interacts with the “Player” layer.

Does the message you wrote in step 6 finally appear?

If in doubt, print out my list and tick off the single tasks once you completed them. Do not skip any step.

Collision detection is always a bit tricky because neither you nor I have all the information about what is happening inside Unity. Most of Unity is not open-source.

Once the collision message appears, your healthbar might work. If it does not, you will have to check if the damage is processed correctly. This is fairly easy to debug because this does not have anything to do with Unity but with your script(s) only. You know your scripts because you wrote them. They represent your logic, and there are no secrets.

1 Like

Nina, Thank you, I have plenty to do today by this evening I will start work on this hopefully I will get it working.

I just went through the list all the player tags are assigned properly the enemy particles are tagged to the player in the collision settings of the particles system for the enemy particles. Except for the health bar portion test, we did this portion if you see in the console the portions we tested in the health bar are all called. I need to know I my debug codes are accurate? because I get messages in the console stating they are all called!.

Enemy.cs

void OnParticleCollision(GameObject other)
    {
        ProcessHit();
        if (hits <= 1 && gameObject.activeSelf)
        {
            KillEnemy();
        }
        Debug.Log(GetInstanceID() + ": OnParticleCollision() called.");
        Debug.Log("OnParticleCollision!");

    }
    private void ProcessHit()
    {
        gameController.AddScore(scorePerHit);
        hits = hits - 1;
        // todo consider hit FX

        Debug.Log(GetInstanceID() + ": ProcessHit() called.");
        Debug.Log("Process Hit!");
    }

    private void KillEnemy()
    {
        GameObject fx = Instantiate(deathFX, transform.position, Quaternion.identity);
        fx.transform.parent = parent;

        gameObject.SetActive(false);

        gameController.DecreaseEnemyCount();

        Destroy(gameObject);

        Debug.Log(GetInstanceID() + ": KillEnemy() called.");
        Debug.Log("Killed Enemy!");
    }
}

Projectiles.cs

 void Shoot()
    {

        if (onRange)
        {

            Rigidbody enemyGun = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
            enemyGun.AddForce(transform.forward * enemyGunImpulse, ForceMode.Impulse);
        }

        Debug.Log(GetInstanceID() + ": Shoot() called.");
        Debug.Log("Shoot Player!");
    }
1 Like

Hi Guys,

I’ve jumped in on this thread as there has been a lot of issues in here that stem from a lack of understanding and knowledge at this level.

Now before i go any further its VERY important that you understand you havent failed and you are not a lost cause. I have been where you are and i know exactly what you are trying to do.

I will tell you outright and honestly that doing what you are doing you will fail if you continue.

Now for the reasoning.

Some of the basics i think you havent grasped before moving on and that is the issue here as you are building uncertainity on top of uncertainity and then it just becomes a confusing mess (believe me i know!)

What i suggest here is draw a line under it for now and head to the unity website.
Theres a whole host of tutorials there that cherry pick things like adding a health bar that you can use but i suggest running those base tutorials like the laser defenders there to push the knowledge that you have done in our past sections.

Theres even a player health script project there as well.

For future reference i think you need to spend a bit more time in previous sections to solidfy the knowledge and make the project your own to expand your learning.

Take my game for example i started with a tutorial simply rolling a ball around and picking up cubes.

2 months later because i did the process i mention above the below is the result

You get out what you put in and this doesnt even use health!

2 Likes

Hi irresistiblejelly, thank you for your advice when I search for tutorials in Unity I come to a roadblock because my keyword search skills are not that good. But I will for sure keep trying to find the tutorials on the health bar and getting the enemy projectiles to kill the player object. yeah I think its best I leave the game alone. Thanks again, later today I will check out your game it looks like a lot of fun :slight_smile:

2 Likes

I need to know I my debug codes are accurate?

What makes you think that the code you posted is inaccurate? The messages appear, so the methods get called. This means: This code works. I suspect that the problem is neither the Enemy class nor the Projectile class but a misinterpretation of the messages in your Console.

Is Enemy.cs attached to the Player Ship?

Maybe Marc is right. Watch a few tutorials on the Unity website, on Youtube and rewatch some of the relevant lectures in our Unity 3D course, e.g. “Tagging Game Objects As Friendly” (currently #50) and “Detecting Particle Collisions” (currently #100).

Bob Tabor’s free C# course could also be helpful to get a better understanding of C# and how instances interact with one another:

2 Likes

I took this course already Nina, and no the enemy.cs is not attached to the player Ship it is only attached to the enemies like the course with Rick and Ben suggested. I only thought the code I added for debugging the class/methods you mentioned where not accurate because you didn’t respond the first time I asked about it I was merely trying to confirm what I done.as you know i get a bit thrown off very fast when it comes to code. :confused:

So I will look at these tutorials in Unity if I can find them. Thank you for your support I know and understand I can be difficult to work with. I don’t want to move on the the Zombie FPS game with Ben and Sam with the Unreal platform until I get my goals done with this game. I think it would be a smart move to wait even though I started the game. My goals are to make that game become my Portal Reign Investigation FPS. With different assets I mean that I want to buy and import from Daz3D. But I’m along way away from getting that game started if I can’t grasp this game and get it done. Hopefully, I find these tutorials and fix this issues with Portal Reign my current game. :slight_smile:

1 Like

You are welcome. And don’t worry. As aforementioned, you have always been polite and ambitious, which is more important to me than anything else.

Good luck! :slight_smile:

2 Likes

I just wanted to help you a little further and also echo what Nina has already said.
It doesnt matter how stuck you are and how frustrating it can be as believe me we do understand! Being polite goes a very long way these days and we always help people to the best of our abilities.

These were the tutorials i was referring to, Some of them are in older versions but you can just get that version from the archives and add it to the hub. Some of them are more recent though but that site is a wealth to search especially if you want to refresh on a specific topic as modules are quite well labelled.

I wish you the best of luck and i hope this helps with guiding you

Edit :- I’m subscribed to a site called game institute now i am not suggesting you do as well but they do a basic c# course not tied to a game engine so this may help as well to find one on Udemy or a you tube series. It may or may not help

2 Likes

Hi irresistiblejelly, Oh! I thank you for this c# advice I will for sure look into this I believe I would benefit from it and I will work on these tutorials starting tonight. your advice is always welcomed :slight_smile:

2 Likes

Thanks :slight_smile:

1 Like

I apologize but none of the above tutorials helped me so I’m back to square one. If I already determined the playerhealth/projectiles.cs is called. Then itsn’t safe to say it is not the scripts but something else preventing the projectiles from destroying the playership object?

1 Like

If I remember correctly, you rotated the enemy towards the player. Maybe the projectiles are missing the player. No collision, no method call.

Disable the rotation script and test your scripts in a simplified environment. Rotate the enemy manually to ensure that the particles hit the player’s collider. The player script is supposed to log a message into your console when the player collider is hit.

2 Likes

I will work on this.

1 Like

Hi Nina, I created an enemy attack .cs I’m not sure if I should abandon this script of keep it in the game I receive this error:

NullReferenceException: Object reference not set to an instance of an object
EnemyAttack.Update () (at Assets/Scripts/EnemyAttack.cs:69)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAttack : MonoBehaviour
{
    [SerializeField] GameObject deathFX;
    [SerializeField] Transform parent;
    [SerializeField] GameObject[] enemyGuns;
    public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    public int attackDamage = 10;               // The amount of health taken away per attack.
    Animator anim;                              // Reference to the animator component.
    GameObject player;                          // Reference to the player GameObject.
    PlayerHealth playerHealth;                  // Reference to the player's health.
    bool playerInRange;                         // Whether the player is within the trigger collider and can be attacked.
    float timer;                                // Timer for counting up to the next attack.


    // Start is called before the first frame update
    void Start()
    {
        AddSphereCollider();
    }

    private void AddSphereCollider()
    {
        Collider sphereCollider = gameObject.AddComponent<SphereCollider>();
        sphereCollider.isTrigger = false;
    }
    void OnCollisionEnter(Collision collision)
    {
        print("Player shot something");
    }
    void OnTriggerEnter(Collider other)
    {
        // If the entering collider is the player...
        if (other.gameObject == player)
        {
            // ... the player is in range.
            playerInRange = true;
        }
    }


    void OnTriggerExit(Collider other)
    {
        // If the exiting collider is the player...
        if (other.gameObject == player)
        {
            // ... the player is no longer in range.
            playerInRange = false;
        }
    }

    void Update()
    {
        // Add the time since Update was last called to the timer.
        timer += Time.deltaTime;

        // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
        if (timer >= timeBetweenAttacks && playerInRange && playerHealth.cur_health > 0)
        {
            // ... attack.
            Attack();
        }

        // If the player has zero or less health...
        if (playerHealth.cur_health <= 0)
        {
            // ... tell the animator the player is dead.
            anim.SetTrigger("PlayerDead");
        }
    }


    void Attack()
    {
        // Reset the timer.
        timer = 0f;

        // If the player has health to lose...
        if (playerHealth.cur_health > 0)
        {
            // ... damage the player.
            playerHealth.TakeDamage(attackDamage);

            GameObject fx = Instantiate(deathFX, transform.position, Quaternion.identity);
            fx.transform.parent = parent;
            Destroy(gameObject);
        }
    }
} 
1 Like

If you need the instance to avoid the NullReferenceException, comment out the part where the enemy’s ship rotates towards the player’s ship.

1 Like

Hi Nina, I really need help I like to move on the create the zombie game but I want to complete this game please can you help me I just can’t complete it on my own. :frowning:

1 Like

I’m afraid I don’t have time to write any custom solutions. I did that a couple of months ago and made a commit to your GitHub repo. You can use the code. As far as I know, you still have the same issues I solved back then, and my solution is still not implemented in your project. If you want to complete your game and cannot do that with the help you got, you could remove the changes and keep the working game only. You can also download Ben’s and Rick’s project from GitHub and compare it to yours. Later, when you are more familiar with C# and Unity, you could reimplement your ideas.

1 Like

I Nina, can you please reach out to me when you have time I will wait I will not get back to until you have time to reach out to me if yo can . If you I don’t want to become annoying to you. Thank you hope to hear from you soon . :slight_smile:

1 Like

Privacy & Terms