r/UnityHelp • • Jan 28 '26

PROGRAMMING How do i make projectiles deal damage

Thumbnail
gallery
0 Upvotes

I'm new to using unity so i don't understand c# that well yet and i'm trying to make the projectiles my enemies shoot deal damage to entities with health values (like the player) I'm sorry of this is too little info, but if there is anything you need to help that is not in this post i will try to provide it.

here are the codes i think are the most relevant

player health code:

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

public class playerhealth : MonoBehaviour

{

[SerializeField] private float StartingHealth;

private float health;

public float Health

{

get

{

return health;

}

set

{

health = value;

Debug.Log(health);

if (health <= 0f)

{

gameObject.transform.position = new Vector3(0f, 0f, 0f);

Health = StartingHealth;

}

}

}

private void Start()

{

Health = StartingHealth;

}

}

other entities health code:

using UnityEngine;

using System.Collections;

using System.Collections.Generic;

public class Entity : MonoBehaviour

{

[SerializeField] private float StartingHealth;

private float health;

public float Health

{

get

{

return health;

}

set

{

health = value;

Debug.Log(health);

if (health <= 0f)

{

Destroy(gameObject);

}

}

}

private void Start()

{

Health = StartingHealth;

}

}

enemy ai code:

using UnityEngine;

using System.Collections;

using UnityEngine.AI;

public class HostileAI : MonoBehaviour

{

[Header("References")]

[SerializeField] private NavMeshAgent navAgent;

[SerializeField] private Transform playerTransform;

[SerializeField] private Transform firePoint;

[SerializeField] private GameObject projectilePrefab;

[Header("Layers")]

[SerializeField] private LayerMask terrainLayer;

[SerializeField] private LayerMask playerLayerMask;

[Header("Patrol Settings")]

[SerializeField] private float patrolRadius = 10f;

private Vector3 currentPatrolPoint;

private bool hasPatrolPoint;

[Header("Combat Settings")]

[SerializeField] private float attackCooldown = 1f;

private bool isOnAttackCooldown;

[SerializeField] private float forwardShotForce = 10f;

[SerializeField] private float verticalShotForce = 5f;

[Header("Detection Ranges")]

[SerializeField] private float visionRange = 20f;

[SerializeField] private float engagementRange = 10f;

private bool isPlayerVisible;

private bool isPlayerInRange;

private void Awake()

{

if (playerTransform == null)

{

GameObject playerObj = GameObject.Find("Player");

if (playerObj != null)

{

playerTransform = playerObj.transform;

}

}

if (navAgent == null)

{

navAgent = GetComponent<NavMeshAgent>();

}

}

private void Update()

{

DetectPlayer();

UpdateBehaviourState();

}

private void OnDrawGizmosSelected()

{

Gizmos.color = Color.red;

Gizmos.DrawWireSphere(transform.position, engagementRange);

Gizmos.color = Color.yellow;

Gizmos.DrawWireSphere(transform.position, visionRange);

}

private void DetectPlayer()

{

isPlayerVisible = Physics.CheckSphere(transform.position, visionRange, playerLayerMask);

isPlayerInRange = Physics.CheckSphere(transform.position, engagementRange, playerLayerMask);

}

private void FireProjectile()

{

if (projectilePrefab == null || firePoint == null) return;

Rigidbody projectileRb = Instantiate(projectilePrefab, firePoint.position, Quaternion.identity).GetComponent<Rigidbody>();

projectileRb.AddForce(transform.forward * forwardShotForce, ForceMode.Impulse);

projectileRb.AddForce(transform.up * verticalShotForce, ForceMode.Impulse);

Destroy(projectileRb.gameObject, 3f);

}

private void FindPatrolPoint()

{

float randomX = Random.Range(-patrolRadius, patrolRadius);

float randomZ = Random.Range(-patrolRadius, patrolRadius);

Vector3 potentialPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);

if (Physics.Raycast(potentialPoint, -transform.up, 2f, terrainLayer))

{

currentPatrolPoint = potentialPoint;

hasPatrolPoint = true;

}

}

private IEnumerator AttackCooldownRoutine()

{

isOnAttackCooldown = true;

yield return new WaitForSeconds(attackCooldown);

isOnAttackCooldown = false;

}

private void PerformPatrol()

{

if (!hasPatrolPoint)

FindPatrolPoint();

if (hasPatrolPoint)

navAgent.SetDestination(currentPatrolPoint);

if (Vector3.Distance(transform.position, currentPatrolPoint) < 1f)

hasPatrolPoint = false;

}

private void PerformChase()

{

if (playerTransform != null)

{

navAgent.SetDestination(playerTransform.position);

}

}

private void PerformAttack()

{

navAgent.SetDestination(transform.position);

if (playerTransform != null)

{

transform.LookAt(playerTransform);

}

if (!isOnAttackCooldown)

{

FireProjectile();

StartCoroutine(AttackCooldownRoutine());

}

}

private void UpdateBehaviourState()

{

if (!isPlayerVisible && !isPlayerInRange)

{

PerformPatrol();

}

else if (isPlayerVisible && !isPlayerInRange)

{

PerformChase();

}

else if (isPlayerVisible && isPlayerInRange)

{

PerformAttack();

}

}

}


r/UnityHelp • • Sep 06 '25

Issue with tile palette

Post image
0 Upvotes

I can’t see the grids in tile palette


r/UnityHelp • • Jul 30 '25

how do i fix this?

0 Upvotes
if (Mouse.current.rightButton.isPressed)
{
    if (Mouse.current.rightButton.wasPressedThisFrame)
    {
        mousePos = Mouse.current.position.ReadValue();
    }
    Cursor.lockState = CursorLockMode.Locked;
    Mouse.current.WarpCursorPosition(mousePos);
    
    Vector2 lookInput = look.action.ReadValue<Vector2>();
    targetYaw += Mathf.Clamp(lookInput.x, -8, 8) * rotationSpeed * Time.deltaTime * 0.8f;
    targetPitch -= lookInput.y * rotationSpeed * Time.deltaTime;
    targetPitch = Mathf.Clamp(targetPitch, -45, 80f);
}else
{
    Cursor.lockState = CursorLockMode.None;
    if (Mouse.current.rightButton.wasPressedThisFrame)
    {
        Mouse.current.WarpCursorPosition(mousePos);
    }
}

why doesnt this work? 

and who downvoted this? why? what was the point of that? just to make it harder for me to fix my problem? who hurt you?

r/UnityHelp • • Jan 23 '25

How to start learning

0 Upvotes

im familiar with coding cuz of my speciality in highschool but unity side of c# seems so complicated and idk how to learn it deeply and master it. any suggestions?


r/UnityHelp • • Jan 02 '26

Unity glitch

Post image
0 Upvotes

My pc crashed one day, and then this happened! I've tried chatgpt so yeah. Can you help?


r/UnityHelp • • Sep 05 '26

Why can I finish my games?

0 Upvotes

Every time When I start to make some game than I can’t finish it. I can make simple mechanics but nothing more. The main reason is graphics. I’m not artist, When I start to make some sprite or 3d model, than I can’t seem to do it. And after that, I get stuck; I try to start a new project, but it's no use. What should I do?


r/UnityHelp • • Jul 12 '26

C# in unity

1 Upvotes

Hey everyone. I’m currently trying to learn how to develop games in unity as a hobby. I have been struggling a little with a few things and thought it might be a good idea to just focus on learning some C# first then come back to unity. I saw this book The C# Player's Guide" by R.B. Whitaker and was wondering if anyone has used this was it any good, or does anyone have a better suggestion for material to learn some C#. Thanks.


r/UnityHelp • • Sep 09 '26

C# Help

1 Upvotes

Im learning c# in visual studio with Bro Code yt (check him out free courses) and im wondering, does the same c# exactly work in unity, idk how to explain but if i type Console.WriteLine("hi");

will it just show on the screen hi or is there more to it?


r/UnityHelp • • Jan 27 '25

Looking for Developers to help make a past time into an official game!

0 Upvotes

Me and Friend are looking for people to help make a game called "Bugout" into a official game!

You can have on & off commitment or you can help if your simply interested!

The game is an FPS Shooter/PvP/PvE/Survival/RPG (Lol thats a lot) with anomalies, the game is also based in 3177 and is post-apocalyptic, Basically what were looking for is people who can code, model, people who can test, basically the whole 9 yards! DM me on discord (sharting._.)


