Hello,
I am working in C#. Well my problem is, I am currently working on a health script for a game working on. It is a 2D stealth based game, there is one player and multiple enemies with varying types of guns and armor. My idea for the script was that each player and enemy has a number (0 for player, 1 for player) when the bullet (raycast) hit’s either the player or enemy it will detect whether it is a enemy or player (using the number) there will then an if statement saying 'whatever number it is minus the damage of said gun. This way I can have one script to take care off all types of enemies and weapons and not mulitiple scripts.
I am kind of new to this whole game dev thing so be gentle. Basically all I would like to know is how would I go about all this e.g. How can I assign something an integer, How can I make the raycast detect what number it is, Then how can I use what information gives back, How am I going to deal with the multiple types of guns.
Any response is greatly appreciated. Cheers for your time,
Paul,
Hey there Chicken,
First off, have you tried tackling this yourself?
First step… the way I would do it is assign tags. If you haven’t learned about tags, they are extremely useful. The way I would do it is give all the enemies in the game a tag: “Enemy”.
Then use an if-statement for your RaycastHit…
if (hit.tag == "enemy") {
//take damage
}
I have tryed it but got stuck when I had to detect data with the raycast. Basically the way I did was give each player or enemy a variable called like “data_type” this was either 0 or 1. But then I could not figure out how to make the raycast read that data and feed it back into a variable
There are multiple ways of communicating data in Unity and I won’t get into them all, but the tutorials do, do a good job in explaining them. In your case however can I assume you have one super script lets say Entity and sub scripts like Enemy and Player. So Entity takes a number determining what faction the Entity is I’m guessing?
So lets say your bullet hits something, you can get the GameObject it hit using a RayCastHit. From that game object you can then check if it contains a specific script and if it has an Entity script, you can check what faction it is. I’m sorry if this sounds confusing I can explain it better if you don’t understand. But to achieve this you would do this. Obviously substitute your own variables.
RaycastHit hit; // Store ray cast hit info
if(Physics.Raycast(ray, out hit, maxDistance))
{
Entity e = hit.collider.gameObject.GetComponent<Entity>() // Try and Get the Entity. Will Return null if it does not exist on the gameobject that was hit.
if(e != null)
{
e.factionNumber // Do something with this.
}
}