#archived-code-advanced

1 messages · Page 79 of 1

hardy jacinth
#

So you want to get it in the rotated camera space, which is R and U

#

So you basically want P_R and P_U

#

you get that using dot product, which is essentially dot(P, R) (|R|=1, length of P is inside)

#

dot(P,R)= PxRx+PyRy

#

and that dot product can be represented by multiplying row vector R and column vector P

#

the same situation happens with U

#

so ONLY NOW you notice, that you can actually use single matrix where R and U are row vectors to get a final P' vector

#

to explain what you did here a bit more

#

in the code you linked, the matrix they make is used to transform from non-aligned camera space (rotated at (0,0)) to rotated one (aka your standard cartesian-like coordinate system).

#

What you tried to prove with what you wrote is that "this matrix times it's transpose gives you identity"

#

but the first matrix was essentially a rotation matrix

#

and transposed matrix is not an inverse rotation matrix

#

tranposed matrix is nothing special. What you should have wrote instead is use X_r, Y_r, X_u, Y_u (R, U components of X, Y to go to RU basis) in one matrix, but R_x, R_y, U_x, U_y in the other (X, Y components of R, U to go to XY basis again)

#

you should treat a matrix like an operator/function that transforms things from one space to things into another space, and check if "inputs and outputs" of consecutive matrix multiplications "match/operate on the same space"

#

which your transpose didn't do

#

no wait a second

#

I just reviewed my knowledge about transposes a bit and what you have above should be correct

#

and because r, b, u vectors form an orthonormal basis, their dot product is always 1 when it's the same two symbols and 0 when it's not

#

so it works

#

👍

slow remnant
hardy jacinth
#

it works, those vectors are independed, they form orthonormal base

#

meaning that they are all perpendicular

#

and of unit length

#

and perpendicular vectors have dot product = 0

slow remnant
#

omg

#

I am so stupid

#

Forgot about that

hardy jacinth
#

shit happens, as you can see

slow remnant
#

Now the proof works

#

Sorry, it should have ended much-much earlier

#

Thank you very much!

hardy jacinth
#

np, on the plus side I got an algebra refresher of my own :P

slow remnant
#

XD

lilac lantern
#

quick question, can a lambda expression be removed from a listener like this?

    public void OnEnable()
    {
        moveButton.onClick.AddListener(() => move?.Invoke());
    }

    private void OnDisable()
    {
        moveButton.onClick.RemoveListener(() => move?.Invoke());
    }
thin mesa
#

no. either store the lambda in a delegate variable or use a regular method instead

lilac lantern
#

thx

real blaze
untold moth
#

Are you sure that's an advanced coding question?

real blaze
#

still, I believe using functions for subscription is generally better practice

jolly token
#

I prefer the Rx style subscription better, that you can Dispose later 😌

hardy jacinth
#

I think I managed to make source generators work, even more so — inside assemblies. For now in editor only and it still crashes

#

Is there a way to debug source generators ?

hardy jacinth
#

I try and try but still get errors like:
SDF.SourceGen/SourceGenerators.GetComponentGenerator/TransformController_Components_g.cs(7,10): error CS0103: The name 'GetComponent' does not exist in the current context.

#

ah, stoopid:

  • in my original annotated class I had a class without partial and inside a namespace
  • from the source generator I produced a partial class without namespace
real blaze
#
Action x = () => Console.WriteLine("1");
Action m = null;
m += x;
m();
x += () => Console.WriteLine("2");
m();

output:

1
1
real blaze
# hardy jacinth Is there a way to debug source generators ?

not as far as I know, but you can inspect the generated code at the location in the image in Visual Studio. and when you open it, Visual Studio analyzes it like normal scripts, with all the error explanation and whatnot, so the errors should at least be clear

hardy jacinth
#

yeah, that I do, but bu source generator crashes at some point and I was thinking it would be good to step by step throug hgenerator code

#

I use Rider but it also gives some readable error logs

#

rootNamespace does nothing special, it just makes new scripts get generated with namespace <rootNamespace> {...} right?

#

it's not magically putting the files in the rootNamespace, I still have to manually use namespace <com.company.package>.<DirOrAssembly> right? othwerise the files would land in global namespace

#

yup, it seems like that

stuck plinth
real blaze
real blaze
hardy jacinth
#

with this I can set root namespaces for all of my assemblies in unity, then deselect appropriate directories as namespace providers

real blaze
hardy jacinth
#

this way any annotated record inside namespace will also generate with appropriate namespace

novel plinth
#

also not really following the conversation 🤓

real blaze
# stuck plinth i get how this looks like copying but remember `+=` is an assignment, you're rea...

so here's what I found. delegates are immutable, so like any other value type, they are copied upon any assignment. but since the methods/lambdas inside them are stored by reference, it might sound like they're reference types. when we subscribe or unsubscribe a delegate, we're just subscribing or unsubscribing the method references inside that delegate; these methods are stored as groups, so m -= (m+m) doesn't make m null (since m+m creates a new group); this is why m=x; x+=n; will not make n a part of m, since x+n is a whole new method group

#

if we really wanna just simply pass in some delegate to some Manager.Entered instead of a fucntion, we can in the simplest form just do Manager.Entered += () => myDelegate?.Invoke(); ; this will pass myDelegate as reference (it captures it, in c++ terms speaking) , so then any changes to myDelegate will reflect on the Manager.Entered

real blaze
novel plinth
#

wdym? thats just the good ole event-delegate 😄

#

but nice you solved it 👍

plucky laurel
#

by side processor you mean another thread?

#

not possible im afraid, afaik

#

doesnt matter, unity api only allows calls from main thread

#

there are very specific api's you can use with Jobs system

#

i dont know if there is an alternative for find methods that supports jobs

compact ingot
#

A manually managed cache of all instantiated objects packed into a native array and your own search function.

#

But such a thing would be contradictory to parallelism/isolation guarantees that jobs tries to give

real blaze
#

but it's the only way to use main APIs

#

unless you really dive in and make a whole system around just that

novel plinth
#

There's new api since 2022 that's much faster called FindAnyObjectOfType

compact ingot
#

whatever you do, you will have sync points in your parallel code. This is equivalent to the unity main thread and while it would be nice of unity to let us shoot in our own feet under the assumption we are smart enough to not muck up the engine’s internal assumptions, we just can’t (most of us anyway). But if we decide unity is just a renderer/view layer, we can actually do whatever we want and make it performant in our separate, highly sophisticated and threaded game code

#

Jobs are a way to do just that with training wheels.

sage radish
novel plinth
radiant wave
#

VR Project, Unity 2020.3.33 UDRP to Oculus 2. Project set to Android Build
We're switching to Air Link for several reasons. Can I increase the Graphic Quality (a lot) when not builingd to run natively? Any suggestions what's within the limits?

jolly token
real blaze
#

yes, functions are by reference

#

which is what I said (later on)

jolly token
#

So you can remove (-=) it by that reference just fine

#

I didn’t read the conversation after ping lol

misty glade
#

I'm building an open world (ish) game with hex based tiles. Internally I'm "chunking" them for various reasons (persisting, world generation with biomes for an area, etc). I'm using TileMap to render them, and I can't seem to find any info on chunking or culling - Unity says that it won't draw the tiles on screen, but I'm not sure if I need to be unloading them. I do have functionality to redraw/reload an area of the map that I'm near (it's quite large - you can see when I tab over to the scene view) but I don't know if I should be manually unsetting tiles or clearing the TileMap and setting all the tiles manually - as you can see it could be a few thousand tiles.

Thoughts?

#

Closest info I can find is one random person's blog that stated:

#

(but I can find no such.. functionality in the API for TileMap)

plucky laurel
#

you just swap them around when moving

#

i havent used tilemap api, wrote my own

#

i have no idea how it works internally, but i know its not lightweight, each tile is an object and allocates

misty glade
#

That's gonna be a lot harder.. I thought of that originally but it got really complicated since I ended up doing a ton of gymnastics to figure out the player's position and world position and tile position

plucky laurel
#

well, those things are just things you do

misty glade
#

hm... I suppose I could track the player position (in the world) and manage my map (which is tile-agnostic) and then just.. draw the tilemap with some offset and set the entire thing to that offset position....

#

redrawing the map chunks would be expensive though since I don't see an easy way to unload tiles or specify blocks

plucky laurel
#

to me its a standard thing, coordinate conversions, world shifting, local/global etc

plucky laurel
#

with tilemap api specifically?

misty glade
#

yeah, we joked about it internally - the star trek solution .. that scene where spock gives scotty (in the past) the warp formula and he's like "oh it never occurred to me to move the universe instead of moving the ship"

plucky laurel
#

rendering and physics will break at distances larger than about 5k units from zero

#

with 1m/1u scale

misty glade
#

So.. my game will need to track state of all those tiles (I call them Blocks to distinguish) - they have a unique coordinate, which I can convert to/from a cartesian coordinate using unity's "odd-R" system (odd rows shifted to the right).

Each Block also has a unique "Chunk" coordinate (in the vid above, they're drawn with a different tile).

I only keep a limited number of chunks (of blocks, not tiles) in memory. My plan was to unload TILES when I unload chunks (that are too far from the player to care about).

#

And yeah, I was aware of the float instability but thought that it wouldn't impact me until +/- more like 1m units from the origin. There's no physics in my game, but there will be some lerping and stuff so maybe.. yeah, I'm probably gonna have to just move the universe.

#

actually I can test this.. hang on a sec, i'll just set the start position to 1m,1m and walk around a bit

plucky laurel
#

it starts to break down slowly, first shadows start glitching, then verts

#

anything that requires float precision goes haywire with more distance

#

anyway, unloading tiles sounds like something that shouldnt happen in the first place

#

ideally you should have one instance of each tile, and simply set the reference, if tilemap api supports it

misty glade
#

I'm familiar with the pattern - you're saying that I need to implement it myself? or telling me unity's tilemap already does that..?

plucky laurel
#

i dont know if it does

misty glade
#

I'm.. feeling like i read that it is, but I can't confirm that.. lemme google a sec

#

I did find this on learn.unity:

#

(re chunking - but it just looks like it refers to reducing the draw calls, not what I was thinking of as a "chunk")

plucky laurel
#

that is renderer yes

#

if the world is large enough to require shifting, i would consider starting with your own coordinate system, which will be used by game logic instead
the objects in the scene will then be considered "views" and convert to local zero space

misty glade
#

yeah, I have that - but I was trying to make the "my coordinate system" map 1:1 with "unity worldspace coordinates"

plucky laurel
#

if its abstracted well enough it wont feel like gymnastics

misty glade
#

it looks like I'm ... probably not going to be able to do that without a little bit of work in a view/viewmodel-to-model type translation

#

Yeah I wrote a lot of code already to translate. I'm actually using cube/axial coordinates for the hexes since it makes ... working with them a lot easier.. so I have a lot of code that converts the cube/axial coords to cartesian so that unity can draw the tile in the right place

#

I'm just going to have to add a bit more to make the whole tilemap draw in the correct location.. but that means everything else will have to have that offset, too.. Like.. I'm probably going to need to write a unity class that translates world position to "my game position" for anything that would traditionally use .position

#
  public struct GamePositionActual
  {
    public decimal X { get; set;}
    public decimal Y { get; set;}
  }
public class GamePosition
{
  public GamePositionActual Position {get; set;}
  public Vector2Int Offset {get;set;}
  public WorldPosition => new Vector2(Position.X - Offset.X, Position.Y - Offset.Y);
}

or something like that

plucky laurel
#

it should be flyweight right?

#

why wouldnt it, it should

radiant wave
#

SceneManager.UnloadSceneAsync() seems to block our main thread although running in a coroutine. Are we doing something wrong there?

var sceneName = LevelLoader.Instance.GetSceneName();
var scene = SceneManager.GetSceneByName(sceneName);
AsyncOperation asyncLoad = SceneManager.UnloadSceneAsync(scene);
if (asyncLoad == null)
    Debug.LogError($"AsyncLoad is null on {gameObject.GetInstanceID()}");
while (!asyncLoad.isDone)
{
    elevatorMoveElapsedTime += Time.deltaTime;
    yield return wait;
}
#

theres a main persistance scene that handles this loading/unloading. we always load the new scenes additionally

compact ingot
radiant wave
#

Unload is causing the problem

compact ingot
#

You can work around it by (un)loading smaller chunks and making your init/finalize code do less

radiant wave
#

I see. the level actually consists of some amount of single rooms. before unloading I could destroy a single room per iteration and then unload. That might work.

compact ingot
#

You can try (un)loading stuff more granularly with addressables

radiant wave
#

unfortunately the environment is procedural

compact ingot
#

you are still loading/destroying stuff though

#

maybe don’t destroy, instead reset and reuse?

radiant wave
#

but at a smaller rate per frame, soi the lag might be smaller.
I'm fine with it taking time (the player is in an elevator scene at that time), but it's VR so we cant afford the loading icon to pop up

long ivy
#

are you testing it in a build or in the editor? iirc unloading a scene in the editor is synchronous, even with the async method

frozen flax
#

Does this work? I need to contact all clients and get their player script and call some function. [ClientRpc] private void ShowAnnouncementTextClientRpc() { foreach (var player in NetworkManager.Singleton.ConnectedClientsList) { if (player.PlayerObject.TryGetComponent<NetworkFPSController>(out var fpsController)) { fpsController.Announcement(); } } }

frozen flax
upbeat path
frozen flax
#

But nothing

upbeat path
#

then the method is not being called

frozen flax
upbeat path
#

what?
From what you have shown and said so far, I doubt whether you are ready to do multi-player

frozen flax
#

If(server || host) {show...}

upbeat path
frozen flax
#

But why?

upbeat path
#

it's your code, not mine so I cannot know

frozen flax
#

Here it is

#
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;

public class ServerManager : NetworkBehaviour
{
    public static ServerManager Instance { get; private set; }

    private void Awake()
    {
        // If there is an instance, and it's not me, delete the GameObject.
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
        }
        else
        {
            Instance = this;
        }
    }

    private void Start()
    {
        if (IsServer)
        {
            Debug.Log("ServerOnline");
ShowAnnouncement();
        }
        else
        {
            Debug.Log("Hello client");
        }
    }
}
``` @upbeat path
upbeat path
#

network is hard, you needs lots of experience to get it to work well

frozen flax
upbeat path
#

Sorry, I don't wish to appear rude but anyone who calls a method a void is not ready to do network code

steel snow
#

are unity jobs blue in the profiler or green ?

#

if using burst

wary blaze
# radiant wave I see. the level actually consists of some amount of single rooms. before unload...

Yes, do this. When using UnloadSceneAsync, both the deactivation of the game objects in the scene and destruction of the game objects occurs in a single frame.

You can usually get away with performing multiple deactivations and/or Destroy calls in a single frame, however for Destroy at least (and maybe deactivation), the operation is not performed until the end of the frame, so there is no way to figure out how much frame time each operation will take up. So you can either be conservative and just perform one operation/frame or you can test to try to find a happy medium between the total time it takes to deactivate/destroy everything and the performance hit/frame.

lavish thicket
#

Hi lovely people, where can i ask a question about webgl ar application? thanks in advance ❤️

west jolt
#

I have the following problem: when I close the game a component calls a singleton in OnDestroy and when the singleton is not yet loaded, it must be created whilst the game is quitting.
So I get the following error: Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?).
This is the static instance:

static Locator instance;
static Locator Instance
{
    get
    {
        if (instance == null)
        {
            instance = FindObjectOfType<Locator>();
            if (instance == null)
            {
                instance = new GameObject("Locator").AddComponent<Locator>();
                DontDestroyOnLoad(instance.gameObject);
            }
        }
        return instance;
    }
}

The only solution I see is to not create the instance when the game is quitting and every time I want to use the Instance property I have to check if it is not null first. But it isn't very elegant :/ Any ideas?
I probably could also attach the Locator script to a random game object in the scene, thus avoiding spawning a new gameobject... but that's even less elegant

compact ingot
west jolt
#

The same happens with OnDisable :/

compact ingot
#

you can always check if the object is still valid

#

if (this) { }

#

this will return false if the object was destroyed

west jolt
#

I think you're recommending the first suggestion of mine, which is to check if the Instance property is null every time I want to use it.
Note: this Instance property is private and I use it in "public static" functions.

compact ingot
#

Well, you are using a smelly pattern and there isn’t much you can do but check validity

#

ideally you’d not use any of the patterns that cause the issue

west jolt
#

Alright, thanks

#

I don't usually recommend singletons, but sometimes is just the most pragmatic solution.
If you're interested, what I ended up doing was at the start of every "public static" function, I try getting the instance using an if statement with a TryGetInstance function inside instead of using the property and checking for null, and the body of the function goes inside the "if" brackets hehe

dusty wigeon
west jolt
dusty wigeon
#

In the actual build, I do the instantiation in the first scene async while in the editor I do it sync.

#

It prevents random spike and it make possible to have these singleton run the Update function if needed.

west jolt
#

Interesting, sounds like a good idea! In my case, my singletons are too few and too simple to benefit from async loading. Thanks for sharing though!

cerulean minnow
#

What's the best way to get a reference to the network player that has spawned in? I have the main camera in scene and it resets to the most recent player spawned for my follow camera script. And If I set it to child the player object when player spawns in , one player seems to control both cameras .. each player should spawn in with they own camera.

stuck onyx
#

does anybody know any free/paid courses unity oriented for advanced coding? I'd like to introduce some in the company I work for and I could find one in spanish but Im not able to find one in english.
Architecture, assemblies, Software design patterns.... would be stuff that I'd be interested into introduce to my coworkers. Any suggestions?

tiny pewter
#

unity is not a hardware.....maybe you are asking for x86/arm architecture and different architecture has its own set of ISA

cloud crag
#

Thank you very much for your time for explaining. Really appreciate that! Thank you very much, I tried using StateMachineBehaviour but had some kind of infinite loop, it was entering same state again and again but this solution seems correct. thanks again!

stuck onyx
#

We updated from Unity 2021.3 2022.3 and we are facing this issue, tried removing and installing again assets like the FEEL one that is listed there but its still not finding the assembly index, tried removing the whole Lib folder and rebuilding, reimporting assets button... rebuild project..... nothing works, could anybody give me a hint of what to do?

regal olive
dusty wigeon
stuck onyx
#

so, i uninstalled and installed again but all the same

dusty wigeon
#

I do not think that reinstalling an asset will change.

stuck onyx
#

what do you suggest?

dusty wigeon
#

As your own assembly has an issue

stuck onyx
#

i tried tons of things since yesterday

#

yeah i went now to rider

#

and tried to do this:

#

then i saw tons of dependencies were untagged

#

tagged them and tried to rebuild

dusty wigeon
# stuck onyx

Unity does not work with Visual Studio/Rider dependency workflow

#

You could try to regenerate the solution

stuck onyx
#

what can I do then? im totally lost

dusty wigeon
#

Also, you could try to redo the upgrade. Maybe with a version that is closer.

stuck onyx
#

regenerate the solution? from Rider?

dusty wigeon
stuck onyx
#

you mean the option in preferences "regenerate projexct files"" ?

#

that i already tried with no success

dusty wigeon
#

Then, I would start over.

stuck onyx
#

damn

dusty wigeon
#

I upgraded a project from 2017 to 2022 and did not have this particular issue. So, I believe your best bet is to start over.

#

Be sure to delete the library folder.

#

Before opening the project.

stuck onyx
#

hmm i did that later now that i think

#

maybe that messed it up

#

okay ill give it a try, thanks a lot for your help im literally since yesterday with this

chilly drum
#

Hello guys, I saw a strange problem, I multiplied a value by 100, and as you can see, it is 0.8, but when it is multiplied by 100, the result returns 79.99999, why is it like this?

#

I came before and reduced this much from the original amount that was first

like this: 1.28 - 0.48 => 0.8

flint sage
#

Because it's a float and not all values are representable in floats

stuck onyx
#

@dusty wigeon should I also remove the obj folder?

#

hmmm i think those were the ones that i was having problem with, not sure if has to do with it

dusty wigeon
hardy jacinth
# dusty wigeon https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

TL;DR, floating point numbers (float, double) are only approximates of real values, because they are represented on 32/64 bits as (sign bit, exponent bit, mantissa bit) which are interpreted something along the lines of sign*(2^exponent)*(1+mantissa). They are the most accurate near 0. They are less accurate the bigger (absolutely) they get, for example 32 bit floats between 2^24 and 2^25 round to multiples of 2. To compare floating point values don't use x == y. Use something like abs(x-y) <= epsilon where epsilon is some small value, e.g. 1e-4, depending how precise you want to be. Summation and other repeated actions on floating point values introduce numerical errors to the final result. Special care must be taken when dealing with floating points.

dusty wigeon
hardy jacinth
#

of course, just wanted to summarise key concepts because OP seems to be a beginner and the source albait very useful is also a very scary looking wall of text :P

hardy jacinth
#

It would be good if some unity staff could respond:
what version of roslyn (Microsoft.CodeAnalysis package to be precise) is actually supported? Docs say 3.8.0, I checked 3.9.0 works, so maybe ver 4+ could be working?

woeful kraken
hardy jacinth
#

My main point of concern is that versions before 4 use old V1 API (SourceGenerators + SyntaxReceivers) which can be slow for bigger projects, while 4+ uses v2 API with incremental generators

hardy jacinth
frozen flax
#

Is there way to spawn objects when server started? Unity netcode for gameobjects

tough summit
#

I'm trying to have an easy way to maintain a list of prefabs via the Unity Editor and these prefabs will be used to spawn gameobjects during runtime. At runtime, I go through every tile part of a Tilemap that the game designers have populated with specific sprites, so I use the name of the sprite to know what type of game asset (furniture) should spawn at those particular coordinates in the Tilemap. I have a class named Furniture, and there will be several types of furniture such as Couch and Table that will inherit from Furniture. Furniture will have a factory to spawn the different types of Furniture. Rather than creating a variable of each type of Furniture for each different prefab, I was thinking of having a KeyValuePair<Key, Value> where the Key will be a string that will be entered in the Unity Editor by the game designers as "Couch" and the Value will be of type Furniture and the game designers can drag the prefab into the Value's corresponding slot. However, Dictionary type is non serializable, so I cannot do this easily except use a List<Furniture> type and think of another way to correlate the prefab to the type of furniture at runtime to select the correct prefab to use to spawn a particular piece of furniture.

sly grove
#
[Serializable]
public struct FurnitureInfo {
  public string name;
  public GameObject prefab;
}

[SerializeField] FurnitureInfo[] furnitures;
#

you can then build a Dictionary from that in Awake

tough summit
#

thank you @sly grove. I hadn't thought of that. I'll give that a try next 👍🏻

green crane
#

What's the best way for doing this:

  1. Storing a series of flags that will determine if a player gets ending 1 or ending 2.
  2. Storing a series of true and false variables in a singleton event manager. Every time an object with a relevant bool is interacted with, set the flag to true or false depending on the interaction (object should send a call to the event system, which will disable or enable the bool respectively). Then, use these variables to determine which content (scenes) to show the player.

eg. If player uses an ax to break down the door, he will see a different room compared to if he did puzzle A.

#

I was going to use an event manager that simply keeps track of which objects are interacted with. Are there any downsides to this?

Trees don't seem nearly as efficient because the player can go from

A > B > C
or
A > D > C

#

I would also use a scriptable object to store all the bools and flags, but can they really be interacted with by the singleton manager? I have a lot of singletons running around too already.

hardy jacinth
#

or use a unity tag system

hardy jacinth
# green crane What's the best way for doing this: 1. Storing a series of flags that will dete...

you could take a look at https://www.youtube.com/watch?v=oPpzT6JKGk0, around 3:40 he talks about his tools Cartographer and Typewrighter. Both of those tools seem to be doing what you want, he talks about their architecture in his videos

=== Wishlist Astortion on Steam ===
https://store.steampowered.com/app/1993980/Astortion/

=== Support the Channel ===
https://www.patreon.com/aarthificial

=== Livestreams on the Second Channel ===
https://www.youtube.com/aarthificial2/about

=== Tools I'm using ===
JetBrains Rider
Unity
Motion Canvas
Adobe Premiere Pro, Audition, Photoshop

==...

▶ Play video
dusty wigeon
# green crane What's the best way for doing this: 1. Storing a series of flags that will dete...

Beware with the usage of event. When using events, you sometimes end up in a position where you are not able to correctly resolve the state of the game with saved flags. Such situation can happens if the order of the events have an importance and you only save flags.

A concrete a example would be the following to scenario:

  • Door X listen to event B (Open Door) and event A (Close Door).
  • Puzzle B is marked as resolved, event B is sent.
  • Door X opens.
  • Puzzle A is marked as resolved, event A is sent.
  • Door X closes.
  • Player Save Game and Quit.
  • Load Game.
  • Puzzle A is marked as resolved, event A is sent.
  • Door X closes.
  • Puzzle B is marked as resolved, event B is sent.
  • Door X is opens.

You end up with two state:

  • Door X is closes when doing the game.
  • Door X is opened when loading the game from the same state.

You have two options in this situation:

  • Save the state of the door. (This is the most flexible - You can by example have a "destructed" door state which as no link the actual state of the game)
  • Define the state of the door by the state of Puzzle A instead of simply listening to an event. (This is the most robust way. - There is no way that the door is in a wrong state given a particular state of the game)

Both solution are viable, the best is two use both through the game. Personally, I have been dealing with this with the controller connection state. Having the option to disconnect and reconnect the controller at anytime for local multiplayer games with multiple controller state was making things heretic when trying to sync the controller state and the game state. Instead, I defined the controller state from the game state. (Who has what controller and what is the current action mapping. (Menu vs Game))

green crane
hardy jacinth
#

+1 for above. Personally I prefer the second solution, because it's more declarative and reminds me of reactive web frameworks, where you say what something is and not how it behaves. This gives a clear dependency chain of A is X => B is Y

green crane
#

I see

#

Because door A can be in a different room from puzzle A, which complicates things a LOT.

#

And there can be multiple events that lead to door A opening.

Like let me give an example from my script in C1.

There is a puzzle that needs you to sleep in the bed (save point) AND have not broken down a door with an ax beforehand.

The problem is, the door is 2 rooms ahead of the bed, and puzzle room.

compounding complexity the further I go...

#

Everything looks like rapidly degrading spagetthi

#

Unless I somehow find a way to store info on items like the puzzle above. So the puzzle has to constantly listen for a variable that indicates the door has not been broken down, and the player has slept in the bed.

#

Seems like I run the risk of memory leaks that way tho

#

Because I'm going to have 30 different puzzles constantly looking out for a signal even when not loaded in.

dusty wigeon
green crane
#

Unless the player himself carries a script with all the variables possible that can be assigned to him, and by doing certain actions the script checks off the action like on a checklist.

#

So the puzzle only reads this file when the player approaches it.

#

So the player walks around with a 'checklist' that is checked off when certain conditions are met.

dusty wigeon
green crane
#

Why?

dusty wigeon
#

Because this is a concern of the game, not of the player.

hardy jacinth
#

make it one centralized manager/singleton like "GameStateFactManager" or something, querry the game state via that

green crane
#

I see...

dusty wigeon
#

If you have multiple player or your player is not spawned, you cannot have the state of the game.

green crane
#

Ahhhhh ok I get it now

#

But maybe a singleton that stores a checklist of all variables would be good, and the puzzles/scenes simply reading them to check if something should appear is the best option.

#

On awake

hardy jacinth
#

if you go that route then remember also that it should be a single source of truth for your state

dusty wigeon
#

In multiple game I have worked on, we used a condition workflow for interactible object to define their state.
It looked like:

Door

  • Conditions
    -- Player has Object A
    -- Player has completed Quest X
green crane
hardy jacinth
#

that the state would not be stored separately in different objects, for example the door is open -> and you querry the door, but instead you make state of this door be defiend in this one single source of truth, and door reference it (and so do other things)

hardy jacinth
#

for example if you have Puzzle A and open doors in it, then in the central manager that holds state you store the fact that for puzzle A doors are open. When you load puzzle A, doors read that state. When something else in another puzzle wants to check if doors were open in A, it reads from the same manager, without the need to load puzzle A etc.

dusty wigeon
#

That being said, if you are going to save the state of the door, you should save the state on the door, not in a centralized place. This is way more extensible.

#

The idea is to NOT save the state of the door (with option two), and instead define the state of the door base on the game state.

hardy jacinth
#

yeah, that, the "door open" was meant to represent "a game state" that you are interested in

green crane
#

I see

#

So the state of the door is defined in the singleton that stores all the variables as mentioned above?

scenic forge
dusty wigeon
#

Depending on what you mean*

#

The door state is defined, by example, by the fact the player has finished a quest or that the player has a given item or even by the fact that the player is affected by a specfic buff.

#

Usually, it is not centralized.

#

In your case though, if your doors are only defined by if a puzzle has been finished, then you could say it is.

green crane
#

I see

#

How do I implement this? So I have a manager that stores a checklist of what the player has done

#

How does that react to the door?

dusty wigeon
#

Then on the door, you have "condition" list.

#

In the old time, we were using hidden MonoBehavior, today you can use SerializeReference

green crane
#

I see

#

So the door just stores a list of conditions it must have

#

And reads the manager on awake

dusty wigeon
#

Your condition would look like:

public abstract class Condition {
  public bool abstract Evaluate();
}

public class PlayerItemCondition {
  public bool override Evaluate() { ... }
}

public class Door {
  [SerializeReference] private List<Condition> condition = new List<Condition>();

  public void RefreshState() { ... }
}
dusty wigeon
green crane
#

Are there any materials I can look at to study this more in depth? Honestly this is a bit out there for me rn

dusty wigeon
dusty wigeon
green crane
#

Thanks!

dusty wigeon
#

The ideal architecture is tree, not a graph.

green crane
#

This is super useful

dusty wigeon
#

Dependency inversion principle is the way to achieve that.

#

However, beware to not over do it.

#

Principle are guideline

dusty wigeon
# green crane This is super useful

A guess an other concept that you would need is Cohesion vs Coupling. (There is ton of other, but I believe that most architectural decision can be express in term of coupling and cohesion)
https://www.geeksforgeeks.org/software-engineering-differences-between-coupling-and-cohesion/

green crane
#

Maybe watching some of my uni lectures

#

But all very surface level stuff

dusty wigeon
#

But, this is only my personnal opinion.

green crane
#

Yeah, true

Sadly I don't have the funds for uni

#

At least not now :/

#

So self taught it is ig

dusty wigeon
#

I have the chance of living in a place where the school cost is one of the lowest in the world.

green crane
#

Ugh lucky, where?

dusty wigeon
#

I really recommend trying to find University Curriculum and go through them. Maybe even buy a book instead of relying on Youtube

dusty wigeon
green crane
#

Ohhhh damn, well yeah what books do you recommend? Also I don't really have time to spend like hours dedicated to learning from scratch tho, I need to release demo asap catcry

#

Parents pressuring me

tiny pewter
#

there should be software engineering in any cs curriculum..

dusty wigeon
#

Just have a predefined amount of time for learning, a couple of hours per week and in a couple of year you gonna be good.

hardy jacinth
dusty wigeon
hardy jacinth
#

I believe stanford has free CS course materials?

dusty wigeon
#

They do

green crane
#

Sure! Seems good 🙂

#

I am looking into C# and programming for unity mostly

hardy jacinth
#

there is just so much different knowledge you take up in university on CS degree that it's hard to find a single source where you can learn that on your own

green crane
# hardy jacinth sounds unhealthy :)

Tbf I've never had a job in all 23 years of my life and I need to go to uni overseas in a couple years. They want me to get a job or finish my game demo

dusty wigeon
green crane
#

I see

#

Hmmmmm so I guess I should just look up coding architecture principles myself and self teach myself c#

hardy jacinth
dusty wigeon
#

This a way, but this is definitely the hardest path that requires the most dedication.

green crane
#

My friends have a uni keyfob they lend me so I just kinda... attend some lectures when I have time

#

Yeah I think I'll do it this way for now, since I'm going to be studying IT in Finland in a couple years anyway

hardy jacinth
#

surprisingly web dev in recent years has some strong concepts that translate well to good practical knowledge in general area of programming

#

e.g. various declarative frameworks with their immutable data model

#

or reactive/observable properties etc.

dusty wigeon
#

They certainly have a different approach to things than usual OOP. It can be a good source of inspiration. However, you cannot simply take what they do and apply it has is. MVVM, by example, in my opinion, is not the best way to structure a UI architecture.

#

Dependency Injection framework are not necessary as we do not need the same level of decoupuling then WEB. (There is almost no Unit test in game development)

green crane
#

Oh wow nice

#

Decoupling?

dusty wigeon
# green crane Decoupling?

the separation of previously linked systems so that they may operate independently

Inverse of Coupling.

#

In other words, in game development, you usually are able to have a good maintable code base same if you have a higher level coupling.

#

This is due in part because there is no need to have Unit Test (Which is the testing of individual function).

#

We do not do Unit Test, because the game, most of the time, evolve to fast, contains non-deterministic function and has a more interdependent structure.

scenic forge
#

Although you can refactor them into MVVM, but that's rarely how people write web frontend nowadays. Unfortunately it seems like C# side of frontend (whether it's web or native app) is still very stuck in the MVVM way.

green crane
#

I see

#

Well that's pretty interesting but also very overwhelming

brave fog
#

Hi! I have a bunch of enums about my characteristics about my charecters which are constant and generated randomly, e.g. hairType, clothesType, isNearWall, isNearLamp, Placement (Bar, lounge, Stage).

I would like to group these enums so it is easier to access them all at once, for example to character appearance enums and character placement-in-the-world enums.

The problem with creating a dictionary of lists of enums is that I wouldn't be able to autocomplete when coding, for example I would like to be able to type stuff like

"Characteristics.apperance.clothesType.dress"

I would also like to do stuff like create a function that returns a characteristic of an enum of type appearance

Like a function that can return clothesType.dress and hairType.curly

Is this possible?

compact ingot
#

and while convenient initially they don’t respond well to being serialized if there is any possibility that they might have to be changed in the future.

#

since an enum is effectively just a name for an integer, you can replace them with whatever you like that assigns a name to an integer. You could use a system of classes with constants in them, or expose the whole thing to the editor via scriptable object references. Obviously you can also nest these classes if you fancy the long names that gives you

hardy jacinth
#

most of the enums you write of seem like just simple boolean flags

devout coyote
dull kestrel
sage bolt
#

if I have an interface like

public interface myInterf {
  public float myValue { get; set; }
}

and an inheritor like

public class myClass : myInterf {
  public static float myStaticValue = 0.1f;
  public float myValue { get { return myStaticValue; } set { } }
}

will instances of myClass each store a reference to myStaticValue or is it evaluated at runtime like a funciton? I'm assuming the latter but I don't have much experience with interface inheritance.

upbeat path
#

static is one per class, so no

sage bolt
#

I mean is anything actually stored in myValue or is it evaluated to the static value as if it were a function

woeful kraken
upbeat path
#

myValue is one per instance of the class

sage bolt
#

yes but the getter just returns the static value

upbeat path
#

but as its using the static all instances will return the same value

woeful kraken
#

yeah further more all classes have access to anything that is static

sage bolt
iron pagoda
#

might as well use the static directly, though that's not always feasible

woeful kraken
sage bolt
sage bolt
woeful kraken
upbeat path
#

the value is already there. in the static variable

woeful kraken
sage bolt
#

some inheritors use myValue get and set normally, but I want some to only get from a static value

woeful kraken
#

ahh. Well I suppose jut give it a try and see if it's doable.

sage bolt
#

so most implementations would be public float myValue { get; set; } but a couple public float myValue { get { return staticValue } set { } }

#

it compiles fine

sage bolt
woeful kraken
sage bolt
#

ohh so when I do public float myValue { get; set; } in an inheritor it functions as two methods and adds in a variable behind the scenes, but if you override them it doesnt?

upbeat path
#

myValue will have a backing value, yes as you have a set, but it wont be used

sage bolt
#

ohhh I understand now, even overriding the get and set doesnt remove the backing value and doesnt then save on memory

woeful kraken
tiny pewter
#

i believe the compiler when create a new variable for the set but there is no way to interact with it unless you use pointer

sage bolt
#

I would need a GetValue() SetValue(float val) function with no backing variable to save on memory like that

sage bolt
#

I understand backing values and how getters and setters work now, thanks fellas

woeful kraken
#

Was surprised it was working in this instance

scenic forge
#

It has worked like this for a long time, and it's not an uncommon thing either.

#

It's how people implement singletons.

#

(On a side note about the backing field, in the Sharplab you can also change the result to C#, and you can see Bar indeed gets lowered to a backing field and two accessor methods)

tiny pewter
#

i use marshal.sizeof get the size, it returns one......

#

no any field is created

devout coyote
#

Whether you call it production ready or not, ms certainly seems to try to sell that it is

scenic forge
#

Eh I would think so, and well this language feature has existed for a long time anyways.

#

And yes, if your property doesn't need a backing field, compiler obviously just won't create one.

sage bolt
#

good to know, thanks

scenic forge
#

C# has a lot of syntax sugars, using Sharplab to see the lowered C# is a good way to understand how they work.

#

This is why you can use things like https://github.com/Sergio0694/PolySharp to bring some newer C# features into older C# versions, since these syntax sugars don't need runtime support to work because they are purely compile time.

hardy jacinth
#

huh, interesting, did you have any luck using it in unity?

scenic forge
#

No I haven't tried it, I guess it would be nice to have record structs though 🤔

rose mulch
#

Is anyone familiar with Ogame programming, i am trying to recreate the combat system, does anyone can help?

half swan
hardy jacinth
#

ogame programming? you mean the online space game OGame?

regal olive
#

Since I'm using abstract class for state classes - I guess I cannot make methods separately outside without reference to where variables are centralized?

hardy jacinth
#

wdym, what do you want?

regal olive
#

I'm trying to understand how I should structure variables in such a manner that makes sense. I guess one way to do it is to localize it when it enters state. But I don't know if it's the right way to go about it

regal olive
dusty wigeon
#

Also, ideally you should never have access to an internal variable. (_inputVelocity seem to be an internal variable because of it's nomenclature)

#

Encapsulate the variable in a Property.

#

And, you should never use Camera.main in an Update function.

#

Ideally, you should have a CameraManager that is able to transform the direction. (You might need to reuse that later)
And, rewrite your code for your camera orientation to

        Vector3 forward = camera.transform.forward;
        Vector3 right = camera.transform.right;
 
        forward.y = 0f;
        right.y = 0f;
        forward.Normalize();
        right.Normalize();
 
        Vector3 desiredMoveDirection = forward * verticalAxis + right * horizontalAxis;
hardy jacinth
#

imo above code is unsafe, because it may happen so that forward is (0,y,0), after forward.y = 0 you get (0,0,0) and after Normalize you get something weird

#

either you get exception, NaNs or Infinites

half swan
#

Nothing weird, just Vector3/2.zero

hardy jacinth
#

oh, ok, good to know, I assumed wrongly based on similar behavior from shaders

rose mulch
#

I have a question : if i wanted to automate the process of creating an instance of an object by receiving a input and making it the parameter or by using a variable that goes in the parameter place, it would work?

hardy jacinth
#

what you probably look for is a) #💻┃code-beginner, b) a Factory (or abstract factory) programming pattern

#

or a builder pattern

#

or a simple constructor, but like above, "What?"

#

not sure if I understand your question

rose mulch
#

lets say i have a class Badguy bg1 = new BadGuy ("VariableAsString", inputVariableAsInt)

#

Does this work?

woeful kraken
hardy jacinth
#

what does "variableAsString" and "inputVariableAsInt" mean, paint a concrete example

#

like a name and HP, e.g. "louis", 15 or what?

regal olive
rose mulch
#

These 2 parameters come from outside the method that is declaring this new instance, they come from a Variable that is a String that goes in the parameter space, that and the other is a user input Int that goes in the other parameter space when the method is called

hardy jacinth
#

you mean like that?

string name = readUserInput(...);
int age = readUserInput(...);
var badGuy = new BadGuy(name, age);

Why wouldn't it work? variables are just holders of values

rose mulch
#

Probably. just trying to figure out if i can receive the values for the instance from outside the method. Another question is: I have a base class defined in a script, and another script that defines a Ship and inherits the baseclass to define its values, now in this third script, do i need any kind of reference to this class? the base or the Ship class itself? knowing that we are talking about 3 scripts.

hardy jacinth
#

answers to those questions usually naturally come out when you try to write it yourself. Have you tried already or are you asking preemptively? If the former, then what is your problem? If the latter, then try to do it yourself first as per channel rules.

rose mulch
#

I am trying to find the best way to do something, coding is about being creative, and asking about it seems more prudent than trying coding in a way that i might find not so good in the future, i am asking for ideas in something, knowing i can do something like i am thinking open ways for me to be creative about it.

hardy jacinth
woeful kraken
hardy jacinth
#

anyone knows if Roslyn has some method of checking if a type is defualt constructible with new() ?

#

or just a plain iteration over constructors and find one without parameters

dull kestrel
hardy jacinth
#

in my custom annotated records, get fields that are default-constructible and assign new() to them in the constructor

dull kestrel
#

Well, you'd have to use Reflection which is slow.

You can Google "GetConstructor()"

hardy jacinth
#

I use Roslyn code generators and their compiler API to generate additional source code during compilation

#

I work in compile time, not runtime

dull kestrel
hardy jacinth
#

It's a great thing, a pain in the ass to set up but pays off. For example I can annotate my class with my custom attribute, and then whenever the source code of that file changes, the compiler automatically generates some other source code

#

that is recognised by both unity and IDE and doesn't physically exist enywhere in the assets, which is good

dull kestrel
#

I've thought of a few things I could do with compile-time modifications, I just haven't had much spare time to go through it.

dull kestrel
tawny imp
#

Hello, i did a TrailRenderer for my game, but this looks like blemishes around the edges. Any solution to make it look smooth?

real blaze
dull kestrel
#

I'm thinking of having some form of chemistry in a game, and however I think about it, it's not adding up in my head without doing crazy stuff.

Let's say I have Allicin (which is in Garlic), that's got a composition of C6 H10 O S2, and then Hydrochloric Acid HCl. Let's say I just want to do something extremely simple and unrealistic like add them together to get C6 H11 O S2 CL, that bit is fine. But let's say this was drinkable, like a potion. I need to be able to very efficiently check this against some kind of data and see what affect it would give.

I could have a dictionary of every possibility, however when it comes to comparing, the order matters too. This would just be expensive to check every possible combination, or would be expensive in allocations if I needed to track what has or hasn't matched. I cannot have a dictionary entry for, let's say 5^6 for each formula either.

But if I wanted to then (in the future) extend this so that C6 H10 O S2 + HCl didn't just straight up equal C6 H11 O S2 CL that then further provides issues. I cannot surely have what equates to an if statement for every possible combination of compounds that may meet.

dusty wigeon
#

Also, I'm not exactly sure what is the issue here. Can you not simply check what the object is made of ?

dull kestrel
#

I am planning on handling 100-1000+ players

dusty wigeon
dull kestrel
dusty wigeon
#

You have a server which should be performant.
You are using an item, which can hide the time by adding animation and/or vfx.
You are doing the operation once in a while.

#

You could even easily make the whole operation in a thread as it does not depends on any Unity operation.

dull kestrel
#

It can happen over seconds, there is no problem there. But I cannot create too many threads (there is a threading limit), and it cannot take that long that it's taking up processing power either.

dusty wigeon
#

You could literaly have the worst algorithm, and still wouldnt matter.

dull kestrel
#

Costs become a factor

dusty wigeon
#

You are overoptimizing

#

Anyway, I still do not understand how it works.

#

Can you just not use the object that made the potion to define the effect ?

dull kestrel
#

Not really. You could do something expensive like comparing lists/dictionaries and seeing what's left over, which is asking for lag spikes due to garbage collection.

#

MMOs that lag are not appreciated

dusty wigeon
#

Also, could you just not write the effect on the potion when you make it ?

dull kestrel
#

If it was a fixed recipe, yes.

dusty wigeon
#

In your case, you would do neither.

dusty wigeon
dull kestrel
#

But I want to take it a step further and make potions into a "profession". It's more an idea that I want to add, more than a definate.

#

If it cannot be performant, which I cannot currently think of a way, it won't be added.

dusty wigeon
#

Because I still do not get it.

dull kestrel
#

But based on my previous example, C6 H11 O S2 CL is expensive to check against, for example H11 CL C6 S2 O

#

You do not know the order, because different elements will be in different orders, and result differently.

dusty wigeon
#

So, the order of the component should not matter ?

#

If it is the case, you simply need to sort them.

#

O(NlogN) + O(NlogN) + O(N)

dull kestrel
dusty wigeon
#

That would be the complexity

dusty wigeon
dull kestrel
dusty wigeon
#

I sort elements in the Update loop.

#

And I have no issue in performance.

dull kestrel
dusty wigeon
dull kestrel
#

I do appreciate you trying to help though

dusty wigeon
dull kestrel
# dusty wigeon Yes, it is my opinion. You are asking for a second opinion. No worries there. Yo...

I am not sure reclarifying is going to be the solution.

For instance the last few MMOs to launch, or large scale games, always have performance issues because they have the mind set that "it'll be OK". They always need to redo or change things entirely because of this false confidence. Everything matters. RAM usage, CPU (Garbage too). It's so important, and you definitely cannot do it in something like Update which updates at potentially crazy intervals, especially for servers where the GPU isn't holding them back since no rendering is required. I would think FixedUpdate is as fast as necessary since that's when the physics happens.

long ivy
#

your priorities are all wrong here, and you aren't going to launch anything at all if you stay focused on a single blade of grass when you have a whole field to create

#

16k items in a dictionary for your server is nothing

dull kestrel
long ivy
#

how much memory is your server currently using?

dull kestrel
dusty wigeon
#

The first step of any optimization is profiling. So, implement a method, then profile. After, you going to be able to know what is better and how much it is better.

dull kestrel
dusty wigeon
#

I believe you might be surprise by how little time you gonna save. However, do not take my words for it.

dusty wigeon
#

Establishing a base is the first step.

#

Implement the most intuitive algorithm.

dull kestrel
#

That's why I asked in code-advanced

dusty wigeon
#

I gave you one didnt I ?

dull kestrel
dusty wigeon
#

Sort both formula and compare

#

And as a side note, if you want performance you should look into DOTS if you have not. @dull kestrel

dull kestrel
dusty wigeon
dull kestrel
scenic forge
#

How many chemical reaction results are we checking against?

dusty wigeon
#

Unity recently did a post on large scale game

dull kestrel
dusty wigeon
#

Also, the Unity employee have been saying that the networking for DOTS is more advanced than the networking for GameObject

dull kestrel
#

It just need to be expandable, and more or less indefinite

dull kestrel
dusty wigeon
dull kestrel
#

I will, outside of this issue

scenic forge
dull kestrel
#

It can get pretty heafty pretty quickly

scenic forge
#

I agree that this seems like a bit of premature optimization and you should just write the simplest implantation first and profile it to see if it’s an actual issue, but if you do believe this is fundamental to your game’s performance then you at least need to have a ballpark estimate, otherwise we are kind of talking on thin air.

dull kestrel
scenic forge
#

I mean you need to at least have an estimate of any sort, even something like “I think my game will have 1000 compounds so there are 1000x1000 combinations, but I expect only 1/10 of them to be valid reactions, so I’m looking at 100000 possible reactions to compare against”

#

Like those aren’t exact numbers, even just knowing the order of magnitude will give at least some basis for the conversation to continue.

dull kestrel
#

OK, but 1000 compounds, some could have 2 to... 5..6..7 elemenents. That is scaling massively. Manually I'm not going to be going 1+1=2, it'll be largely automated so that if 1 and 2 are involved it = 3 if 4 is involved then that reverses it if 5 is involved then that adds X,Y,Z to the result

#

It's clearly not going to work performance wise, so I'll be seeing how far I can go.

scenic forge
#

Well if memory isn’t an issue, you can store all possible reactions in a dictionary keyed by something (maybe simply just a string of reactant 1 + reactant 2 like H2 + O2; or a tuple of reactant enums) and looking up will be O(1) regardless of how many reactions there are

#

But that circles back to knowing at least a ballpark number of the reactions you will have to know if it’s even possible to fit all of them into memory.

sly grove
#

Normalize the input and give it a consistent hashcode and equality implementation and you can just throw it in a dictionary

#

And if they don't fit in memory it's basically the same technique just with a SQL database key lookup

dull kestrel
scenic forge
#

You don’t even need to write your own hash, like I suggested string and value tuples have them implemented for you for free.

dull kestrel
scenic forge
#

Then use value tuples

sly grove
#

Right it's not the hash function that needs to be written it's consistent rules about how to "normalize" the input so that a+b is the same as b+a for example, assuming that's true

scenic forge
#

Like reactant enums.

#

But it’s trivial as soon as you know all the reactions can fit into memory

dull kestrel
sly grove
#

Right, sorting the input in a way that doesn't change it is one way to make a stable key from it

dull kestrel
jolly token
#

Just keep in mind that keys should be immutable 😄

dull kestrel
calm trout
#

Hi. I'm trying to publish a fork of FuzzySharp (https://github.com/NiftyHat/FuzzySharpUnity) as a Unity Package under openupm so I can add it via a scoped registry for package management and I had a question about best practices for package naming. OpenUPM requires that I follow official naming conventions so I want to get this right for submission.
The official docs say to use reverse domain name: my personal packages are com.niftyhat.* but the I'm not the author of FuzzySharp, just the maintainer for the Unity package repo. Both options of either placing it under my own domain of com.niftyhat.fuzzysharp and or creating a domain for the package author both feel incorrect. I had considered com.niftyhat.thirdparty.fuzzysharp which feels more accurate but then makes the package name long.
Any thoughts on what is the most correct way to name a package that is a fork of an existing C# library?

GitHub

Unity Package for Fuzzy Sharp a C# .NET fuzzy string matching implementation of Seat Geek's well known python FuzzyWuzzy algorithm. - GitHub - NiftyHat/FuzzySharpUnity: Unity Package for F...

jolly token
timber shadow
regal olive
#

So this request is a bit advanced...Does anyone know how to make a Puppet Combo like AI for my game. You know Murder house, and Power drill massacre? Those AIs are what I am trying to dissect and learn how to make a Ai similar to it. Except all the ps1 graphics

devout coyote
real blaze
gleaming rock
#

Is there fast way to spawn bunch of those blocks and have them being simulated so they collide and bounce with ground?
These are spawned when blocks explode/trees fall down, for example.
And yes I am pooling them.

Right now the performance is ok but not so ok when there is hundreds or thousands of blocks, resulting of large explosion

#

Also right now they use box colliders & rigidbodies and I would like to keep them 3d rather than rendering them flat 2d

bleak citrus
#

don't crosspost.

regal olive
real blaze
# regal olive Okay I would want an ai to hide in a room and when you walk up to that room it w...

I see. a state machine can do the trick. you set up some states, and switch your AI manager 's current state to different ones based on some conditions.
for the process of making it, you can make a abstract state class and provide a set of methods for them like Update, Start and End etc. then inherit from that for each state that you need, and let your ai manager use them. you can just hard code the conditions inside the ai manager if it's a simple system, however if it's more complicated it'd be better go to create another abstract class for conditions as well (to be able to easily create different condition subclasses or switch between them at runtime etc)

nimble bison
#

Hello guys! I have a maze like the following: https://discord-cdn.is-terrible.com/6dbEle1Yo

My problem is when I try to rotate the prefab arrow the center axis, it rotates it around another axis, so instead of simply rotation around the center axis, it rotates it around the corner axis I guess. How can I fix this ? Thanks!

My code:

GameObject cellObject = Instantiate(Resources.Load("Prefabs/" + cellType) as GameObject, position, Quaternion.identity);
cellObject.transform.Rotate(Vector3.up, cellRotation);

6dbEle1Yo.png

spiral zenith
#

So you can rotate around the center of the tiles

nimble bison
spiral zenith
#

transform.RotateAround(center_of_the_tile, Vector3.up, cellRotation)

untold moth
#

Sometimes I hear the voice of Unity in my head. It tells me things. It tells me that I should use Transform.Rotate...

half swan
simple badge
#

Trying to generate procedural planets. For LOD i am chunking it into triangles. Something is wrong with the normals however, as you can see in the picture. There's not supposed to be visible edges.

If I just output the object space normal to the albedo texture and draw that, i get a seamless gradient as expected. This to me confirms that the object space normals and uvs are correct, so this leaves the tangent space conversion.

Every mesh (you can see one of the meshes highlighted in the screenshot) has its own texture
For each pixel on the texture I am doing:

albedoPix[i] = new Color(objectSpaceNormal.x * 0.5f + 0.5f, objectSpaceNormal.y * 0.5f + 0.5f, objectSpaceNormal.z * 0.5f + 0.5f);

Vector3 tangentSpaceNormal = ObjectToTangentSpaceNormal(objectSpaceNormal, tangent, bitangent);

normalPix[i] = new Color(
    tangentSpaceNormal.x * 0.5f + 0.5f,
    tangentSpaceNormal.y * 0.5f + 0.5f,
    tangentSpaceNormal.z * 0.5f + 0.5f,
    1
);
public Vector3 ObjectToTangentSpaceNormal(Vector3 objectSpaceNormal, Vector3 tangent, Vector3 bitangent)
    {
        tangent.Normalize();
        bitangent.Normalize();
        objectSpaceNormal.Normalize();

        Matrix4x4 objectToTangentMatrix = new Matrix4x4(
            new Vector4(tangent.x, bitangent.x, objectSpaceNormal.x, 0),
            new Vector4(tangent.y, bitangent.y, objectSpaceNormal.y, 0),
            new Vector4(tangent.z, bitangent.z, objectSpaceNormal.z, 0),
            new Vector4(0, 0, 0, 1)
        );

        Vector3 tangentSpaceNormal = objectToTangentMatrix.MultiplyVector(objectSpaceNormal);

        tangentSpaceNormal.Normalize();

        return tangentSpaceNormal;
    }

And here's what i do in the shader:

VS_OUT vs_main(VS_IN input)
                {
                    VS_OUT output;

                    output.position = UnityObjectToClipPos(input.position);

                    output.uv = input.uv;

                    float4 worldPosition = mul(unity_ObjectToWorld, input.position);
                    float3 lightDir = worldPosition.xyz - _MainLightPosition.xyz;
                    output.lightdir = normalize(lightDir);

                    float3 viewDir = normalize(worldPosition.xyz - _WorldSpaceCameraPos.xyz);
                    output.viewdir = viewDir;

                    float3 worldNormal = mul((float3x3)unity_ObjectToWorld, input.normal);
                    float3 worldTangent = mul((float3x3)unity_ObjectToWorld, input.tangent);

                    float3 binormal = cross(input.normal, input.tangent.xyz);
                    float3 worldBinormal = mul((float3x3)unity_ObjectToWorld, binormal);

                    output.N = normalize(worldNormal);
                    output.T = normalize(worldTangent);
                    output.B = normalize(worldBinormal);

                    return output;
                }

                float4 fs_main(VS_OUT input) : COLOR
                {
                    float3 tangentNormal = tex2D(_NormalMap, input.uv).xyz;
                    tangentNormal = normalize(tangentNormal * 2 - 1);

                    float3x3 TBN = float3x3(normalize(input.T), normalize(input.B), normalize(input.N));
                    TBN = transpose(TBN);

                    float3 worldNormal = mul(TBN, tangentNormal);

                    
                    return float4(worldNormal * 0.5 + 0.5, 1);
                    // return float4(ambient + diffuse + specular, 1);
                }

Any ideas would be greatly appreciated. I abandoned this years ago and would like to finally get it working

frozen imp
simple badge
#

forgot to mention, all the verts of the mesh share the same normal/tangent/binormal

#

straight out from the center of that mesh

#

@frozen imp

flint sage
#

I mean, looks like they don't

simple badge
#

hm thats probably it.. if i render input.N in the shader (vertex normal), i get this result. I expect perfectly unicolored meshes but theres a clear fade on the top of the front mesh here

#

this fade is very weird considering how I set normals:

Vector3[] normals = new Vector3[verts.Count];
Vector4[] tangents = new Vector4[verts.Count];
for (int j = 0; j < normals.Length; ++j) {
    normals[j] = normal;
    tangents[j] = tangent;
}
#

So something seems to be wrong in the interpolation of the vertex attributes

flint sage
#

Can't assume that without more details

simple badge
#

since the entire mesh just shares one normal, perhaps i should skip using mesh normals and just pass the single normal as a uniform

simple badge
#

you have vert and frag shaders above

flint sage
#

I doubt it's the shader but your mesh gen

simple badge
#

but as i said, normals are set on the mesh by me

#

to the same value

#

so why would there be a gradient in the shader output?

#
MeshFilter mf = GetComponent<MeshFilter>();
Mesh m = new Mesh();
m.vertices = vertArray;
m.triangles = tris.ToArray();
m.uv = uvs.ToArray();
m.normals = normals;
m.tangents = tangents;
mf.mesh = m;
mossy sky
#

I am trying to make a script for my camera in 3d unity game, I want it like Stratergy view

#
using UnityEngine;
using System.Collections;
public class StrategyCamera : MonoBehaviour
{
    public float zoomSpeed = 10f; // The speed at which the camera zooms in and out
    public float minZoom = 1f; // The minimum zoom level
    public float maxZoom = 10f; // The maximum zoom level
    public float panSpeed = 10f; // The speed at which the camera pans
    public float rotationSpeed = 10f; // The speed at which the camera rotates
    private Camera camera; // The camera component
    void Start()
    {
        camera = GetComponent<Camera>(); // Get the camera component
    }
    void Update()
    {
        // Zoom the camera
        float zoomDelta = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed; // Get the zoom delta from the mouse scroll wheel
        camera.orthographicSize = Mathf.Clamp(camera.orthographicSize - zoomDelta, minZoom, maxZoom); // Zoom the camera by the zoom delta
        // Pan the camera
        Vector3 panDelta = new Vector3(Input.GetAxis("Horizontal") * panSpeed, Input.GetAxis("Vertical") * panSpeed, 0); // Get the pan delta from the arrow keys
        camera.transform.position += panDelta; // Pan the camera by the pan delta
        // Rotate the camera
        float rotationDelta = Input.GetAxis("Mouse X") * rotationSpeed; // Get the rotation delta from the mouse X axis
        camera.transform.RotateAround(Vector3.zero, Vector3.up, rotationDelta); // Rotate the camera around the Y axis by the rotation delta
    }
}
flint sage
frozen imp
#

Visualizing with debug drawline/ray would help as well

flint sage
#

Yes that's one triangle

#

Where's the rest

simple badge
#

every tri works the same

flint sage
#

See the ones at the edges on each triangle? They have to be exactly the same for there to be no line visible

simple badge
#

these colored triangles you see are not gpu triangles, they are separate meshes

#

the normal map is created manually as seen above, where the object space normal is the normal straight out from the center of the sphere

#

here is object space normal drawn to the albedo maps

#

so my object space normals are correct, somewhere along the way they get distorted

they are converted to tangent space, drawn to the normal map, then converted back in the shader

#

all of these functions handling the normals from this known working state are posted above

frozen imp
simple badge
#

they don't share points, they are separate meshes

frozen imp
#

Your mesh group triangles share points

#

That's why they are smoothed

simple badge
#

every normal in a mesh is the same

#

so smoothing should have no effect

#

im not using any mesh groups

frozen imp
#

You need to calculate unique normal for each

frozen imp
simple badge
#

surely unity will not start smoothing my normals with another, for all intents and purposes, unrelated mesh?

frozen imp
#

You need to calculate unique normal for each
This is your solution

simple badge
#

i cant see why this would be needed

#

since for each pixel i will get a world space normal

frozen imp
simple badge
#

if i use "real" vertex normals i will have to convert all pixel normals

simple badge
frozen imp
simple badge
#

my input object space normal is correct along the edge

#

but the output after tangent space conversion is distorted

#

if the output value was correct, the seams would not be visible

frozen imp
#

I don't think you are trying to understand.

simple badge
#

look, i can remove the other meshes completely

#

the problem is that the normal output at the highlighted points are incorrect.

#

theres no sharing of normals along edges

#

i could have "round" normals for my meshes but i shouldn't have to
I convert the normals to tangent space where the input vertex normal and tangent is the same as on the mesh, hence i expect a correct result

simple badge
frozen imp
simple badge
#

i get what you're saying but this is a custom shader where the normal map is made for these exact normals

#

this is because in my generation i get object space normals, and converting these for the normal map is way easier when i only have one vertex normal and tangent

#

if i used "real" vertex normals on a bumpy surface i would have to interpolate between the vertex normals in order to get the right vector to paint onto the texture

#

which would be heavier and would break when i increase the lod of the mesh with more triangles without recalculating the normal map

#

in the end the surface is expected to look more like this

#

than a perfect sphere

#

and i have to be able to subdivide this without generating a new normal map

twin totem
#

Hi does someone know how to filter swear words from your game for free?

frozen imp
frozen imp
#

@twin totem Don't spam. No relation to code, lookup dictionary of banned words.

simple badge
#

the reason is that i want to be able to up and down the lod infinitely

#

im in paint throwing up a visualization hold on

#

so im not a perfect artist but pretend this is the same surface but in three levels of detail

#

if i was to have the same tangent space normal maps on these, i would get different results on the screen

#

so thats why i put the vertex normals facing straight out

frozen imp
#

If you want to have smoothed seams you'll have to assign normals manually there accounting for surrounding vertices, you only need to do this for border vertices though if you have irregular shape

simple badge
#

that data is already in my normal map though

#

doing it your way, you'd have the normal map be one solid color for a sphere, correct?

#

because you represent the shape of the sphere in the vertex normals and use the map only for finer detail

frozen imp
#

I haven't looked at your shader, but I doubt it, they are not the same

simple badge
#

my maps look like this because i represent the shape of the sphere in the normal map

frozen imp
#

If that's the problem you might want to adjust the shader, because that's the only way to have smoothing on seams.
Note they are not actually look like that when they are smoothed. You might assign them that way,
https://discordapp.com/channels/489222168727519232/885300730104250418/1148321077785796731
but because they are sharing vertices their normals are smoothed and actually are turn to this if you sample them after generation
https://discordapp.com/channels/489222168727519232/885300730104250418/1148320584820871288

simple badge
#

im trying to tell you though the chunks aren't sharing vertices

#

each chunk is completely separately generated

#

different gameobject with a different meshrenderer+meshfilter+mesh

frozen imp
#

That is not what I'm saying

#

Your drawing, you drew the single chunk, I'm telling what happens to the single chunk

#

To points that are inside one

#

Except to the ones on edges

#

The ones you need to fix to do the smae to smooth

#

oof

simple badge
#

but all normals are the same, no matter how much unity tries to interpolate between (0,0,1) and (0,0,1), it should still always be (0,0,1)

frozen imp
#

they are not the same

simple badge
#

they are the same

frozen imp
#

If they were the same you would've had a one flat face

simple badge
#

here's one mesh printing the normal

#

as you can see its uniform

#

the vertex normal*

frozen imp
#

I don't know how else to explain :)
Create a smaller model, probe its actual normals, explore how it works.

simple badge
#

the vertex normal is the same across the entire mesh

dusty wigeon
#

As stated by Fogsight, your normal are not correct.

simple badge
#

custom shader @dusty wigeon

frozen imp
dusty wigeon
#

Yeah, then your custom shader might not correctly apply the normal then.

frozen imp
#

How to build your procedural shaders too

simple badge
#

i am intentionally setting the vertex normals to straight away from the triangular shaped mesh
this is because my normal map is originally in world space, not tangent space

#

i dont want the shape or detail level of the geometry to have any impact on the output normals

dusty wigeon
simple badge
#

fine i will ignore vertex normals completely and just draw world space normals onto the normal map

#

then rotate that vector to align with the meshes rotation

#

heres what i had in the beginning anyway (in this case spherical normals on an irregular surface but in reality it would be the opposite)

#

only issue is getting it to rotate along with the object, and it seemed tangent space was the way to go for that

#

(and it worked except for the slight distortion)

misty glade
#

I'm having some trouble wrapping my head around how I'm going to represent location in my game - keeping float instability to a minimum since the world might be large.

Every tile in my game has a unique location that can be mapped to a tilemap location. The player's location in world space can also be mapped to a tile (although the player is free to walk around "normally" - ie, in floating point precision).

I was thinking originally that I was going to use a decimal "true location" and then map this to a unity location .. but things started getting complicated (keeping track of offset, redrawing everything on the screen when the offset changes, etc).

Would it be terrible to just slap a double on the position of everything and don't do all this offset stuff? I'm not sure how to test this. decimal seems like massive overkill and is six times the storage size of float .. but maybe I should go that way?

In my world, players can move about 5u per second, and there's a few data points needed on each tile.. I am sorta guessing in the dark that a player might need a few million tiles in their save file so I feel like optimizing it for size now is useful, but ... I'm also just getting brainfucked with all the offset stuff and worry I'm gonna have a lot of downstream bugs if I choose to do it this way..

#

Although I suppose putting location in a double doesn't solve anything since those need to get casted back to floats for unity anyway, and then I'm back to the original problem of float instability.

dusty wigeon
#

Also, the second is animation if I am right.

frozen imp
#

Last time I checked physics and lighting start breaking up around 10k range. Should be good before that scaling down the world coordinates to that.

#

In the extreme case you can make your world tick virtually and just have a simulated view area to play with.

misty glade
#

Yeah I'm wondering about movement - like if it's gonna start getting jittery from moving with a tween

dusty wigeon
#

I do not think movement will bug that soon.

misty glade
dusty wigeon
#

Pretty sure that movement will not bug till you are really really far.

#

Like near the end of the float precision.

misty glade
#

I'm .. thinking of basically keeping the offset in a singleton and then storing the "true location" of items in doubles, then converting to a unity "world location" by calling the singleton .. but... that feels like it's gonna be a big source of bugs later on

#

something like this

frozen imp
#

I haven't tested how optimal tilemap is. I think it supposed to have chunking handling, but didn't get to testing to scale.

misty glade
#

(decimal or double doesn't matter - probably would use double since I feel like that's plenty safe)

#

The tilemaps themselves are placed in cartesian coords and don't move, so .. I think I'm ok there. But I was planning to have little things "plop" out of a given tile, and those would need to have precision.. ie, they might tween from somethign like new Vector2(1000000,1000000) to new(1000002, 1000002)

dusty wigeon
#

It shouldnt be that bad. You just have to never use transform.position and use that instead.

misty glade
#

K.. it's just sort of a lot to wrap my head around that there's a "true" position and a "unity" position now, and I have to be really careful not to mix the two and always go through the offset in the singleton

#

I just know I'm gonna have a few hundred bugs related to this when I forget

tiny pewter
#

My solution to this is lazy evaluation only calculated the world position when needed to reduce O(number of vertex*8 ) memory

misty glade
#

I mean, yeah, obviously, but I'm mostly worried about erratic behaviour in late stage gameplay when the player is far from the origin

#

I'm already juggling too many coordinate systems.. unity cartesian tiles, hexagon cartesian mapping, hexagon cubal/axial mapping, and "big hexagon" coordinates.. now I have another that is the global cartesian "offset". 🤯

#

oh, and screen position 😛

#

(for mapping clicks-to-world)

regal olive
#

So I have an abstract class.
The top one "playerConroller" - does it need to be initialized in the deriving classes? Or is it done on it's own.

sly grove
#

are you expecting to assign it in the inspector?

regal olive
#

Do I need to make some reference ot it?

#

No

sly grove
#

yes you need to make some reference

#

you always have to initialize your variables somehow

#

that would be either in the inspector or in code

#

it can be done here or in deriving classes

#

but it needs to happen somewhere

regal olive
#

I see, how would one do that? I guess Jetbrains has been gaslighting me and not giving me any errors when I call variables from it like playerController._cam.transform.

sly grove
#

it would be a runtime error

#

there is no gaslighting happening

regal olive
#

I see. Since I've been struggling with the "object reference not set" and it only directs me to the line without any other pointer as well as IDE not catching it.

sly grove
#

it's a runtime error

regal olive
#

Right

#

Now I know

regal olive
#

Thank you

sly grove
#

You could do it in a constructor, or simply by assigning it directly since it's a public field

regal olive
#

It's an abstract class, not monobehavior. It's not some script I attach it.

sly grove
#

since this isn't a MonoBehaviour, we're working with basic C#

half swan
#

Oh mb, I thought that link covered POCOs too

regal olive
#

With constructor you mean the derived classes?

sly grove
#

The derived classes will need their own constructors, yes

#

ideally they invoke a constructor from the parent

regal olive
#

Right, any recommendations?

sly grove
# regal olive Right, any recommendations?

Yes I recommended using constructors. Here's an example:

public abstract class PlayerBaseState {
  protected readonly PlayerController playerController;

  protected PlayerBaseState(PlayerController pc) {
    this.playerController = pc;
  }
}

public class FlyingState : PlayerBaseState {
  public FlyingState(PlayerController pc) : base(pc) {
    // whatever other initialization you need for this particular state
  }
}```
#

