- Home /
Using Object.name correctly (C#)
Hello, I am writing a a selection script using raycast and I want an object to be selected if its clicked and its name is "Player". So I gave it a go and I recognise my mistake, I just can't think of another way to do it.
The error: Non- Invocable member 'UnityEngine.Object.name' cannot be used like a method.
Here's my code:
using UnityEngine;
using System.Collections;
public class Control : MonoBehaviour {
public bool selected;
//Rays
public RaycastHit hit = new RaycastHit();
public Ray thisRay;
void Start () {
}
void Selected(){
thisRay = Camera.main.ScreenPointToRay(Input.mousePosition);
if(hit.collider.name("Player") != null)
{
selected = true;
}
}
void Update () {
if(Input.GetMouseButtonDown(0))
{
Physics.Raycast(thisRay, out hit);
}
Debug.DrawLine(thisRay.origin, hit.point, Color.red);
}
}
Answer by CatchCo · Mar 30, 2014 at 08:03 PM
The compiler is trying to tell you that you can't use a string
property as a method.
Your issue is at line 15: The syntax you have used for character comparison is not possible in c#. The C# way of string comparison would look like this:
if(hit.collider.name == "Player")
If you change line 15, to my example the class will compile.
Answer by ava4414 · Mar 30, 2014 at 07:01 PM
you can use hit.collider.name("Player"), instead you have to use if(hit.collider.name == "Player").... but i recommend you to use the gmae object tag, you can find it with hit.gameObject.tag and you are going to avoid a lot of problems, and then you set the tag in the unity window
I'm interested about the alternative you offered with the gameObject.tag. Unfortunately my intellisense doesn't feel it viable. Did you mean: hit.collider.gameObject.tag?
Your answer
![](https://koobas.hobune.stream/wayback/20220613141536im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
I made a better shader how do i fix[add _Shadow Strength]help???>Sorry that im asking for to much 1 Answer
Moving object to where a ray lands(C#) 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
How do I create a pause button? 2 Answers