Answer the question
In order to leave comments, you need to log in
How to cast a beam in Unity?
Task:
Throw a beam from the center of the camera and create a sphere at the point of contact with the object.
using System;
using UnityEngine;
using System.Collections;
public class RayShooter : MonoBehaviour
{
private Camera _camera;
// Use this for initialization
void Start ()
{
_camera = GetComponent<Camera>();
}
// Update is called once per frame
void Update ()
{
if (Input.GetMouseButton(0))
{
var centerPoint = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight /2, 0);
Ray ray = _camera.ScreenPointToRay(centerPoint);
RaycastHit hit;
bool e = Physics.Raycast(ray, out hit);
if (e)
SphereIndicator(hit.point);
}
}
private IEnumerator SphereIndicator(Vector3 position)
{
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = position;
Debug.Log("Sphere");
yield return new WaitForSeconds(1);
Destroy(sphere);
}
}
{
.............
RaycastHit hit;
bool e = Physics.Raycast(ray, out hit); // e = true
if (e)
SphereIndicator(hit.point); // Запуск метода
}
private IEnumerator SphereIndicator(Vector3 position)
{ // Дебагер тут
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); // А тут его нет.
//Он ушёл выполнять другие скрипты.
sphere.transform.position = position;
.....................
}
if (Physics.Raycast(ray, out hit) )
SphereIndicator(hit.point);
Answer the question
In order to leave comments, you need to log in
SphereIndicator is a coroutine, and coroutines are started with StartCoroutine :
void Update ()
{
if (Input.GetMouseButton(0))
{
var centerPoint = new Vector3(_camera.pixelWidth / 2, _camera.pixelHeight /2, 0);
Ray ray = _camera.ScreenPointToRay(centerPoint);
RaycastHit hit;
bool e = Physics.Raycast(ray, out hit);
if (e)
{
StartCoroutine(SphereIndicator(hit.point));
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question