r/Unity3D – Telegram
r/Unity3D
260 subscribers
12.6K photos
15.5K videos
14 files
47.8K links
News about the Unity engine and project showcases from Reddit. Made possible with @reddit2telegram (@r_channels).
Download Telegram
UnityEngine;


public class SkyController : MonoBehaviour
{  
  [SerializeField] private string assetPath;
  [SerializeField] public bool hourOverride;
  [SerializeField, Tooltip("Use 0-24H format")] private int hourCustom;


  public int hourCurrent;
  private string timeOfDay = "Day/";
  private string assetPathStart = "";
  private string assetPathDefault = "";
  public Texture2D[] textures;
  public bool textureReload = false;
  public int textureCount;


  void Start() {
    assetPathStart = assetPath;


    SetTimeAndPath();
    LoadTextures();
  }


  void Update() {
    if (!hourOverride && DateTime.Now.Hour != hourCurrent) {
        SetTimeAndPath();
        LoadTextures();
        textureReload = true;
    }
  }


  void SetTimeAndPath() {
      hourCurrent = hourOverride ? hourCustom : DateTime.Now.Hour;
      timeOfDay = hourCurrent switch {
          <=5 => "Night/",
          <=9 => "Morning/",
          <=16 => "Day/",
          <=20 => "Evening/",
          _ => "Night/"
      };


      assetPath = string.IsNullOrEmpty(assetPath) ? assetPathDefault : assetPathStart;
      assetPath += timeOfDay;
  }


  public Texture2D[] LoadTextures() {
    textures = Resources.LoadAll<Texture2D>(assetPath);
    return textures;
  }


  public Texture2D GetTexture(int loadOrder) {
    Texture2D texture = (loadOrder < 0 || loadOrder >= textures.Length) ? texture = null : texture = textures[loadOrder];
    return texture;
  }
}

\---

/// SkyLayer.cs
using UnityEngine;
using UnityEngine.UI;

public class SkyLayer : MonoBehaviour
{
    public SkyController skyController;
    private RawImage rawImage;
   
    [SerializeField] public bool disabled;
    [SerializeField] public int loadOrder;
    [SerializeField] public bool staticSet;
    [SerializeField] public bool speedSet;
    [SerializeField] public float speedCustom;
    [SerializeField] public bool mirrorLayer;
    [SerializeField] public int mirrorSpeed;

    public float speed;

    void Start() {
        if (disabled) gameObject.SetActive(false);
        skyController = FindFirstObjectByType<SkyController>();
        rawImage = GetComponent<RawImage>();
        SetTexture();
    }

    void Update() {
        if (skyController.textureReload) {
            SetTexture();
            skyController.textureCount++;

            if (skyController.textureCount > skyController.textures.Length) {
                skyController.textureReload = false;
                skyController.textureCount = 0;
            }
        }

        rawImage.uvRect
            = new Rect(rawImage.uvRect.position
            + new Vector2(SetSpeed(), 0)
            * Time.deltaTime,rawImage.uvRect.size);
    }

    void SetTexture() {
        if (skyController.GetTexture(loadOrder) == null) {
            Destroy(gameObject);
            return;
        }

        Texture2D texture = skyController.GetTexture(loadOrder);

        rawImage.texture = texture;
        texture.wrapMode = TextureWrapMode.Repeat;
        texture.filterMode = FilterMode.Point;

        RectTransform rawImageRect = GetComponent<RectTransform>();
        RectTransform parentRect = transform.parent.GetComponent<RectTransform>();

        rawImageRect.sizeDelta = parentRect.sizeDelta;
    }

    private float SetSpeed() {
        speed = staticSet ? 0f :
           
speedSet ? speedCustom :
            mirrorLayer ? (mirrorSpeed + 1) * 0.005f :
            (loadOrder + 1) * 0.005f;
        return speed;
    }
}

https://redd.it/1hxjaw2
@r_Unity3D
Weird way to set Cinemachine Camera's Tracking Target at Runtime

I feel like I am missing something. My player object gets spawned at runtime, and so I cant set the target in the inspector. Before using Cinemachine I had a CameraFollow noscript I just referenced. But with Cinemachine it feels so clunky

I have my Main camera that has the CinemachineBrain on it
I have a Vitural camera
I have a player spawn noscript that grabs a reference to the Main camera
That I want the noscript to, after it spawns the player, Pass the player transform to the Main camera, to the CinemachineBrain, which finds the current active camera, and then applies the player transform to the Tracking Target of that camera.

What I find weird is when you try to find the active Virtual Camera that the CinemachineBrain is using, it gives you an interface (ICinemachineCamera), not a reference to the actual VCam (CinemachineCamera)
And what makes it even worse is in older version of Cinemachine that ICinemachineCamera had a Follow and LookAt var, in fact if you head over to the documentation IT STILL SAYS IT HAS THIS! Yet, if you look at the actual noscript those are gone... like What?!?! What kind of software development does that, not a depreciated of Obsolete tag, just gone, and then not update your documentation even. This is why I hate using 3rd party systems, But this was bought by Unity and everyone says it's amazing so I started using it.

So the solution I found (Here) is so weird and messy, I am thinking there HAS to be a better way to do this, Surely setting follow targets at runtime is a common enough function there is a streamline way to do it.

My janky solution
if (mainCamera != null)

{

CinemachineBrain cinemachineBrain = mainCamera.GetComponent<CinemachineBrain>();

if (cinemachineBrain != null)

{

ICinemachineCamera virtualICamera = cinemachineBrain.ActiveVirtualCamera ;

if (virtualICamera is Component component)

{

component.GetComponent<CinemachineCamera>().Follow = playerObj.transform;

}

else

{

Debug.LogError("Active virtual camera is not a CinemachineVirtualCamera.");

}

}

else

{

Debug.LogError("Main camera does not have a CinemachineBrain component.");

}

}

at first I used this, but this is bad cause I want to be able to access the active camera, not keep log of the index and get it that way

CinemachineVirtualCameraBase cinemachineCamera = CinemachineCore.GetVirtualCamera(0);

if (cinemachineCamera != null) {

cinemachineCamera.Follow = playerObj.transform;

}

else

{

Debug.LogError("No active Cinemachine virtual camera found.");

}

https://redd.it/1hxjz1n
@r_Unity3D
Help with my game (pls)

Im making a flappy bird copy and I'm following a tutorial for an older version of unity which is why it probably isn't working right, but I'm not sure how to adapt it or do it properly for the newer versions. Here are some pics of the code.

https://preview.redd.it/3hfbojgh11ce1.png?width=1102&format=png&auto=webp&s=7a98eeea0e69d6386c871b64b423e03151522091

https://preview.redd.it/55dgmwwi11ce1.png?width=1018&format=png&auto=webp&s=37f81c560956eb7b168809a3efc927340c14106f

https://preview.redd.it/wdztjfck11ce1.png?width=1080&format=png&auto=webp&s=2d1a36df13d91e4297d8e4cb83fcc79b7448f01c

im trying to make a trigger to add a score for each obstacle you pass, and the code was working fine until I added the 'collisiontriggernoscript' and i got a bunch of errors,

any help or tips are much appreciated.

:)

https://redd.it/1hxm95z
@r_Unity3D
Designer Looking for Programmers and Coders

Hello everyone

My name is Ok_Suit/Joey

I am an indie game designer working on a rogue like dungeon crawler which gets heavy inspirations/can be thought of as an amalgamation of the following

The Binding Of Isaac

Rampage

Infectonator

Zombies Ate My Neighbors

Nuclear Throne

I currently have one artist and a programmer, we are working in Unity and I am living/working in the North Eastern USA



I have one programmer and one artist with me

You'd have to sign an NDA for the "meat and potatoes" so to speak (Nothing against anyone, just careful and have had close calls before)

But we currently have a playable prototype (I can email it)

