x


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?

more ▼

asked Jan 02 '12 at 01:22 AM

CursedScripter gravatar image

CursedScripter
31 10 13 14

The variable ray is the variable im talking about at the end

Jan 02 '12 at 01:24 AM CursedScripter
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
      }
    }
  }  
}
more ▼

answered Jan 02 '12 at 02:11 AM

aldonaletto gravatar image

aldonaletto
41.4k 16 42 197

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/MyAssets/Scripts/Control.cs:32)

And The variable target doesn't actually take that object i click as the variable

Jan 02 '12 at 02:45 AM CursedScripter
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4157
x3460
x1530
x823
x32

asked: Jan 02 '12 at 01:22 AM

Seen: 1116 times

Last Updated: Jan 02 '12 at 02:45 AM