- Home /
Clicking on an Object to Make it the Variable Target
How could i click a cube and have it because the variable target.
I would like to have this in C# so if that is possible please give it to me like that
I saw this post which is practically what i need but i got errors converting it because it was in javascript
http://answers.unity3d.com/questions/199159/how-to-make-an-object-the-target-when-you-click-on.html
The main problem im getting is the variable ray in that post
This is the script in that post
var hit: RaycastHit;
var ray;
private var target : Transform;
function Update ()
{
if(Input.GetMouseButtonDown(0)) // for standalone
{
if (Physics.Raycast (ray, hit, 100))
{
if(hit.collider.gameObject.tag == "TagName")
{
target = hit.collider.gameObject;
}
}
}
What type of variable is that?
The variable ray is the variable im talking about at the end
Answer by aldonaletto · Jan 02, 2012 at 02:11 AM
This is the C# version:
RaycastHit hit; Ray ray; Transform target;
void Update (){ if (Input.GetMouseButtonDown(0)){ ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast (ray, out hit, 100)){ if (hit.transform.tag == "TagName"){ target = hit.transform; } } }
}
Thanks but a couple of questions...
I get this semi error... I still can run my script but this pops up
NullReferenceException UnityEngine.Camera.ScreenPointToRay (Vector3 position) Control.Update () (at Assets/$$anonymous$$yAssets/Scripts/Control.cs:32)
And The variable target doesn't actually take that object i click as the variable
I know this is old, but I just experience the same problem and got the same error. I fixed it by making sure my camera was tagged as "$$anonymous$$ainCamera".