And I am looking for additional programmers, coders, and a sound/music designer to finish the game and expedite the process of development

Feel free to PM me if interested, but know that if you do decide to join you will get credit, skill growth, and revenue share once the game is ready.

Feel free to PM me if interested



https://redd.it/1hxp0c1
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
How do you use pixel perfect cameras for only specific layers ? Because Pixel Perfect component is not working if I use a stacked camera (as overlay) of the main camera. So I don't know how to only use pixel perfect on any other layers than my UI (that is blurry under pixel perfect).
https://redd.it/1hxr45b
@r_Unity3D
Unity PlayStation 2 Exporter (v0.0.1)

https://github.com/distrohelena/ps2unity

Hello! This is an old project of mine that I wanted to do a video on but never really got the time, and I've decided to open-source it.

I've had plenty of experience developing exporters, as my job in 2014 was developing a Unity/Unreal exporter for JanusVR. Also working on a project to convert C# to TypeScript which is currently working but closed source for the moment.

Always wanted to work with old hardware, specially the PlayStation 2, as that was my childhood console. As most old consoles, there are a ton of homebrew code available, but no real game engines to facilitate actual game development. So, I decided to write an exporter for Unity.

Features:

- 3D Models
- Camera
- Lights
- Tesselation: Big triangles on the PS2 get easily culled, so we can tesselate to make them smaller.
- Lightmaps: We extract the lightmaps, and convert from HDR to SDR with a specific exposure.
- Code Conversion: C# to C++ code conversion (very rudimentary, but does work). Requires manually building the output code inside the ps2engine project.
- DirectX Windows version: Debug on Windows, the C++ version of the engine is cross-platform, and just loads different renderers based on the platform.

How it works:

- Unity C# project, ps2unity. In it, we export the data from the loaded scene
- ps2engine: A multi-platform C++ engine, designed to read the format data exported from it. We have a PS2 and a Windows version that runs on DirectX. The PS2 version runs on top of Tyra, a PS2 engine.

I export 2 binary files:

- scene.ps2: Contains the scene configuration, as what objects are where and what assets are they using.
- assets.ps2: Contains all assets used by the scene.

Those are ready for PS2 loading, and need no transformation (like texcoords are Vector4s, as that is the format that is expected by the PS2. At least what I could get working ;) )

C# code is converted to C++ using Roslyn as the analyzer. This part is really rudimentary, but does work for very simple noscripts (like moving the camera with the gamepad).

https://imgur.com/a/MAGZGIQ

Of course, this needs A LOT of work to be a fully fledged exporter. We need a physics engine that can be optimized, and ways to load/unload meshes on demand, and to configure all that. I would love to keep working on this, but I've been out of time for a while, and I have some other big projects running in parallel that I'll love to share with the community once they're working!

For now, I leave the source-code live for anyone who wants to take a look, and am open to help/discuss development. The system is somewhat ready to support other platforms, and I really wanted to get it working on the PlayStation 1/N64/PSP. Would be fun!

Last point, I was thinking about re-working this for Godot, but I'm not experienced in that engine enough to know how to grab the data needed for the export.

https://redd.it/1hxlqt5
@r_Unity3D
I'm currently having an issue programming a multiplayer game that uses two controllers.

I'm trying to program a two player multiplayer game that uses two controllers; one per user. However, when I tried to control the first player with a singular controller while having both controllers plugged in, the controller ended up controlling both players while the other controller plugged in doesn't do anything.

I tried implementing this idea by creating two separate noscripts that handles user input and assigns a controller to their designated player gameobject's .

The following is player one's noscript, where its controller is assigned

public int playerIndex = 0;
private Gamepad assignedGamepad;
void Start()
{
// Assigning Controller To The Player
var gamepads = Gamepad.all;
if( playerIndex >= 0 && playerIndex < gamepads.Count)
{
assignedGamepad = gamepadsplayerIndex;
}
}

The following is player two's noscript, where it's controller is assigned

private Gamepad assignedGamepad;
public int dioIndex = 1;
void Start()
{
var gamepads = Gamepad.all;
if (dioIndex >= 0 && dioIndex < gamepads.Count)
{
assignedGamepad = gamepadsdioIndex;
Debug.Log("Player 2 is connected");
}
else
{
Debug.LogError("Player 2 isn't connected");
}
}

https://redd.it/1hxskha
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
When you learn to make a character move for the first time, but it’s not exactly what you wanted.

https://redd.it/1hxla93
@r_Unity3D
Put my game down for a week or two to take a break, and came back to a new bug. Both enemies and Player are doing damage just by looking at each other, and I can't figure out what changed? I didn't touch the code for these and it was working before. Anyone have any ideas?

https://redd.it/1hxvlda
@r_Unity3D
Unity Overlap Painting

Hi, I’m looking for a specific shader in Unity that would allow me to paint on a plane during runtime, similar to painting on a canvas.Here’s the behavior I’m aiming for:

I have three colors in the palette: the default color (the base color of the plane), and two brush colors (blue and yellow).
When I paint over an area that has already been painted, the spot will change to the new color, but the previous color will remain active, so I can continue painting with it elsewhere. In other words, if I paint the same spot twice, the spot’s color will update to the new one, while the previous color is still available for further painting.

Previously, I attempted to paint using meshes (connecting triangles to form the brush shape), but I couldn't figure out how to update the color when painting over the same area.If anyone knows of an asset or a method to achieve this effect, please let me know. I’d really appreciate any help!

https://redd.it/1hxtvz3
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
If you hate coding or designing UI like I do, I have found this awesome free UI resource in Unity Store.

https://redd.it/1hxj6sk
@r_Unity3D
This media is not supported in your browser
VIEW IN TELEGRAM
Don't mind me, just having fun exploding my balls with DOTS Physics :]

https://redd.it/1hxy4xl
@r_Unity3D
Crazy amount of shader bloat in Unity 6?

I've noticed my Quest 2 builds breaking in Unity 6.

When I have 6 level of graphical settings, Unity actually appears to compile every single shader combination for every possibly URP graphical setting that can happen at runtime.
For example, if you switch terrain holes on, I believe it instantly doubles the number of shaders you have. Now, with 6 GB of ram, the game OOMs (out-of-memory) on scenes containing only 3 1024x1024 textures (!!)

When I cut out all but the lowest quality setting on my game (which really only has one quality setting on Android), as much as 400MB was cut from the build). I still see 23,000 shaders being compiled on build.

Does Unity actually have to load EVERY SINGLE SHADER combination at runtime? It's quite honestly quite ridiculous. I believe many other engines simply load only the shaders for the current graphical setting at runtime, and reload the game when you opt to change graphical settings?

My windows builds which do have higher graphical settings now actually take longer to boot even on an SSD with a Geforce 4070 Ti than my Quest builds, and it looks like the engine compiles 230,000 variants of the Simple Lit shader (!!)

https://redd.it/1hxx3ba
@r_Unity3D
Combat Improvements for my Soulslike game Trial by Fire.

https://reddit.com/link/1hy0egr/video/mch8f03st4ce1/player

Added quite a lot of new stuff and polished existing systems. Also did the first network test with a friend of mine and must say that most things work great, but some effects and sounds are not yet synced over the network. That will be a task for the coming days. Here's a list of things I did last week:

Reduced number of i-frames for the roll
Created better hit colliders so attacks can miss if not properly timed
Changed the environment (again...)
Footsteps on different surfaces and these are synced over the network
New model for the player
Aggro system for the enemy, it will attack the one dealing most damage (will incorporate more factors later)
Heavy attack for both the enemy and player
Hit react / Knockdown (after heavy attack) effect on enemy
Hit react resets basic attack cooldown
Knockdown will taking longer for enemy to recover

I'm going to work on a ranged type of enemy and syncing effects and sounds across the network.

https://redd.it/1hy0egr
@r_Unity3D