Then when you make the states you need to pass in the controller to the constructor:

public class EnemyStateMachine : MonoBehaviour {
  public PlayerController pc; // assign this in the inspector
  FlyingState flying;
  WalkingState walking;

  void Awake() {
    flying = new FlyingState(pc);
    walking = new WalkingState(pc);
  }
}```
regal olive
#

Any reason not to just do:

FlyingState flying = new FlyingState(pc); without the Awake?

sly grove
#

in other words - pc won't be assigned yet if you do it in the field initializer

#

it will be assigned if you do it in Awake

#

This is why Awake exists

regal olive
#

I see. Since my current method of doing is just this.

sly grove
#

so you can do initialization at the appropriate time

#

sure but now you can't do that

regal olive
#

Right

sly grove
#

unless you can guarantee you have a valid reference to the player controller in a static context somehow

sly grove
regal olive
#

it is

sly grove
#
public PlayerIdleState IdleState = new PlayerIdleState(this);```
#

that would probably work in that case

#

does it need to be public though?

#

seems like something that shouldn't be

regal olive
#

I just have one script, technically I'm looking for a way to organize code in derived classes so I wouldn't have to fill the state areas and just put the method name in instead.

#

But referencing data outside of the override methods requires a separate reference

#

I don't know if it's the best way to do it, but it seems like it would help with better organization.

