Am am new one in Unity C#, so probably my request is nonsence due to platform limitations.
Also, please excuse my english, I fear it will contant mistakes.
I know about GetComponent with variable script possible? - Questions & Answers - Unity Discussions but it seems like it doesn’t fit my needs (or I am too noob to understand how it does).
For some reasons I need to check GameObjects for some (nearly random) scripts and turn it on/off on raycast.
But when I tried to use some kind of that - it was a failure. GetComponent just do not want to use string variable as component name. How may I do this?
Actual (non-workable) listing:
using UnityEngine;
using System.Collections;
public class RaycastFunctionSwither : MonoBehaviour {
public string components;
public float distance;
private string element;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
string subject;
string old_subject;
if (Input.GetKeyDown("e"))
{//if user want to use it
var hit = RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit, distance))
{//raycast gives new object, so old became an old one
old_subject = subject;
subject = hit.collider.gameObject.name;
if (subject != old_subject)
{
foreach (var Element in components)
{//check and turn off
if (old_subject.GetComponent(Element))
{
old_subject.GetComponent<element>().enable = false;
}
}
if (subject != null)
{//если объект != старый объект И объект != null
foreach (string element in components)
{//check and turn on
if (subject.GetComponent<element>)
{
subject.GetComponent<element>().enable = true;
}
}
}
}
}
}
else if (Input.GetKeyUp("e"))
{ //check and turn off
foreach (var element in components)
{//check and turn off
if (old_subject.GetComponent<element>)
{
old_subject.GetComponent<element>().enable = false;
}
}
}
}
}