如何修复:NullReferenceException:不要创建自己的模块实例,从 ParticleSystem 实例获取它们

Mis*_*sty 5 c# particles unity-game-engine particle-system

我正在尝试制作一个脚本,以便在按下按钮时粒子系统会更改为某种颜色,除了更改粒子颜色之外,它一切正常,当我尝试时会出现以下错误:

NullReferenceException:不要创建自己的模块实例,而是从 ParticleSystem 实例获取它们

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

public class Attack : MonoBehaviour
{
    public int MovementDirection = 0;
    public int State = 0;

    public GameObject attackOrb; //The prefab for our attack hitbox
    public Transform Player;        //Where the player is

    public float R = 0.0F;
    public float G = 0.0F;
    public float B = 0.0F;
    public float A = 1.0F;

    private ParticleSystem attackEffect;

    // Start is called before the first frame update
    void Start()
    {
        attackEffect = gameObject.GetComponent<ParticleSystem>();
    }

    // Update is called once per frame
    void Update()
    {
        var main = attackEffect.main;
        main.startColor = new Color(R, G, B, A);

        if (Input.GetKeyDown(KeyCode.Keypad1)) State = 1;
        if (Input.GetKeyDown(KeyCode.Keypad2)) State = 2;
        if (Input.GetKeyDown(KeyCode.Keypad3)) State = 3;
        if (Input.GetKeyDown(KeyCode.Keypad4)) State = 4;
        if (Input.GetKeyDown(KeyCode.Keypad5)) State = 5;
        if (Input.GetKeyDown(KeyCode.Keypad6)) State = 6;


        switch(State)
        {
            case 0:
                GetComponent<Renderer>().material.color = new Color(1f, 0.5f, 0.5f, 0.5f);
                R = 1f;
                G = 0.5f;
                B = 0.5f;
                A = 0.5f;
                break;
Run Code Online (Sandbox Code Playgroud)

它本来应该显示为 R、G、B、A 颜色,但却返回该错误。为什么它会返回这个问题以及我该如何解决这个问题?

完整错误:

NullReferenceException: Do not create your own module instances, get them from a ParticleSystem instance
UnityEngine.ParticleSystem+MainModule.set_startColor (UnityEngine.ParticleSystem+MinMaxGradient value) (at C:/buildslave/unity/build/artifacts/generated/bindings_old/common/ParticleSystem/ParticleSystemBindings.gen.cs:50)
Attack.Update () (at Assets/Script/Attack.cs:30)
Run Code Online (Sandbox Code Playgroud)

Dav*_*ave 2

startColor这是在 Unity3D 中更改粒子系统的方法:

    var main = particleSystem.main;
    main.startColor = new ParticleSystem.MinMaxGradient(new Color(R, G, B, A));
Run Code Online (Sandbox Code Playgroud)

如果您想知道为什么要检查ParticleSystem.MainModule.startColor. 它不是类型Color而是ParticleSystem.MinMaxGradient