regal olive
regal olive
#

Nah, still can't access them. They're not being derived from player controller.

#

Player controller is a mono

sly grove
#

unless they're public

#

but - why do you need to access them from anywhere else?

#

oh I guess to change states?

regal olive
#

Yes

mellow plinth
#

In Unity WebGL, how can I call Javascript functions defined outside the project?

mellow plinth
#

Explanation: I'm hosting Unity WebGL inside a MAUI Blazor Hybrid App.
I need a form to exchange information between Unity and the App.
Inside the razor component (Blazor) I can create javascript files that can call C# code of Blazor.
I want to call functions inside that javascript file from Unity.

thin mesa
#

so create a js script that calls those outside functions and/or that has functions that interact with your C# code

cerulean wasp
#

do ModifyiableContactPairs work for 2D? I only see it for 3D. Alternatively, if there is an equivalent for 2D, that would be nice too

cerulean wasp
#

I basically want to be able to tell the physics2D system to ignore contacts including a specific collider, if that contact’s normal is in a cerain direction

real blaze
# cerulean wasp do ModifyiableContactPairs work for 2D? I only see it for 3D. Alternatively, if ...

the documentation at https://docs.google.com/document/d/1lyvZ_Epm7W5iQSuLkF0kHKsHNshKDoyp4U73JO8Zt1M/edit suggests it's a PhysX thing, so my guess is that it doesn't work for 2D

