So i’ve been trying for a few days to get my code to work by using Physics2D.Raycast to be able to using raycasting for using a touchscreen to activate or touch 2D objects, but with no luck. I was wondering if someone could give me a simple start since I’m still unable to do this without countless errors. Any help is appreciated, Thank you!
This is an example of my code Ive been using so far: `using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Interactables: MonoBehaviour
{
Ray ray;
RaycastHit hit;
private float distp;
public float maxdist;
private bool ispaused;
bool open = false;
public static String trigname;
public static bool radiohit = false;
private Vector3 v1;
private int hitnum = 0;
// Use this for initialization
void Start()
{
maxdist = 5f;
}
// Update is called once per frame
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Clickers();
ispaused = CharacterSettings.paused;
if (open == true)
{
//close after far away enough
}
}
private void Clickers()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
if (hit.collider != null) //Changed
{
//Debug.Log(hit.transform.tag);
if (ispaused == false)
{
distp = Vector3.Distance(transform.position, hit.transform.position);
//Here goes the selectable items
}
if (distp <= maxdist)
{
Battery();
}
}
}
}
private void Battery()
{
if (hit.collider.GetComponent<Collider2D>().tag == "Battery")
{
Flashlight.battery++;
Destroy(hit.transform.gameObject);
}
}
}
`