unity 3 d 5.0マウスをクリックしてgameObjectのmaterialを動的に変更

5543 ワード

unity 3 d 5.0でrendererの後にmaterialを使用できない場合はGetComponentでコンポーネントを取得する必要があります
コードはこう書くべきです
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class touch3d : MonoBehaviour {

    Ray ray;
    RaycastHit rayhit;
    // Use this for initialization
    void Start () {

    }


    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            int target = LayerMask.GetMask("target");
            Debug.Log(target);
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out rayhit, 100f, target))
            {
                //rayhit.collider.gameObject.GetComponent().material.mainTexture = (Texture)Resources.Load("meinv");
                rayhit.collider.gameObject.GetComponent().material.color = Color.blue;
                Debug.Log(rayhit.collider.gameObject.name);
            }
        }
    }   
}

タッチイベントであれば、マウスをタッチに変更するだけでいいのですが、以下のようになります.
using UnityEngine;  
using System.Collections;  

public class example : MonoBehaviour {  
    public GameObject particle;  
    void Update() {  
            if (Input.GetTouch(i).phase == TouchPhase.Began) {  
            int target = LayerMask.GetMask("target");
                Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);  
                if (Physics.Raycast(ray, out rayhit, 100f, target))  
rayhit.collider.gameObject.GetComponent().material.color = Color.blue;


            }  

        }  
    }  
}  

Input.GetTouch(i).phase==TouchPhase.Beganは、タッチ押下イベントを判断する他のタッチイベントは以下の通りである.
TouchPhase Enumeration  
Describes phase of a finger touch.


Values
Began   A finger touched the screen.
Moved   A finger moved on the screen.
Stationary  A finger is touching the screen but hasn't moved.
Ended   A finger was lifted from the screen. This is the final phase of a touch.
Canceled    The system cancelled tracking for the touch, as when (for example) the user puts the device to her face or more than five touches happened simultaneously. This is the final phase of a touch.