austere jewel
#

!ban 931732121997959219 spam

thorn flintBOT
#

dynoSuccess funcieq#0 was banned.

simple badge
#

@frozen imp i am now doing it completely your way and I am inclined to believe normal maps simply can't work well with "seams"

this is the standard shader, normals of shared edges are the same as you wished, normal map is just filled with new Color32(255, 128, 128, 128); (have used 127 too, is equally wrong)

#

This is how I currently set up the texture, although i have tried some different variations with the same result

Texture2D normalTexture = new Texture2D(texSize, texSize, TextureFormat.RGBA32, true, true);
normalTexture.filterMode = FilterMode.Trilinear;
#

without a normal map the seams are gone

#
for (int j = 0; j < normals.Length; ++j) {
    normals[j] = verts[j].normalized;
}
m.normals = normals;
m.RecalculateTangents();

I have heard unity can create some bad tangents, but in this case i don't see how it could matter as i am testing with a completely flat normal map

frozen imp
#

I don't know what rabbit hole you put yourself into. Learn a way to create a smooth geometry first with multiple meshes without any shaders. Then create a shader to accomodate your needs. Take a look at the Catlikecoding tutorial I linked it has everything you need.

simple badge
#

it is smooth as you can see in the second screenshot, i have no problem creating the geometry

