Unity c#脚本中的轨迹渲染器

Unity c#脚本中的轨迹渲染器,c#,unity3d,space,trail,C#,Unity3d,Space,Trail,我有一个简单的项目,在那里我产生了多个小行星,它们倾向于在一个行星上受引力。我想添加一个简单的轨迹来增强视觉效果。手动添加小行星,然后添加组件“轨迹渲染器”并选择所需的材质,这非常简单。但我无法解决如何将其添加到脚本中。这是我目前的代码: using System.Collections; using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(FauxGravityBody))] pub

我有一个简单的项目,在那里我产生了多个小行星,它们倾向于在一个行星上受引力。我想添加一个简单的轨迹来增强视觉效果。手动添加小行星,然后添加组件“轨迹渲染器”并选择所需的材质,这非常简单。但我无法解决如何将其添加到脚本中。这是我目前的代码:

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());
    }

}
使用系统集合;
使用UnityEngine;
[RequiredComponent(类型)(刚体))]
[所需组件(类型(人造重力体))]
公共类产卵器:单行为{
公共游戏对象流星预制;
公共浮动距离=20f;
公共浮动时间=10f;
私人游戏物体流星;
公共列车员径;
无效开始()
{
start例程(spawnemeteor());
}
IEnumerator PrownMeteor()
{
Vector3 pos=Random.onUnitSphere*距离;
meteor=实例化(MeteorPrefact,pos,Quaternion.identity);
meteor.AddComponent();
meteor.AddComponent();
meteor.AddComponent();
meteor.AddComponent();
返回新的WaitForSeconds(时间);
start例程(spawnemeteor());
}
}
这确实会将轨迹添加到生成的对象中,但它使用默认的粉红色轨迹。我想要的线索材料位于文件夹“Assets/Effects/trail.mat”中。如何在脚本中指定要使用该特定材质


亲切问候。

注意,如果您需要所有流星上的这些组件——TrailRenderer、SphereCollider等,您只需手动将它们添加到预制件本身(通过将它们拖到预制件上)。那么,一旦你实例化了主预制件,它们就已经存在了,正确的材料和所有的东西


然后,您仍然可以通过
GetComponent()
等方式获取特定设置(或禁用组件)。祝您好运

最好的方法是

创建
预制件
并将所需组件连接到
预制件

并在需要的时候和地点安装

使用
GetComponent()
方法可以获得附加组件

GameObject bullets = Instantiate(yourPrefab, yourtransform.position, Quaternion.identity) as GameObject;
bullets.GetComponent<Rigidbody>().AddForce(transform.forward * 100, ForceMode.Impulse);
GameObject子弹=实例化(yourPrefact、yourtransform.position、Quaternion.identity)为GameObject;
bullets.GetComponent().AddForce(transform.forward*100,ForceMode.pulse);

注意:如果您需要所有流星上的这些组件——TrailRenderer、SphereCollider等,您只需手动将它们添加到预制件本身(通过将它们拖到预制件上)。那么,一旦你实例化了主预制件,它们就已经存在了,正确的材料和所有的东西。然后,您仍然可以通过
GetComponent()
等方式获取特定设置(或禁用组件)。祝您好运@PhilippLenssen这应该是答案。@Mateusz完成,谢谢。我不能100%确定询问者是否在脚本添加组件背后有隐藏的意图,但我猜可能性不高。这是关于,而不是。