I recently decided to try making a survival game. I watched a tutorial about how you make that your tree objects could be chopped down.
So here is my script: (Some Variables are german, because I am from Germany)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaumFäller : MonoBehaviour
{
public int damage;
string item;
private GameObject baumscript;
private RaycastHit hit;
void Update()
{
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 1000f);
{
if (Input.GetButtonDown(“Fire1”))
{
if (hit.gameObject.tag == “Baum”)
{
print(“TREE”);
GameObject baumscript = GameObject.Find(hit.collider.transform.gameObject.name);
baumscript.GetComponent().Schaden(damage);
}
}
}
}
}
This script should identify my tree object and execute the Schaden void, which is public in the “BaumVerhalten” Script from my tree object. After compiling I get this error:
[…]Baumfäller.cs(19,25): error CS1061: Type ‘UnityEngine.RaycastHit’ does not contain a definition for ‘gameObject’ and no extension method ‘gameObject’ of type ‘UnityEngine.Raycast.Hit’ could be found. Are you missing an assembly reference?
Does anyone know what I have done wrong or how it could be fixed?
code tags when pasting code into the forums please:
if you find yourself getting errors along the lines of "this thing does not contain a definition for… " you should be looking at the API to see what attributes and methods do exist: https://docs.unity3d.com/ScriptReference/RaycastHit.html
having said that,
these make no sense. “Do an entire scene search for the thing I hit by name…”
I just added the .transform and now it works perfectly fine!
So, now that it is fixed, could you tell me how to set the range oft the Ray? Because I dont want my Charakter to be able to hit a tree Form all over the map…