frozen imp
#

So what's the problem then?

simple badge
#

using a normal map causes seams no matter what

#

it's as if unity is unable to represent a flat surface using a normal map

frozen imp
#

Check that those points on the border have precisely the same normals on both meshed meeting there, it could be they are slightly off.

simple badge
#

they do, exactly the same

#

that is why it is perfectly seamless when not usign a normal map

#

here's a test normal map found online to ensure im just not doing something iffy with the normal map creation (although i dont see what that could possibly be) and i still get seams

frozen imp
#

I would create two very basic meshes meeting slightly at the angle and make sure to use the exact same normal, just for sanity check to create absolutely controllable environment. To make sure that's not some error. Then you can definitively tell if it's a shader/lighting problem treating seam differently.

#

So it's a texture color difference there, not the shape?

#

That would be just a matter of generating it properly and probably a shader question.

simple badge
#

with the test normal map i am referring to the "medium" colored neutral zone at the seams

#

obviously the texture will not line up correctly

#

will test just using two planes

#

well a test with two planes creates a seamless transition so now i am just more confused

#

i will have to assume it's my auto generated tangents

frozen imp
#

autogeneration would not know anything about other neighboring mesh

simple badge
#

doesn't have to, it's a sphere

#

for (int j = 0; j < normals.Length; ++j) {
normals[j] = verts[j].normalized;
}

