Tree Chopping / Raycast Identifying not working | PLEASE HELP

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…”

BaumVerhalten referenceName = hit.transform.GetComponent<BaumVerhalten>();
if(referenceName != null)
{
referenceName.Schaden(damage)
}

First of all, thanks for replying!

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…

Use the hit.distance and read up on the link presented it should give you a clear view of how to handle it :slight_smile:

So the hit.distance read the raycast from the origin to the point you hit. So use something along the line of:

public int choppingRange = 10;

if(hit.distance <= choppingRange){
debug.Log(" Trees be choppin' ");
}else{
debug.Log(" The object is to far away ");
}

OK. Thank you. I will try it out :wink: