Changing a skybox via C#

Good evening all. I’ve been all over these forums looking at solutions to this, but I’m still getting errors.

Here’s my code so far.

using UnityEngine;
using System;

public class DayNightCycle : MonoBehaviour {

    var dayMat : Material;
    var nightMat : Material;

	void Update () {
        changeSky();
	}

private static void changeSky()
{
        var hours = System.DateTime.Now.Hour;
         
        if (hours == 18 || hours == 19 || hours == 20 || hours == 21 || hours == 22 || hours == 23 || hours == 24)
        {
           Skybox.material = nightMat;
        }else{
            Skybox.material = dayMat;
        }
}
}

I have my var dayMat and var nightMat throwing errors, which is causing the Skybox.material to error. Any and all solutions welcome!

Stupid question, but did you make sure that your two variable contained valid Materials?

What do you mean? I haven’t assigned my sky box texture materials because my script is broken. The missing textures don’t appear to be the problem, but rather how my code is written.

Why are you string a bunch of ors instead of using <=

If (hours <= 18)

Also you defined your materials wrong for c#

Public Material nightMaterial;

Your doing explicit types unityScript style, even with your hours you should prolly use a explicit type in place of var instead of the implicit var

1 Like

Here. Simplified the if and used the proper skybox thingy.

If you don’t understand the if it says

if hours over or equal to 18 and hours are less than or equal to 24.

if(hours >= 18 && hours <= 24)
{
RenderSettings.skybox = nightMat;
}
else
{
RenderSettings.skybox = dayMat;
}

Skybox is a class, and not the actual skybox in render settings. That is why your code was erroring.

1 Like

Thank you for all your replies. The code now reads as follows:

using UnityEngine;
using System.Collections;

public class SkyboxCycle : MonoBehaviour {

  public Material nightMat;
  public Material dayMat;

   void Update () {
  changeSky();
   }

private static void changeSky()
{
  var hours = System.DateTime.Now.Hour;

  if(hours >= 18 && hours <= 24)
  {
  RenderSettings.skybox = nightMat;
  }
  else
  {
  RenderSettings.skybox = dayMat;
  }
  }
}

The console in Unity is saying
Assets/Scripts/SkyboxCycle.cs(19,33): error CS0120: An object reference is required to access non-static member `SkyboxCycle.nightMat’

Assets/Scripts/SkyboxCycle.cs(23,33): error CS0120: An object reference is required to access non-static member `SkyboxCycle.dayMat’

So my question now is, “How do I manually reference the location of my two skybox materials?” My material are located in /Assets/Sky in my project folder.

I assume it will go in here somewhere?

  public Material nightMat;
  public Material dayMat;

Why are you making the change sky a static void, just make if void

1 Like

Thank you, the code now runs correctly. It was the static void that was causing problems.