❔ How do I change the color of certain targets when they're shot, and also destroy others when shot?
I have tagged the ones to be destroyed as destroy and the ones that change color as color, but neither are working. I looked up a video for the color one, and the destroyable ones i saw that you can use Destroy(objects name) to do it, but i dont know what to write to make it destroy the target being shot and not all of them, and the color changer video just didnt work. Here is the code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
Renderer render;
bool shoot;
Camera cam;
public float distance = 10;
public LayerMask whatCanBeHit;
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
shoot = Input.GetButton("Fire1");
}
public void FixedUpdate()
{
if (shoot)
{
//Debug.Log("Shoot");
RaycastHit hit;
Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, distance, whatCanBeHit);
if (hit.collider.tag == "Color")
{
render = GetComponent<Renderer>();
render.material.color = Color.red;
}
else if (hit.collider.tag == "Destroy")
{
Destroy(gameObject);
}
string s = hit.collider != null ? hit.collider.name : "Nothing";
Debug.Log($"You hit {s}");
//Debug.DrawRay(cam.transform.position, cam.transform.forward * distance, Color.yellow);
//Debug.DrawLine(hit.point, hit.point + hit.normal * 1, Color.red, 10f);
}
}
}
8 Replies
Seems you are beginner in Unity ) . Let's solve your problem
Did you set tags to your objects?
And also. I think you want other objects to be colored or destroyed, not the one that is shooting
yeah theyre tagged as Color and Destroy
Have you tried this?
yeah, im getting an error: Object reference not set to an instance of the object
i dont know what that means
It means there's no reference to some object (object can be destroyed or not assigned)
It should say at which line of code in which script it's called
if (hit.collider.tag == "Color") apparently, but im not sure what about that line wouldnt be referencing an object
Ahh. Physics.Raycast where you receives "hit" also returns info if it hitted something. You should execute all this code only on "true"
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.