I am using Unity3D, and i programming augmented reality. If i touch the screen and the touched position has one object, I will do something. Actually I want "How can i know touched which game object ?
My code is here:
using UnityEngine;
using System.Collections;
public class Atak : MonoBehaviour {
private Animator anim;
private GameObject kamera;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
kamera = GameObject.FindGameObjectWithTag ("Kamera");
}
// Update is called once per frame
void Update () {
RaycastHit dokunma;
if (Physics.Raycast(kamera.transform.position,Input.mousePosition,10)&&
dokunma.collider.gameObject.tag=="Oyuncu" && Input.GetMouseButtonDown(0)
){
anim.SetBool ("Bekle", false);
anim.SetBool ("Saldir", true);
} else{
anim.SetBool ("Bekle", true);
anim.SetBool ("Saldir", false);
}
}
}
The editor gives me error:
Use of unassigned local variable'dokunma'
You did not assign anything to the dokunma
(RaycastHit) variable. Note that you have to pass in the dokunma
variable to the Physics.Raycast
function with the out
keyword so that it will be initialized and result of the raycast will be stored in it.
void Update()
{
Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit dokunma;
if (Physics.Raycast(rayCast, out dokunma, 10) &&
dokunma.collider.gameObject.tag == "Oyuncu" && Input.GetMouseButtonDown(0)
)
{
anim.SetBool("Bekle", false);
anim.SetBool("Saldir", true);
}
else
{
anim.SetBool("Bekle", true);
anim.SetBool("Saldir", false);
}
}
It makes more sense to check for touch press first before performing the raycast. Always use the CompareTag
function to compare tags. Something below should do it.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray rayCast = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit dokunma;
if (Physics.Raycast(rayCast, out dokunma, 10))
{
if (dokunma.collider.CompareTag("Oyuncu"))
{
anim.SetBool("Bekle", false);
anim.SetBool("Saldir", true);
}
else
{
anim.SetBool("Bekle", true);
anim.SetBool("Saldir", false);
}
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments