Home>
I want to solve

I want to be able to assign a value to newColor.

problem

Error statement
cs (58,25): error: CS0165: Use of unassigned local variable'newColor'

Line 58: ps.startColor = newColor;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class ParticleManager: MonoBehaviour
{
    ParticleSystem ps;
    void Start ()
    {
        ps = GetComponent<ParticleSystem>();
    }

    void Update ()
    {
        if (Input.GetKey (KeyCode.Space))
        {
            PlayFirework ();
        }
    }
    void PlayFirework ()
    {
        var rand = Random.Range (0, 2);
        var r2 = Random.Range (0, 256);// red random
        var g2 = Random.Range (0, 256);// green random
        var b2 = Random.Range (0, 256);// blue random
We received advice on/* Random and made changes.
        Random.Range does not include the max value in the result, so if I want to make it random from 0 to 255, it will be Random.Range (0, 256).
       * /
        Color32 newColor;
        // Red is fixed at 255 and green and blue are random at 0-255
        if (rand == 0)
        {
            newColor = new Color32 (255, (byte) g2, (byte) b2, 255);
        }
        // Green is fixed at 255 and red and blue are random
        // Blue is fixed at 255 and red and green are random

        ps.startColor = newColor;//
        ps.Play ();
    }
}
What I tried

When the if statement was commented and only newColor = new Color32 () was extracted and executed, it could be executed without error.
Therefore, it is possible that the if statement is incorrect, or that the value in the if statement is not reflected in the C # writing style.

     /*
        // Red is fixed at 255 and green and blue are random at 0-255
        if (rand == 0)
        {
            newColor = new Color32 (255, (byte) g2, (byte) b2, 255);
        }
        // Green is fixed at 255 and red and blue are random at 0-255
        // Blue is fixed at 255 and red and green are random at 0-255
        * /
            newColor = new Color32 (255, (byte) g2, (byte) b2, 255);

Environment i am using
Unity2020.1.0f1 Personal
Visual studio 2019

  • Answer # 1

    The if statement itself is correct, but I think the problem is that if the value of rand is non-zero, the variable newColor is left unassigned.

    The variable newColor is just before the if statementColor32 newColor;Was just declared, but not initialized.

    So when declaring a variable

    Color32 newColor = new Color32 ();


    If you initialize it or add else to the if statement as shown below, the error will be resolved without commenting out the if statement.

    if (rand == 0)
    {
        newColor = new Color32 (255, (byte) g2, (byte) b2, 255);
    }
    else else
    {
        newColor = new Color32 ();
    }