簡體   English   中英

Unity c#腳本中的軌跡渲染器

[英]Trail Renderer in Unity c# script

我有一個簡單的項目,我在其中生成了多個小行星,它們往往會被一個行星吸引。 我想添加一個簡單的軌跡來增強視覺效果。 當我手動添加小行星然后添加組件“軌跡渲染器”並選擇所需的材料時,這非常簡單。 但我無法弄清楚如何將其添加到腳本中。 這是我現在的代碼:

using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(FauxGravityBody))]
public class Spawner : MonoBehaviour {

    public GameObject meteorPrefab;
    public float distance = 20f;
    public float time = 10f;
    private GameObject meteor;
    public TrailRenderer trail;
    void Start ()
    {
        StartCoroutine(SpawnMeteor());
    }

    IEnumerator SpawnMeteor()
    {
        Vector3 pos = Random.onUnitSphere * distance;
        meteor = Instantiate(meteorPrefab, pos, Quaternion.identity);
        meteor.AddComponent<FauxGravityBody>();
        meteor.AddComponent<DestroyMeteor>();
        meteor.AddComponent<SphereCollider>();
        meteor.AddComponent<TrailRenderer>();

        yield return new WaitForSeconds(time);

        StartCoroutine(SpawnMeteor());
    }

}

這確實將軌跡添加到生成的對象中,但它使用的是默認的粉紅色軌跡。 我想要的路徑材料位於文件夾“Assets/Effects/Trail.mat”中。 如何在腳本中指定要使用該特定材料?

親切的問候。

請注意,如果您需要這些組件——TrailRenderer、SphereCollider 等——在所有流星上,您只需手動將它們添加到預制件本身(通過將它們拖到它上面)。 然后,一旦您實例化主要預制件,它們就已經在那里了,正確的材料等等。

然后,您仍然可以通過GetComponent<TrailRenderer>()等獲取它們來調整特定設置(或禁用組件GetComponent<TrailRenderer>() 。祝你好運!

最好的方法是......

創建Prefab並將您需要的組件附加到您的Prefab

並在您需要的時間和Instatiate對其進行Instatiate

並使用GetComponent<>()方法可以獲得附加組件

GameObject bullets = Instantiate(yourPrefab, yourtransform.position, Quaternion.identity) as GameObject;
bullets.GetComponent<Rigidbody>().AddForce(transform.forward * 100, ForceMode.Impulse);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM