简体   繁体   English

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

[英]Trail Renderer in Unity c# script

I have a simple project where I spawn multiple asteroids and they tend to gravitate over a planet.我有一个简单的项目,我在其中生成了多个小行星,它们往往会被一个行星吸引。 I wanted to add a simple trail to enhance the visual effects.我想添加一个简单的轨迹来增强视觉效果。 It's very simple when I add the asteroid manually and then add component "trail renderer" and select desired material.当我手动添加小行星然后添加组件“轨迹渲染器”并选择所需的材料时,这非常简单。 But I can't work it out on how to add it to a script.但我无法弄清楚如何将其添加到脚本中。 This is my code for now:这是我现在的代码:

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

}

Which indeed adds the trail to the spawned objects, but it's using the default pink trail.这确实将轨迹添加到生成的对象中,但它使用的是默认的粉红色轨迹。 My desired trail material is located in folder "Assets/Effects/Trail.mat".我想要的路径材料位于文件夹“Assets/Effects/Trail.mat”中。 How can I specify in the script that I want to use that specific material?如何在脚本中指定要使用该特定材料?

Kind regards.亲切的问候。

Note if you need these components -- TrailRenderer, SphereCollider etc. -- on all meteors, you can simply add them to the Prefab itself manually (by dragging them over it).请注意,如果您需要这些组件——TrailRenderer、SphereCollider 等——在所有流星上,您只需手动将它们添加到预制件本身(通过将它们拖到它上面)。 Then they will already be there, right materials and all, once you Instantiate the main prefab.然后,一旦您实例化主要预制件,它们就已经在那里了,正确的材料等等。

You can then still adjust specific settings (or disable components) by using getting them via GetComponent<TrailRenderer>() etc. Good luck!然后,您仍然可以通过GetComponent<TrailRenderer>()等获取它们来调整特定设置(或禁用组件GetComponent<TrailRenderer>() 。祝你好运!

The best way to do it is....最好的方法是......

create Prefab and attach you needed component to your Prefab创建Prefab并将您需要的组件附加到您的Prefab

and Instatiate it when and where you need it并在您需要的时间和Instatiate对其进行Instatiate

and using GetComponent<>() method you can get attached component并使用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