I have this problem that i just can't figure out how to solve. I am trying to make a game in Unity, and i have stumbled across a problem that goes like this.
I want to put an object in the scene in a list, when i hit it with a raycast.
With what i have tried so far. Either it puts everything that is tagged the same thing on the list when i press mousebutton on one of the objects, or it only puts in the same thing (Cube in this example).
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTagged : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public List<GameObject> playersTagged;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.takeDamage(damage);
if(hit.collider.tag == "Taggable")
playersTagged.Add(GameObject.FindWithTag("Taggable"));
}
}
}
}
CodePudding user response:
Instead of using GameObject.FindWithTag() which returns the first object it'll find source
Use gameobject property playersTagged.Add(target.gameobject). Since all components store the reference to the gameobject they are attached to.
CodePudding user response:
use
playersTagged.Add(hit.collider.gameObject);
CodePudding user response:
You are adding GameObject.FindWithTag("Taggable")
which means you are getting all GameObjects that have that tag and adding all of them to the list. You just want to add the hit object, so you just need to add hit.collider.gameObject
.