#archived-code-advanced
1 messages · Page 79 of 1
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
👍
But it doesn't work for the second part (when different symbols then it is 0)
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
shit happens, as you can see
Now the proof works
Sorry, it should have ended much-much earlier
Thank you very much!
np, on the plus side I got an algebra refresher of my own :P
XD
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());
}
no. either store the lambda in a delegate variable or use a regular method instead
thx
delegate variable won't work either, since it copies on assign
it works just fine
https://dotnetfiddle.net/I4eb26
Are you sure that's an advanced coding question?
I see. well they do get copied, but perhaps the equality check works fine with two copies of one delegate
still, I believe using functions for subscription is generally better practice
Delegate don’t get copied. It’s reference type.
I prefer the Rx style subscription better, that you can Dispose later 😌
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 ?
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
as strange as it may sound, they do indeed get copied. I had dealt with it previously. you can use decompiler (debugger & step into the operation) to see that it uses internal calls to copy the delegate
here, check this https://dotnetfiddle.net/bate5c
Action x = () => Console.WriteLine("1");
Action m = null;
m += x;
m();
x += () => Console.WriteLine("2");
m();
output:
1
1
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
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
i get how this looks like copying but remember += is an assignment, you're reassigning x with the new combined delegate not updating the existing object, so the delegate you added to m wouldn't change
yeah... that part is a bit hard to manage since it's all manually done with no help from internal tools
right. seems ReferenceEquals returns true for m=x too. I do remember something about them being copied though. will have a look
I see that there is a setting in Rider (idk what about VS) that you can click RMB on a directory > Properties... > uncheck the namespace provider
with this I can set root namespaces for all of my assemblies in unity, then deselect appropriate directories as namespace providers
oh i thought you were talking about source generators :p yeah Rider's great in that regard, in VS I always have to edit the namespace for every single new script
well, my approach wit hsource generators will just for now be → take record declaration -> find compilation unit syntax -> generate new file based on the record declaration, just swap it's members
this way any annotated record inside namespace will also generate with appropriate namespace
huh? proly you want this instead?
https://dotnetfiddle.net/gJ9VDM
also not really following the conversation 🤓
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
yeah this is the last solution I wrote just now 👍 I think this technique is not very well known but works like a charm
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
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
but it's the only way to use main APIs
unless you really dive in and make a whole system around just that
There's new api since 2022 that's much faster called FindAnyObjectOfType
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.
I've heard of this method, but not used it yet. Do you know how much faster it's supposed to be? As far as I know, it only skips sorting, so if there's only one instance of that type that can be found, it would cost just as much as a regular FindObjectOfType.
it's fast and efficient, the old one used sorting algorithm which why it was slow. The sorting is optional now
Edit: Misread the last part, the old api sorts all objects in hierarchy 1st then sort them out apparently, regardless what types are they. The new one skips the former by default iirc. It's sorta explained in the release notes
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?
This is not Delegate being copied. += is the one copying whole invocation list. The lambda itself did not get copied here.
So you can remove (-=) it by that reference just fine
I didn’t read the conversation after ping lol
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)
you only need to set and move same limited (say 9) chunks
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
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
well, those things are just things you do
I'm not.. sure that's true..? I thought they were uh.. for lack of a better term, DOTS-like
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
to me its a standard thing, coordinate conversions, world shifting, local/global etc
why is it expensive?
with tilemap api specifically?
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"
its unavoidable
rendering and physics will break at distances larger than about 5k units from zero
with 1m/1u scale
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
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
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..?
i dont know if it does
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")
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
yeah, I have that - but I was trying to make the "my coordinate system" map 1:1 with "unity worldspace coordinates"
if its abstracted well enough it wont feel like gymnastics
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
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
The object (de)activation and init(finalizing) will still happen on the main thread and block
Unload is causing the problem
Same
You can work around it by (un)loading smaller chunks and making your init/finalize code do less
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.
You can try (un)loading stuff more granularly with addressables
unfortunately the environment is procedural
you are still loading/destroying stuff though
maybe don’t destroy, instead reset and reuse?
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
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
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(); } } }
Have you tested it?
Yes, but I cannot see debug on announcement being shown in log
so put Debugs in this method
then the method is not being called
That is weird since debug log line before this void is shown
what?
From what you have shown and said so far, I doubt whether you are ready to do multi-player
Well, server is calling this func. So it is called on all clients
If(server || host) {show...}
but if it is not logging then it is not being called is it?
It looks like that
But why?
it's your code, not mine so I cannot know
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
network is hard, you needs lots of experience to get it to work well
I know, im learning it
Sorry, I don't wish to appear rude but anyone who calls a method a void is not ready to do network code
...
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.
Hi lovely people, where can i ask a question about webgl ar application? thanks in advance ❤️
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
Don’t call into a global scope on destroy. Use onDisable for that.
The same happens with OnDisable :/
you can always check if the object is still valid
if (this) { }
this will return false if the object was destroyed
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.
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
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
Instead of lazy loading of singleton, instantiate them at launch. The worst that will happen is that you gonna get a NRE (and a false one, because only the C++ side would be destroyed).
That's definitely an option but I prefer loading it lazily: doesn't matter in which scene I'm in, if I need a "Locator", I just call it and a new one will be created for that scene under the hood.
I use a mix of RuntimeInitializeOnLoadMethodAttribute and Reflection to instantiate them at the start.
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.
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!
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.
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?
unity is not a hardware.....maybe you are asking for x86/arm architecture and different architecture has its own set of ISA
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!
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?
you mentioned looping issues...
if looping the Animation Clip is not a wanted behavior,
consider disabling Loop Time https://discussions.unity.com/t/animation-loop/34663/2
Did you upgrade the asset and validate that the asset is supported in the knew version ?
Also, did you make sure that you have not other errors ? Because it seem to me that all your DLL has an issue at the moment.
yeah i did that with the MoreMountains asset a bit below and nothing changed 😦
so, i uninstalled and installed again but all the same
Like I said, I do not think 1 particular asset has an issue.
I do not think that reinstalling an asset will change.
what do you suggest?
As your own assembly has an issue
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
Unity does not work with Visual Studio/Rider dependency workflow
You could try to regenerate the solution
what can I do then? im totally lost
Also, you could try to redo the upgrade. Maybe with a version that is closer.
regenerate the solution? from Rider?
From Unity
you mean the option in preferences "regenerate projexct files"" ?
that i already tried with no success
Then, I would start over.
damn
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.
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
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
Because it's a float and not all values are representable in floats
@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
Removing everything that is generated by Unity
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.
Obviously. I was just adding on what has been said. (Also, it was not about comparison, but understanding on why a float is not the value exact the user was expecting. I though it could be pertinant to include a deep dive in the subject)
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
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?
I'd love that too. The Unity Roslyn stuff has been confuse a few of my coworkers and friends. There's no real good documentation that I found either.
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
I guess no support for 4+ as that only comes with .NET 6 which unity doesn't support and we don't know when it will.
Is there way to spawn objects when server started? Unity netcode for gameobjects
if nobody responds, try #archived-networking
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.
just make a custom serializable struct and make an array of those
[Serializable]
public struct FurnitureInfo {
public string name;
public GameObject prefab;
}
[SerializeField] FurnitureInfo[] furnitures;
you can then build a Dictionary from that in Awake
thank you @sly grove. I hadn't thought of that. I'll give that a try next 👍🏻
What's the best way for doing this:
- Storing a series of flags that will determine if a player gets ending 1 or ending 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.
you could use ScriptableObject, one for each category/tag of objects. Each tile would be associated with the category. Scriptable object type would contain list of prefabs
or use a unity tag system
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
==...
thanks!
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))
I see, that's pretty complex tbh... I still have only 1 year or less coding experience. The whole situation seems quite complex to set up now that I think about it.
+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
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.
See, if you go with option two, you do not need those puzzle to listen to any event. Has soon as they are loaded, they are already in correct state.
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.
I wouldnt put the script on the player.
Why?
Because this is a concern of the game, not of the player.
make it one centralized manager/singleton like "GameStateFactManager" or something, querry the game state via that
I see...
If you have multiple player or your player is not spawned, you cannot have the state of the game.
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
if you go that route then remember also that it should be a single source of truth for your state
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
What does that mean?
Oh I see... so the door checks the manager on load instead of the player or anything else
Exactly
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)
Sorry? I don't follow this
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.
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.
yeah, that, the "door open" was meant to represent "a game state" that you are interested in
I see
So the state of the door is defined in the singleton that stores all the variables as mentioned above?
I have a very primitive version of Vue's reactivity implemented in my game for this reason.
No.
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.
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?
You have multiple manager
Then on the door, you have "condition" list.
In the old time, we were using hidden MonoBehavior, today you can use SerializeReference
I see
So the door just stores a list of conditions it must have
And reads the manager on awake
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() { ... }
}
You do not want to have your door depends on those manager though. Instead you use polymorphism to create different condition that will have a dependence on those manager.
I see... hmm I think I'll go look at this a bit more in depth. Thanks for the help 🙂
Are there any materials I can look at to study this more in depth? Honestly this is a bit out there for me rn
You could read on the SOLID principle, that would be a good start. In this case, we used the Inversion Dependency Principle to regulate the dependency.
https://deviq.com/principles/dependency-inversion-principle
Thanks!
The ideal architecture is tree, not a graph.
This is super useful
Dependency inversion principle is the way to achieve that.
However, beware to not over do it.
Principle are guideline
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/
Oh wow I never knew any of these things existed... thanks. I learnt coding by following tutorials
Maybe watching some of my uni lectures
But all very surface level stuff
And this is why self learning is not the best way to learn Coding.
But, this is only my personnal opinion.
Yeah, true
Sadly I don't have the funds for uni
At least not now :/
So self taught it is ig
I have the chance of living in a place where the school cost is one of the lowest in the world.
Ugh lucky, where?
I really recommend trying to find University Curriculum and go through them. Maybe even buy a book instead of relying on Youtube
Quebec
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 
Parents pressuring me
there should be software engineering in any cs curriculum..
You can learn on the way. You do not need to learn everthing at once.
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.
sounds unhealthy :)
I'm not really into book unfortunately, I cannot really guide you here. I just think that they way be a better replacement than Youtube Video.
I believe stanford has free CS course materials?
They do
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
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
Unfortunately, most academic resource will not be on Unity and C#.
I see
Hmmmmm so I guess I should just look up coding architecture principles myself and self teach myself c#
well, for starters I recommend https://gameprogrammingpatterns.com/architecture-performance-and-games.html
This a way, but this is definitely the hardest path that requires the most dedication.
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
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.
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)
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.
The mainstream web frontend frameworks don't use MVVM.
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.
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?
You are overusing enums maybe a bit. They aren’t expressive enough for what you ultimately need them for.
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
most of the enums you write of seem like just simple boolean flags
MAUI, yikes... Even MS doesn't build their own apps in that stuff X)
Ok, thank you!
Because it's not really production ready
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.
static is one per class, so no
I mean is anything actually stored in myValue or is it evaluated to the static value as if it were a function
Was gonna say I don't think you can even use this. The static keyword cannot be used with property accessors.
myValue is one per instance of the class
yes but the getter just returns the static value
but as its using the static all instances will return the same value
yeah further more all classes have access to anything that is static
the static keyword itself is only used to store a value
might as well use the static directly, though that's not always feasible
but you can't user set with it
return as in myValue stores a reference in memory or return as in evaluated at runtime
dont plan to
youre code specifically said public float myValue { get; set; }
the value is already there. in the static variable
you'd have to declare your property as static too.
some inheritors use myValue get and set normally, but I want some to only get from a static value
ahh. Well I suppose jut give it a try and see if it's doable.
so most implementations would be public float myValue { get; set; } but a couple public float myValue { get { return staticValue } set { } }
it compiles fine
yes but does myValue actually store a reference to the variable in memory and take up another 64 bits, or is get run like a function where it pulls from the static value?
I beleive all "property accessors" are technically methods.
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?
myValue will have a backing value, yes as you have a set, but it wont be used
ohhh I understand now, even overriding the get and set doesnt remove the backing value and doesnt then save on memory
yeah essentially.
Typically static keyword cannot be used with property accessors because property accessors are associated with an instance of a class, and static members are not associated with any instance of a class.
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
I would need a GetValue() SetValue(float val) function with no backing variable to save on memory like that
ahh alright
I understand backing values and how getters and setters work now, thanks fellas
You can though.
C#/VB/F# compiler playground.
well I said typically.
Was surprised it was working in this instance
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)
Well ms seems to push people to Maui instead of xamarin, afaik they don't recommend you build new apps in xamarin anymore.
Whether you call it production ready or not, ms certainly seems to try to sell that it is
interestingly if you create an implementation with overriden get and set it doesnt seem to create a backing field 🤔
https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABAzAAgJYB2ALjFAGYCGYMOAYhBALABQA3izpztvsTgEIUoOVjgDmMIgG4cAZ0kyAvi2XMeGAEx0Gg4SG1M2HLuoCMSXkW7ndOALw5TU45x6Ert0RKuiMAdmskXSU5SREcRQicAHpogggcYCoAa0IxHDI8GAAbABMXGOi3Pk9xMN8A4Kj5HwEhexwANwpsgFcYEMjY7LxknIBPOSIUiEbSMmyIAHccAApYMFaoWTwxuqgASgLY4o96rwVQ6SjYpLBUgnTMnPzmRSA=
C#/VB/F# compiler playground.
that compiler is the same as unity right?
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.
good to know, thanks
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.
huh, interesting, did you have any luck using it in unity?
No I haven't tried it, I guess it would be nice to have record structs though 🤔
Is anyone familiar with Ogame programming, i am trying to recreate the combat system, does anyone can help?
Please don't crosspost. Only post to one of the code channels
ogame programming? you mean the online space game OGame?
Since I'm using abstract class for state classes - I guess I cannot make methods separately outside without reference to where variables are centralized?
wdym, what do you want?
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
^
You should pass the reference in the constructor. This way, your StateMachine does not need to know about the concept of the player and you can reuse the StateMachine for other needs.
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;
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
From the docs on normalize:
"If this vector is too small to be normalized it will be set to zero."
Nothing weird, just Vector3/2.zero
oh, ok, good to know, I assumed wrongly based on similar behavior from shaders
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?
What?
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
lets say i have a class Badguy bg1 = new BadGuy ("VariableAsString", inputVariableAsInt)
Does this work?
builder patterns are great when pulled off correctly
what does "variableAsString" and "inputVariableAsInt" mean, paint a concrete example
like a name and HP, e.g. "louis", 15 or what?
The _inputVelocity is a variable in the playerCharacter class. Since it I may want it to be accessed by other states than just the moving state.
would this be a way to add references in abstract classes?
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
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
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.
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.
also #💻┃code-beginner seems like a more appropriate channel for that
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.
I'd scour GitHub for examples then
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
What are you trying to achieve?
in my custom annotated records, get fields that are default-constructible and assign new() to them in the constructor
Well, you'd have to use Reflection which is slow.
You can Google "GetConstructor()"
I use Roslyn code generators and their compiler API to generate additional source code during compilation
I work in compile time, not runtime
Not so sure with them tbh, I'll shut up
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
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.
This may help towards your goal though: https://learn.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.isymbol.isimplicitlydeclared?view=roslyn-dotnet-4.6.0
Hello, i did a TrailRenderer for my game, but this looks like blemishes around the edges. Any solution to make it look smooth?
haven't seen one. Roslyn built-in methods are usually not handy methods, but rather necessary methods. In different code analysis repositories (Roslynator for instance*) you can find lots of utility classes, maybe you'll find one for this usecase as well.
generally, all structs are, and as for classes, need to check manually
Anti aliasing.
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.
Why do you need to very efficiently check this against some kind of data ?
Also, I'm not exactly sure what is the issue here. Can you not simply check what the object is made of ?
Because I am planning to handle a lot of players on a server. Any delay, unless I am threading, is not good for networked games.
I am planning on handling 100-1000+ players
Your situation is like the best situation to have not very efficient algorithm.
So let's say launch day, 200 people were crafting potions, and the slower the better?
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.
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.
You could literaly have the worst algorithm, and still wouldnt matter.
Costs become a factor
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 ?
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
Also, could you just not write the effect on the potion when you make it ?
If it was a fixed recipe, yes.
Garbage collection only matter if you increase memory or decrease it.
In your case, you would do neither.
What do you mean ?
If it was a "fixed" recipe like Garlic + Hydrochloric acid = health potion, it would be simple and sweet.
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.
It seem to me that you either, do not know exactly how it should work or you do not know how to explain it.
Because I still do not get it.
I want to essentially simulate (really simply) chemical reactions and determine that a particular formula would provide x benefit.
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.
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)
Yeah, a bubble sort would work. But it's not free either.
That would be the complexity
I'm sorry, but sorting 5-10 elements is basically free.
You're thinking a single player game.
No, I'm thinking of sort elements.
I sort elements in the Update loop.
And I have no issue in performance.
OK. I'm going to redirect this to another chat.
What do you mean ? You want a second opinion ?
No, I want an opinion that I can visualise as "it will work". Your opinion so far has been "performance doesn't matter" and "I'd do it in Update".
I do appreciate you trying to help though
Yes, it is my opinion. You are asking for a second opinion. No worries there. You should stay here because I believe your question belong to the channel. Just repost your post with some adjustment to clarify things.
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.
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
16k is nothing, you're right if this was the only thing involved in the game. This is just one element in the grand scheme of things.
how much memory is your server currently using?
That's largely irrelevant. Thinking forward it'll end up using more and more. Minimising where you can is important. And even if I were to just straight up surrender that memory, CPU still matters to check each formula and order.
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.
That's fixing what is broken, but I can already see the methods would already consume too much.
I believe you might be surprise by how little time you gonna save. However, do not take my words for it.
Sure, by how much is it ?
Establishing a base is the first step.
Implement the most intuitive algorithm.
That's the issue, I haven't found one that's intuitive.
That's why I asked in code-advanced
I gave you one didnt I ?
Right
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
For this particular issue this isn't the saving grace, but generally I know of the performance benefits, thanks.
I meant using DOTS for the whole application instead of GameObject. (If you are not already using it)
I assume you mean MonoBehaviour not GameObject, unless I am out of the loop.
No, I meant DOTS.
How many chemical reaction results are we checking against?
Unity recently did a post on large scale game
There isn't particularly a number on it. But as the game progresses there'll be more and more.
Also, the Unity employee have been saying that the networking for DOTS is more advanced than the networking for GameObject
It just need to be expandable, and more or less indefinite
I am not using Unity's networking however
You should none the less look at DOTS if performance is that important for you.
I will, outside of this issue
More and more doesn’t mean much, if it goes from 5k to 6k it’s still too little to even worry about performance.
5k-6k wouldn't matter if that was 5-6k unique "recipes" or elemental-compositions, however that's quick to fill if you have to account for every possible combination.
It can get pretty heafty pretty quickly
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.
That's fair if you think that. But given the 15 years I have been programming I just do not imagine it working out for me right now. I'll just for the time being scale it back.
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.
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.
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.
Isn't this just a hash table lookup basically
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
I was actually thinking about hashing, I am already loving you.
You don’t even need to write your own hash, like I suggested string and value tuples have them implemented for you for free.
I am happy you like strings, but unless I want to display something server side, they're a plague.
Then use value tuples
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
Like reactant enums.
But it’s trivial as soon as you know all the reactions can fit into memory
In a compound that would be true. It's just ordering that, which a one off isn't that bad (which it would be).
Right, sorting the input in a way that doesn't change it is one way to make a stable key from it
Cheers! Tunnel vision should be a crime. I just needed that insight. I'll have a think how to create the unique key.
Just keep in mind that keys should be immutable 😄
Yeah, the key is probably the main issue. Avoiding too much process or memory usage is the main issue here, I feel one is going to need to cave.
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?
Just use your domain, then keep original author in package.json and LICENSE
Anyone know how to delete a localization entry via script? I'm struggling: https://forum.unity.com/threads/deleting-localization-entry-via-script.1487955/
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
No clue what those games are, you should probably elaborate on what you are trying to make..
as Trottero suggested, it'd be better if you described the AI behavior you want rather than referencing a not well known game.
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
don't crosspost.
Okay I would want an ai to hide in a room and when you walk up to that room it will chase you for a certain amount of time until it will run away.
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)
Okay I see
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);
I wanted to have a path like this:
https://discord-cdn.is-terrible.com/6dbFOTpvM
But the rotation just seems to mess this up...
You can use transform.RotateAround to rotate around a point 🙂
So you can rotate around the center of the tiles
Thanks for your answer! Unity tells me to use Transform.Rotate instead of RotateAround...
Plus I can't quite understand the rotation that is happening...
https://discord-cdn.is-terrible.com/6dbMcc0Qw
https://discord-cdn.is-terrible.com/6dbMqQAYu
What do you mean by "Unity tells you" ?
And are you sure you are using it correctly?
transform.RotateAround(center_of_the_tile, Vector3.up, cellRotation)
Sometimes I hear the voice of Unity in my head. It tells me things. It tells me that I should use Transform.Rotate...
"Tryyyy multiplyinnng mouuuse inpuuuut by ddeeeltaTiiiime"
Oh my god, it was the voice of unity this whole time!
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
Because they are on the edges, they don't have access to neighbouring points of other meshes, you need to set their normals manually.
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
I mean, looks like they don't
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
Can't assume that without more details
since the entire mesh just shares one normal, perhaps i should skip using mesh normals and just pass the single normal as a uniform
what details would help you help me?
you have vert and frag shaders above
I doubt it's the shader but your mesh gen
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;
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
}
}
Attach a debugger and check that your normals are actually uniform
Visualizing with debug drawline/ray would help as well
See the ones at the edges on each triangle? They have to be exactly the same for there to be no line visible
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
You are using single normal for entire chunk, and they are smoothed only because Unity smoothing kicks in when triangles share points. You want unique normals for each point. Like this (only in here they used on faces with unique vertices to create opposite low poly effect) https://cdn.discordapp.com/attachments/451423007018188800/504675491513368578/Tile_normals.mp4
every normal in a mesh is the same
so smoothing should have no effect
im not using any mesh groups
You need to calculate unique normal for each
It's a figure of speech, you have multiple meshes they are a group of points and triangles
surely unity will not start smoothing my normals with another, for all intents and purposes, unrelated mesh?
You need to calculate unique normal for each
This is your solution
i cant see why this would be needed
since for each pixel i will get a world space normal
Already explained that, your normals on edges look different directions
if i use "real" vertex normals i will have to convert all pixel normals
no all normals of the mesh look in the exact same direction
The seam where they are connected are they looking the same direction?
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
I don't think you are trying to understand.
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
if i remove all other meshes, there's no such thing as "connected seams", but the output normal is still wrong
Right, last ditch attempt to make you understand. You have groups of normals right now. Instead each point has to have own normal set projecting from the center. Like this https://discordapp.com/channels/489222168727519232/885300730104250418/1148310733004754955
This will make your normals where meshes meet line up into same direction smoothly.
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
Hi does someone know how to filter swear words from your game for free?
@simple badge What I told you in the beginning. If you have irregular shape you find neighbouring points and average using those even if they are on another mesh. Like I already mentioned, when triangle share point in the inner area of the mesh you get that automatically with Unity doing this for you.
@twin totem Don't spam. No relation to code, lookup dictionary of banned words.
if i wanted the actual geometry to have an effect on the output normals then yes, but i dont
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
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
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
I haven't looked at your shader, but I doubt it, they are not the same
my maps look like this because i represent the shape of the sphere in the normal map
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
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
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
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)
they are not the same
they are the same
If they were the same you would've had a one flat face
here's one mesh printing the normal
as you can see its uniform
the vertex normal*
I don't know how else to explain :)
Create a smaller model, probe its actual normals, explore how it works.
the vertex normal is the same across the entire mesh
As stated by Fogsight, your normal are not correct.
custom shader @dusty wigeon
Better yet start with a tutorial.
https://catlikecoding.com/unity/tutorials/ Has great tutorials with procedural spheres as well. Should make it clear.
Yeah, then your custom shader might not correctly apply the normal then.
How to build your procedural shaders too
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
It's all good. You can do whatever you want. Your normal are most likely not correct.
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)
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.
If I am not wrong, the shadow is usually the first thing that breaks. Changing the position to a double will not solve this.
Also, the second is animation if I am right.
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.
Yeah I'm wondering about movement - like if it's gonna start getting jittery from moving with a tween
I do not think movement will bug that soon.
Just a prototype video - tiles drawn programmatically, player moving around simply
Pretty sure that movement will not bug till you are really really far.
Like near the end of the float precision.
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
I haven't tested how optimal tilemap is. I think it supposed to have chunking handling, but didn't get to testing to scale.
(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)
It shouldnt be that bad. You just have to never use transform.position and use that instead.
I'm doing the chunking myself, fwiw.. it was a little bit of a headache but I wanted control over what was in memory.. as far as what Tilemap specifically chunks/culls, I don't think that'll be a bottleneck for me since I'm manually unsetting tiles periodically as they go out of range
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
My solution to this is lazy evaluation only calculated the world position when needed to reduce O(number of vertex*8 ) memory
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)
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.
define "initialized"?
are you expecting to assign it in the inspector?
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
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.
it wouldn't be a compile error
it would be a runtime error
there is no gaslighting happening
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.
IDE will not catch it
it's a runtime error
you have to set the reference
Thank you
You could do it in a constructor, or simply by assigning it directly since it's a public field
It's an abstract class, not monobehavior. It's not some script I attach it.
since this isn't a MonoBehaviour, we're working with basic C#
Oh mb, I thought that link covered POCOs too
With constructor you mean the derived classes?
The derived classes will need their own constructors, yes
ideally they invoke a constructor from the parent
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);
}
}```
Any reason not to just do:
FlyingState flying = new FlyingState(pc); without the Awake?
the field initializers run before deserialization
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
I see. Since my current method of doing is just this.
Right
unless you can guarantee you have a valid reference to the player controller in a static context somehow
If this screenshot is on PlayerController, then it can work
it is
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
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.
If I do not make those states public, the derived classes can't seem to access them.
make them protected
not public
Nah, still can't access them. They're not being derived from player controller.
Player controller is a mono
if the classes you are making aren't subclasses of PlayerController then no, they can't be accessed from those classes
unless they're public
but - why do you need to access them from anywhere else?
oh I guess to change states?
Yes
In Unity WebGL, how can I call Javascript functions defined outside the project?
It said I must do:
// .cs
[DllImport("__Internal")]
private static extern void MyMethod();
// Plugins/helpers.js
mergeInto(LibraryManager.library, {
MyMethod: function() { }
});
But I don't have a Plugins/helpers.js file inside the project. That file is outside and may look different.
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.
so create a js script that calls those outside functions and/or that has functions that interact with your C# code
here's an example of how you can do that https://forum.unity.com/threads/call-javascript-function-in-index-html-from-webgl.625480/#post-6406899
Ok, I'll try that
do ModifyiableContactPairs work for 2D? I only see it for 3D. Alternatively, if there is an equivalent for 2D, that would be nice too
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
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
Instead of an intro. This is a doc describing an early experimental API for modifying contacts right after they were computed in the narrow-phase and before the solver will calculate constraints out of them. Contact modification might be useful for custom reactions to contacts, basically. Here...
also there's no 2D version of this struct, unlike other physics classes that have a sepaarte 2D version (https://docs.unity3d.com/ScriptReference/30_search.html?q=ModifiableContactPair)
!ban 931732121997959219 spam
funcieq#0 was banned.
@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
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.
it is smooth as you can see in the second screenshot, i have no problem creating the geometry
So what's the problem then?
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
Check that those points on the border have precisely the same normals on both meshed meeting there, it could be they are slightly off.
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
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.
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
autogeneration would not know anything about other neighboring mesh
doesn't have to, it's a sphere
for (int j = 0; j < normals.Length; ++j) {
normals[j] = verts[j].normalized;
}
m.RecalculateTangents();
yep, am doing that after setting normals
but then again, the normal map is flat, so tangents should not matter??
it's not aware of sphere it just calculated for its mesh
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.
That I don't know, I only dealt with low poly looks. But if you have problems might be relevant
(sry, my Discord didn't update until I sent something...)
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)
(Why not? Just curious why you would tell someone they shouldn’t build a music player in Unity)
It's simply wrong tool for the job.
Explain?
It's a game engine
Apps are better made in app frameworks
Which are lighter, and take way less resources
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.
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.
Sure, but that example also makes use of what Unity provides
Yes that’s my point
If you want to make the trippy sound visualizations like Windows Media Player has then sure, you can use Unity for that
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"
Yea totally!
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)
Word. This convo is making me a bit curious how Spotify works.
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.
Pretty sure spotify is a web app.
They probably convert their audio to a specific format during upload so they have full control of what format needs to be decoded by their player
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.
Frontend is but I doubt that actual music player is written in electron
I mean, Web APP stack. Frontend/Backend.
They've got a pretty good dev blog, you might be able to find some info there
thanks. this helps. Would you know if there is any alternative way to do something similar? I’m effectively trying to write my own version of a PlatformEffector2D
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.
Unity doesn't support covariant return types for overriden methods???
not in 2020 at least, just tested
#Creating a computeshader asset with an editor script
I don't know really
Isnt like .Net 5.0 functionality ?
Dunno which .net, but C#9
Unity does not support all function of C#9
interesting; know why can't they support the whole thing? 🤔
don't it all just compile down to IL for Unity to use? what's special about these C# rules?
It could require newer runtime support
.NET level change, not just syntax sugar
ty for the help. my quest for oneway platforms on tilemaps continues
i really wish we just had better 2D tools for this
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
you can use prebuilt DLLs from newer C# versions in most cases, it's just unity's own build system that doens't support newer versions yet
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
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
is there a way to simulate an import of an asset?
why not create a scripted importer?
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
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?
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.
hm okay, and is there a way I can import a file by code?
AssetDatabase.ImportAsset(...)?
If you have a ScriptedImporter, it will automatically trigger when Unity detects a new file with a matching extension.
okay tnx I'll try that stuff, importing the .compute file directly did not work for me
hmm, but how would api exposed through dll work if it uses incompatible language features, for example struct records?
you could try with default ShaderUtil.CreateShaderAsset(string content) and just pass compute shader
the OnImportAsset together with the ShaderUtil.CreateComputeShaderAsset actually works for me
hmm, no, nevermind, seems like shader asset =/= compute shader asset, I thought they are the same thing just different source code inside
Record struct is just syntactic sugar, you can take a look at lowered C# output https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+tJQCYAIDOALlAK5iG4Cq+MUAFAAICMADLgHICGAtjADS4AlgDsKAQQDmMAJQBuIA==
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?
@spiral aurora Stop spamming your question across this server please.
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.
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
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?
yes
any assets directly referenced in your scene will be loaded with the scene
For pretty obvious reasons I think.
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
Look into #📦┃addressables then
yeah, I'm in the middle of transitioning our game to addressables. How would that interact with prefab references stored in scriptable objects?
you would store AssetReferences to them instead of direct references
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 😓
you can read data directly on it, it needs to be actually loaded into memory for that to work
barring some magic AOP injection style code
yeah, that makes sense in retrospect, it's just incompatible with the way we were using the system
whats the purpose of having files in a runtime folder?
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?
Use class instead of Enum
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.
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.
what I mean is this
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
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.
That's just package layout convention it doesn't actually mean anything
And it doesn't look like they even separated their asset into assemblies anyway
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?
Just use Update. 🤔
You can use a coroutine or add timers if you wanted to reduce the frequency you search at
wouldn't this be more efficient in the long run?
Do what makes sense for your game
I prefer to use Update same if we do not update the function every frame. It is more readable.
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 ?
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)
In real life it's friction. In unity it's drag. You need something similar to dissipate the kinetic energy of the object.
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
Well, I'm not sure of the details, but there's definitely some sort of drag involved. Something is decreasing the velocity/angular velocity or forces affecting the object with time or on collision.
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
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?
yes, gravity as a constant accelerating force
to my understanding thats all there was to it
Constant force or velocity? These are 2 different things.
its using the same equation as the Forcemode Accelerate method Unity has
In this case that is correct(if I understand your setup correctly).
velocity over time indipendent of mass
Yes. Although I don't see your code, so I can't say if the implementation itself is correct.
That doesn't reveal a lot, but this part should be fine.
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
That's fine, but there's a lot more to moving objects than just applying acceleration.
the value this gives is then used like so
velocity = exampleVector2.normalized * exampleForce
exampleVector2 storing the direction it needs to be going in
You can use velocity vector directly in the method actually, though this cant help your original question
So far it's fine, but as I said, it's just a small part of physics.