frozen imp
#

m.RecalculateTangents();

simple badge
#

yep, am doing that after setting normals

#

but then again, the normal map is flat, so tangents should not matter??

frozen imp
#

it's not aware of sphere it just calculated for its mesh

night geyser
#

im making a music player, but i cant figure out how to listen to the media key (play/pause)
anyone smart here know how to correctly set up an (ideally global) listener for that key?
ive gotten this far with google and chatgpt. i think this correctly sets up the global hotkey, but still doesnt listen to it.

frozen imp
fallow eagle
#

(sry, my Discord didn't update until I sent something...)

scenic forge
#

I haven't touched Win32 API in years, but I remember that's just registering and tells Windows to send you a message when the key is pressed, you still need to go handle the message yourself to be notified.

#

Honestly it's probably easier to just check if the key was down in your update loop

#

If Unity's can't detect those keys you can use Win32 API to do it instead.

#

(And well, I don't think you should be building a music player in Unity but hopefully you have your reasons)

fickle tinsel
scenic forge
#

It's simply wrong tool for the job.

fickle tinsel
#

Explain?

fresh salmon
#

It's a game engine

#

Apps are better made in app frameworks

#

Which are lighter, and take way less resources

scenic forge
#

Yeah Unity is a game engine and you are using it to make... not a game. A music player has needs that app frameworks can provide which Unity can't, while not being able to make use of what Unity provides.

fickle tinsel
#

Cool. I was just curious what reasons would be articulated. You both seem to articulate implied arguments (“it’s a game engine” (therefore what?)).

I wouldn’t use Unity to build a music player either. But I also don’t see unity as JUST a game factory either. It’s a real-time simulation factory, and games aren’t the only use case.

E.g. turning yourself into an anime character is an app a few developers have made in Unity for phones (iPhone & android). That’s a perfect use of the “game engine” technology.

scenic forge
#

Sure, but that example also makes use of what Unity provides

fickle tinsel
#

Yes that’s my point

fresh salmon
#

If you want to make the trippy sound visualizations like Windows Media Player has then sure, you can use Unity for that

scenic forge
#

I suppose the better way to phrase it would be "a music player can't make use of what Unity provides" rather than "a music player isn't a game"

fickle tinsel
#

Yea totally!

scenic forge
#

But regardless, Unity's audio really isn't up for the task for a music player.

#

For one it can only load a tiny set of audio formats, and if you want to load anything dynamically you have to do it via UWR (there's no way to directly load a byte array and decode the audio)

fickle tinsel
#

Word. This convo is making me a bit curious how Spotify works.

scenic forge
#

And things as simple as "show an open file dialog for user" is not trivial in Unity unless you bring in an asset, while it's provided for you in app frameworks.

dusty wigeon
scenic forge
#

But if you have no control over the audio format and need to play them dynamically (like a music player), you have no choice but to have decoders for everything popular.

#

My Unity game needs to load user generated content including audio, and I have to embed FFmpeg.

flint sage
dusty wigeon
flint sage
#

They've got a pretty good dev blog, you might be able to find some info there

cerulean wasp
#

My core issue is that platformeffector2D doesn’t work for TilemapCollider2D because it is based on the world space center of the collider. I just want to make a TilemapCollider2D with proper one-way collision.

hardy jacinth
#

Unity doesn't support covariant return types for overriden methods???

real blaze
modest vale
#

#Creating a computeshader asset with an editor script

dusty wigeon
hardy jacinth
#

Dunno which .net, but C#9

dusty wigeon
#

Unity does not support all function of C#9

jolly token
real blaze
#

don't it all just compile down to IL for Unity to use? what's special about these C# rules?

jolly token
cerulean wasp
#

ty for the help. my quest for oneway platforms on tilemaps continues

#

i really wish we just had better 2D tools for this

hardy jacinth
#

Use Tiled maybe ?

#

If it fits your needs

cerulean wasp
#

i cannot use tiled. my game is maker-style, so all tiles get placed programatically during runtime

#

it also doesn’t help that I cannot define a tile to use an edge collider. Using box colliders can allow the player to land on the bottom of the collider

stuck plinth
modest vale
#

does someone understand how this works?
The discription says

/*
creates a new ComputeShader object from the provided source code stirng.
You can use this method alongside the ScriptedImporter to create custom compute shader generation tools in the editor
*/

ShaderUtil.CreateComputeShaderAsset(/*AssetImportContext context, string source*/,);

As far as I understand the Scripted importer only gets triggered when an asset is imported and there is no way to create an AssetImporterContext instance
I would like to create a computeshader asset in a specific folder idk if this is what I need tho

stuck plinth
#

i think the intention is you create a custom scripted importer for the shader asset you want to generate and call that method on import

modest vale
#

is there a way to simulate an import of an asset?

stuck plinth
#

why not create a scripted importer?

modest vale
#

hm I thoguth beacuse it s OnImport method will only get called when an asset of a specific type gets imported

#
public override void OnImportAsset(AssetImportContext ctx)
    {
        throw new NotImplementedException();
    }

that s the function that gets called on import

stuck plinth
#

well this method is very specifically for making a compute shader where the source asset is different to the imported one, if you don't have a custom importer maybe just generate the source by other means?

sage radish
# modest vale is there a way to simulate an import of an asset?

I believe with this method, you could define a custom asset file extension like .gencompute with your generated source code, or just information required to generate the source code, and make a ScriptedImporter that imports that file as a compute shader.

modest vale
#

hm okay, and is there a way I can import a file by code?

stuck plinth
#

AssetDatabase.ImportAsset(...)?

sage radish
#

If you have a ScriptedImporter, it will automatically trigger when Unity detects a new file with a matching extension.

modest vale
hardy jacinth
hardy jacinth
modest vale
#

the OnImportAsset together with the ShaderUtil.CreateComputeShaderAsset actually works for me

hardy jacinth
#

hmm, no, nevermind, seems like shader asset =/= compute shader asset, I thought they are the same thing just different source code inside

chilly drum
#

Hi,
I need a solution, How can move enemy in drap FPS exactly on point, if It needs to move in the right direction from exactly one point..

#

And how can we do exactly what is happening in coroutine?

humble leaf
#

@spiral aurora Stop spamming your question across this server please.

spiral aurora
#

OK

#

thx

#

Please understand me, I need urgent help.

humble leaf
#

Everyone here needs "urgent" help. This is a community server, if anyone can help/wants to help, they will. Your urgency isn't a reason to hit every channel with your question. Choose one, stay in one.

sharp monolith
#

Hi im having a problem with my ai character for my vr game. the NavMeshAgent means the character cant be grabbed as it doesnt let it be picked up off the floor, ive written code to turn on a collider and turn off the NavMeshAgent when the players hand is close enough to grab the ai, but insted it just makes it launch itself downwards, ive even tried turning off gravity so the thing cant fall but then it just teleports to the furthest down it can go
Hi im having a problem with my ai character for my vr game. the NavMeshAgent means the character cant be grabbed as it doesnt let it be picked up off the floor, ive written code to turn on a collider and turn off the NavMeshAgent when the players hand is close enough to grab the ai, but insted it just makes it launch itself downwards, ive even tried turning off gravity so the thing cant fall but then it just teleports to the furthest down it can go

#

The second collider is on a EmptyGameObject as having a trigger collider and normal wont let the code differenciate, I THINK, but idk if thats true

restive dust
#

not sure where to ask this question so I'll ask here: I'm profiling memory usage in our game and I'm seeing references to objects not instantiated yet held in memory -- these seem to be prefab references stored in ScriptableObjects

#

is this expected?

sly grove
#

any assets directly referenced in your scene will be loaded with the scene

#

For pretty obvious reasons I think.

restive dust
#

hmm. This seems a little at odds with how we use the system, because we use it to store data for things that the player might not see in their particular play of the game

restive dust
#

yeah, I'm in the middle of transitioning our game to addressables. How would that interact with prefab references stored in scriptable objects?

sly grove
restive dust
#

right, that's what I was wondering. thank you

#

it's a little uh, disappointing to find this issue because it felt a little unexpected for me to expect a reference to a prefab to not work like an address, but I guess that's what the addressables system is supposed to fix 😓

sly grove
#

barring some magic AOP injection style code

restive dust
#

yeah, that makes sense in retrospect, it's just incompatible with the way we were using the system

burnt hamlet
#

whats the purpose of having files in a runtime folder?

twilit grove
#

Is there a way to have two dimensional Enums? In this game I'm making, there are four different classes of abilities, and each ability class has multiple different abilities. I want it so that a single data type can hold 1 enum which decides which type of ability it is, and a second enum which can be many different types of enums, each with their own set of abilities, so it basically holds the enum of an ability without having to have 1 of each enum ability in the data type. Any idea how to do this?

dusty wigeon
#

I'm not exactly sure what you want, however whenever enum does not fit your need, almost everytime you can use a class instead of it.

dusty wigeon
# burnt hamlet whats the purpose of having files in a runtime folder?

If you mean StreamingAsset, then it can be if you want a player to change files in the game such as moding the game. It can also be if you want to have assetbundle distributed at start or use the functionality that demands a path such as watching a movie.

However, you can place files into the normal filesystem on the target machine to make them available using a pathname. For example, for deploying a movie file on iOS devices, the original movie file must be available from a location in the filesystem to play using the PlayMovie function. This folder can also include AssetBundles that you intend to distribute directly in the Player installation, rather than downloading them on-demand.

https://docs.unity3d.com/Manual/StreamingAssets.html

burnt hamlet
#

the script in the folder is a library containing methods and datatypes, but I'm not sure why it needs to be in a Runtime folder, or if it even does need to be in one

dusty wigeon
#

Pretty sure it does not needs to be. I've seen a lot of library using this folder, I guess it is either the packaging system or the nomenclature used.

sly grove
#

And it doesn't look like they even separated their asset into assemblies anyway

cerulean minnow
#

If I have an enemy alway searching for players to attack , I still shouldn't run it in update right , maybe use a coroutine or something?

humble leaf
#

Just use Update. 🤔

austere jewel
#

You can use a coroutine or add timers if you wanted to reduce the frequency you search at

cerulean minnow
austere jewel
#

Do what makes sense for your game

dusty wigeon
#

I prefer to use Update same if we do not update the function every frame. It is more readable.

spiral fulcrum
#

Anyone can help me with Shader Update.... i got an Sebastian Lague Shader Shader Graph, and it cant work on new version of unity, any tips to make it work ? or REwrite ?

burnt hamlet
#

Anyone know how Unity gets gameObjects to slow down instead of bouncing forever?
(For context, the left square is using my custom code in addition to Unity physics material bounciness, the right square is using no custom code, only traditional Unity engine stuff)

untold moth
burnt hamlet
#

the right square has no friction(neither does) or angular drag, just linear drag

#

which is why the edges touching the ground isn't causing them to shift around, just bounce

untold moth
burnt hamlet
#

upon further testing it looks like the way Unity does gravity is different from the way I've been doing it

#

when an object is sitting on the ground it seems to have less gravitational force, wheras in my case the object has a constant gravitational force being applied

#

this seeming to be the case since when the normal object starts falling it starts slow and ramps up considerably, in the case of the object using my code, the ramp up isnt as significant, its terminal falling speed isnt too much higher than where it starts

untold moth
#

In real life gravity is applied to object across time, making them fall quicker the longer they fall.

#

Do you have it as constant velocity or something?

burnt hamlet
#

yes, gravity as a constant accelerating force

#

to my understanding thats all there was to it

untold moth
#

Constant force or velocity? These are 2 different things.

burnt hamlet
#

its using the same equation as the Forcemode Accelerate method Unity has

untold moth
#

In this case that is correct(if I understand your setup correctly).

burnt hamlet
#

velocity over time indipendent of mass

untold moth
#

Yes. Although I don't see your code, so I can't say if the implementation itself is correct.

burnt hamlet
untold moth
#

That doesn't reveal a lot, but this part should be fine.

burnt hamlet
#

the usage of this method is
exampleForce = AddVAccellerate(exampleForce, addedForce)

#

you feed in the current value and the desired additional force and it applies the equation

untold moth
#

That's fine, but there's a lot more to moving objects than just applying acceleration.

burnt hamlet
#

the value this gives is then used like so
velocity = exampleVector2.normalized * exampleForce

#

exampleVector2 storing the direction it needs to be going in

tiny pewter
#

You can use velocity vector directly in the method actually, though this cant help your original question

untold moth
#

So far it's fine, but as I said, it's just a small part of physics.

burnt hamlet
#

I know, I've been taking things a step at a time, adding important features to get things behaving how they should

#

in this case I'm confused whats so different about how I'm handling gravity and how Unity is normally handling gravity

untold moth
#

As I said, drag and also probably angular momentum. Unity calculates velocity based on center of mass and the hit point of the object.

#

It also probably stops applying gravity after the object has been still for a few frames.