r/UnityHelp • • Oct 14 '24

OTHER Help.... What feature i have to add

0 Upvotes

r/UnityHelp • • Apr 09 '26

UNITY How do I make my game look less "Robloxy?"

Thumbnail
gallery
1 Upvotes

r/UnityHelp • • Sep 04 '26

PROGRAMMING i need a team

0 Upvotes

im new to unity and i want to make a fun game about the player being a chicken nugget and having to avoid the kids trying to eat them. im not really sure what to do or where to go so i am asking for a dev team thats at least somewhat experanced and can shopw me how to use unity or just help me make it, i also dont know if this is even possible and if there is a dev team feature in unity PLEASE HELP IM CRASHING OUT


r/UnityHelp • • Mar 01 '26

PROGRAMMING please help with this error. I am following a tutorial and he doesn't have this problem

Thumbnail
gallery
1 Upvotes

r/UnityHelp • • Nov 09 '24

unity math isn't mathing

0 Upvotes

i write down code that says:

int = int - 1;

And even though int is set to 100 when i try minusing one it MINUSES 100 INSTEAD! someone please help


r/UnityHelp • • Dec 19 '22

Help needed

2 Upvotes

HEY, my name is ErdnosYT! I am the CEO and Lead developer of the game development studio DullBladeInteractive! And we are new to this studio stuff. So if anyone are up for any job in a game studio, hit me up!

Some info about us:

The team!

