统一。用键盘控制getcomponent

时间:2018-10-23 19:58:12

标签: c# unity3d

我是一个初学者,对Unity编码有问题。我想使用两个箭头键显示和隐藏3D文本网格。一次一个网格。但这不像我想的那样。我认为您会很容易发现问题所在。 还有一个问题。它将在移动设备上工作,并且将使用数十个网格。我不确定这是否是最好的方法,所以请告诉我是否有更好的方法。 (尤其是关于性能和优化问题)的感谢。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextmeshSelection : MonoBehaviour{
public List <GameObject> Textmeshes = new List<GameObject> ();
public int Num;

void Update() {
 if (Input.GetKeyDown(KeyCode.RightArrow)) {
  Num++;
  Renderer rend = Textmeshes[Num].GetComponent<Renderer> ();
  if (rend.enabled)
   rend.enabled = false;
  else
   rend.enabled = true;
 }

 if (Input.GetKeyDown(KeyCode.LeftArrow)) {
  Num--;
  Renderer rend = Textmeshes[Num].GetComponent<Renderer> ();
  if (rend.enabled)
   rend.enabled = false;
  else
   rend.enabled = true;
 }

 if (Num < 0) {
  Num = 0;
  Renderer rend = Textmeshes[Num].GetComponent<Renderer> ();
  if (rend.enabled)
   rend.enabled = false;
  else
   rend.enabled = true;
 }
}

}

1 个答案:

答案 0 :(得分:0)

您不应该每次都在GetComponent中调用Update,而应该一次都初始化它们,例如在字典中

// Dictionary to store the references to the Renderer components
// Makes it easier to find them later
// You could as well only use a List instead and rely on the index
Dictionary<GameObject, Renderer> renderers = new Dictionary<GameObject, Renderer>();

private void Awake()
{
    // Get all references already at app start
    foreach(var textMesh in Textmeshes)
    {
        renderers[textMesh] = textMesh.GetComponent<Renderer>();

        // And hide all from beginning
        renderers[textMesh].enabled = false;
    }

    // Then enable only the first one depending what your Num is at start
    SanatizeNum();
    SetRendererEnabled(Num, true);
}

然后,我将从Update中提取您的代码到多种方法中,以使其更整洁,消除冗余并使其更易于维护。

private void Update()
{
    if (Input.GetKeyDown(KeyCode.RightArrow)) 
    {
        GoToNext();
    }

    if (Input.GetKeyDown(KeyCode.LeftArrow)) 
    {
        GoToLast();
    }
}

private void GoToNext()
{
    // Hide the current renderer
    SetRendererEnabled(Num, false);

    Num++;
    SanatizeNum();

    // Show the new renderer
    SetRendererEnabled(Num, true);
}

private void GoToLast()
{
    SetRendererEnabled(Num, false);

    Num--;
    SanatizeNum();

    SetRendererEnabled(Num, true);
}

private void SanatizeNum()
{
    Num = Mathf.Clamp(Num, 0, Textmeshes.Count -1);
}

private void SetRendererEnabled(int index, bool enabled)
{
    renderers[Textmeshes[index]].enabled = enabled;
}