Erdnos: Hi! My name is Sondre! I have been developing games for about two years, the first year in scrach. And the second year in Unity and Unreal. I have also “studied” Computer Science at Harvard( CS-50: https://pll.harvard.edu/course/cs50-introduction-computer-science?delta=0) and i have made some projects. Thought none of them is complete.

Links:

itch.Io: https://erdnosyt.itch.io/

TikTok: Erdnosyt

YouTube: https://youtube.com/@erdnos48

Note: I am 13 years of age and I have a lot of school work. So my time is at times limited. And as the others are living in the states and I am writing this while they are sleeping I will be writing for them.

The Rat - His name is Alex( I think). He is from the states and have experience in web development. He is also the discord manager and is doing most of the stuff on that side. He also made a website for the studio(currently empty)

Minion -ahh minion! He is also American! And he is the second founder(more on that later on.) he to be honest don’t really have any specific job. He’s just doing what he wants to. Sometimes post something on the TikTok and yeah- actually his job is to spread positivity in the group!

History:

It all started in August of 2022. Right before school started. I had wanted to make a studio for a while, and then I found a TikTok account which was named “Small games studios”, which was a Norwegian 14 year old who wanted to make games. In his account there was a link to his discord. Which I joined. There I met minion. And Eggy. Me and minion were talking a bit and then we found out that he had a great idea! Make a super realistic “Life” simulation! Where players play together in a world built by them. For instance, the builders actually build houses. The salesmen sell those houses. And anyone buys it. The government controls it. (As of now this is set on hold.). So me and minion made a discord server, our “studio”. Then we invited Eggy. We went a bit back and forth on the name side, we where about to chose “Boring studios” until we just challenged Eggy to say who words of which he answered: “Dull” and “Blade”. Therefore we are named “Dull Blade Interactive(DBI)”. And since then we have just tried to make some games. Failed. A polish boy named Anonymouss also joined after a bit. Very cool guy. Tho he left after a bit.

Notes:

There is no pay, as we have no income we are not able to provide any payments.

We will be working on discord!

Most of the team are under 18

There is no meetings no deadlines no nothing!

This is just a friend group having fun making games!

The team is spread out over the world. So time is a hard concept.

And communication is limited. So we will just have to find some ways around that.

Shot info:

DBI(dull blade interactive) is a American-Norwegian colaberation. And we are up for more to join us in our mission to make games that actually have a meaning! (My discord username: Erdnosyt#8804 )

How to join:

  1. DM this Reddit account. I will then ask you to tell me a little bit about yourself. Then I will most likely invite you to our discord

  2. Help us help you help us all.

Would be fun if you tried it out!


r/UnityHelp • • Oct 19 '25

UNITY Help 🥺

Post image
3 Upvotes

Please


r/UnityHelp • • Jun 20 '25

Ragdoll working but.

Post image
0 Upvotes

My armeture works and it is ragdolling but the object (my character) isnt moving with it. The model falls over but is stuck in a t pose for some reisonderdelen.


r/UnityHelp • • May 24 '25

Aot grappling and gas

0 Upvotes

r/UnityHelp • • Aug 05 '26

UNITY My game keeps crashing

0 Upvotes

Hi there! Whenever I try to open Honkai Star Rail through HoYoPlay, it shows the Unity crash. I've tried opening the app directly, deleting the crash files, and using repair files on the HoYoPlay launcher, but nothing seems to work. Any ideas?


r/UnityHelp • • Apr 01 '26

SOLVED Question about Null Reference Exceptions

0 Upvotes

Hi, could someone tell me if a null reference exception completely blocks the execution of a script, or does it only block what's related to the missing object, or perhaps both depending on the context?


r/UnityHelp • • Feb 12 '26

Best ai for Unity?!

Thumbnail reddit.com
0 Upvotes

r/UnityHelp • • Jan 02 '26

PROGRAMMING All objects of an array are null, but when I try and find a null object, they don't get detected.

0 Upvotes

I have a script that loops through all of the elements until it finds a default value, and when it does, it sets itself to the corresponding variable.

The function is in a global script, and is actually being called from a separate script. The following is the code from the global script, where the function is located.

public void FindFirstNull(string dir, Vector3 value)
{
    if (dir == "South")
    {
       
        for ( int i = 0; i < bottomVertices.Length; i++ )
        {
            if (bottomVertices[i] == Vector3.zero)
            {
                bottomVertices[i] = value;
            }
        }
        
    }
    if (dir == "North")
    {

        for (int i = 0; i < topVertices.Length; i++)
        {
            if (topVertices[i] == Vector3.zero)
            {
                topVertices[i] = value;
            }
        }

    }
    if (dir == "East")
    {

        for (int i = 0; i < rightVertices.Length; i++)
        {
            if (rightVertices[i] == Vector3.zero)
            {
                rightVertices[i] = value;
            }
        }

    }
    if (dir == "West")
    {

        for (int i = 0; i < leftVertices.Length; i++)
        {
            if (leftVertices[i] == Vector3.zero)
            {
                leftVertices[i] = value;
            }
        }

    }
}

I tried using gizmos to see if it just wasn't updating on the editor, but all of the drawn gizmos appear at the default value for the vector 3 array, 0,0,0.

Here is the line of code that actually calls this function:

worldManager.FindFirstNull("South", new Vector3(vertexPosXY.x, y + vertexOffset.y, vertexPosXY.y));

This isn't the only time its called, because it is in a for loop, but none of the default values are changing in the first place, so whatever is wrong with THIS line of code is what is wrong with ALL other times it is called as well.

I thought it was a Unity thing, so I tried the above method and the System.Linq method, but no dice.


r/UnityHelp • • Aug 09 '26

UNITY Model from blender imported weirdly to Unity

0 Upvotes

The model was fine when I opened it in blender but when I imported the .fbx into unity It is now all scattered and weird


r/UnityHelp • • May 27 '26

UNITY I need HELP with Unity and Visual studio!

Thumbnail
gallery
0 Upvotes

Помогите,пожалуйста,понять, что не так с кодом. Я не понимаю что не так :( я посмотрела туториал и всë, вроде бы, одинаково написано в этих строчках (27 и 42), но почему-то выдаëт ошибку, хотя в строке 42 вообще просто скобка стоит. И подскажите, пожалуйста, почему у меня не появляется окошко маленькое как в туториале (я на него стрелочкой указала). Чат gpt мне не помог и в комментах под видео ничего нет. Я уже несколько дней мучаюсь с этим:((

Please help me figure out what's wrong with the code. I don't understand what's wrong :( I watched the tutorial, and everything seems to be written the same way in these lines (27 and 42), but for some reason it's giving me an error, even though line 42 just has a parenthesis in it. And please tell me why I don't see the small window like in the tutorial (I pointed to it with an arrow). The GPT chat didn't help me, and there's nothing in the comments under the video