#archived-code-advanced
1 messages · Page 167 of 1
Haha
it's bugging me so much that you're still using sublime text and posting in #archived-code-advanced, we force beginners to use working IDEs here, getting this far without an IDE is insane
Guessing the high progressId is some running number that never is decreased?
I... yeah fair sorry, was something beat into me by my middle and high school
Sublime can be fine imo
no because the progressId is a list that is entirely deleted and refilled every time I call the assetmanager and refilled by whatever the
built in Progress class decides
Just let Unity do it's thing then 😛
ok lol
can be? I tried it for a period in between MonoDevelop and Visual Studio before I found Rider and found it could not be configured beyond extreme basics, that being after spending a ton of time figuring out plugins, causing it to become insufferably laggy 😄
It doesn't have so many features I consider mandatory even beyond that. Am I missing something?
its notepad with autocomplete XD
its simple
thats about it
Yeah, that's what I would consider "not fine" 😄
You can install quite a few plugins
Including omnisharp
If you want
But lots of languages don't have such fancy tools as java or C#
XD
yeah sublime does actually have the ability to support a lot
its just an absolute pain in the ass to learn how, i remember when trying to get C++ to work on windows with sublime
Support with it has probably gotten better in the 5+ years since I last tried to use it with C# 😄
Idk, omnisharp was already a thing 5 years ago
uugghh ok so seeing when its not equal to running isnt working apparently all are always running...
Emphasis on +
its still not registering as compelte
is this due to me closing it in an async?
or doing the remove or alternatively setting its status?
wait
cant I just
close it if progress >= 100%...
answer?
Yes!
goddamnit
Probably, I unfortunately don't know that api
yeah... instead of doing fancy "Are you complete yet?"
I can just see if the progress is 100%
and close it on that
so it appears that Async tasks dont like to write to litterally anything and will refuse to do so without telling you
Well yeah if you don't do async correctly then errors will go poof
Hello everyone, not sure if this is the correct channel, will gladly move to a suggested channel if more appropriate haha but for me this is advanced coding (even though I am not an expert) 😋
I'm using a script that logs data from my project (car position, player position, and other things). This is a Binary Writer and Reader, as it also converts the data to CSV which I can use to further process.
However, I'm getting an "Out of Memory" exception:
OutOfMemoryException: Out of memory
System.Collections.Generic.List`1[T].set_Capacity (System.Int32 value) (at <fb001e01371b4adca20013e0ac763896>:0)
SerializationHelpers.ReadListVector3 (System.IO.BinaryReader reader, System.Collections.Generic.List`1[T] buffer) (at Assets/Scripts/Networking/LowLevel/SerializationHelpers.cs:94)
SerializationHelpers.ReadListVector3 (System.IO.BinaryReader reader) (at Assets/Scripts/Networking/LowLevel/SerializationHelpers.cs:89)
LogConverter.TranslateBinaryLogToCsv (System.String sourceFile, System.String dstFile, System.String[] pedestrianSkeletonNames, System.String referenceName, UnityEngine.Vector3 referencePos, UnityEngine.Quaternion referenceRot) (at Assets/Scripts/Logging/WorldLogging.cs:358)
LogConverter.OnGUI () (at Assets/Scripts/Logging/WorldLogging.cs:752)
NetworkingManager.OnGUI () (at Assets/Scripts/Networking/NetworkingManager.cs:91)```
Is there anyone here willing to help me solve it? I'm a bit desperate lol
Sounsd like you have too much data
Are you suggesting somewhere the script is dumping an overload of data into the file?
I created multiple scenes and I have a framework that let's me loop all of the scenes after eachother by means of experiment definitions, after a certain trigger is hit. When the trigger is hit, it stops the logging of data, loads the new scene based on the new experiment definition, and inserts the player and car and other objects, then it starts logging again.
Perhaps the error is somewhere in the logic of this, or indeed the script is dumping an overload of data.
The error msg doesn't tell me much. Basically it's just the functions that are called and the two errors referencing the BinaryReader
No it's an overload of memory
Since it's reading, it sounds like your file is too big to fit in memory
Including intermediate steps
That shouldn't be the case, the files are all below 1 MB (in size, that is)
Not sure about the memory.
Lists capacity is 2.14 billion items
Idk if it throws an OOM exception if you try to create a bigger list
is there anything exposed that could do camera projection math without involving an actual camera object? like i need to set the culling matrix of a camera according to a hypothetical camera that doesn't actually need to render, so i would like to just produce the matrix in code without setting up an entire dummy camera and getting the matrix from it
but hitting my head against matrix math isn't very appealing
Here is the code from the Binary Reader related errors, in SerializationHelpers.cs line 89 and 94:
public static List<Vector3> ReadListVector3(this BinaryReader reader)
=> ReadListVector3(reader, new List<Vector3>());
public static List<Vector3> ReadListVector3(this BinaryReader reader, List<Vector3> buffer)
{
var count = reader.ReadInt32();
buffer.Capacity = Math.Max(buffer.Capacity, count);
for (int i = 0; i < count; i++)
{
buffer.Add(reader.ReadVector3());
}
return buffer;
}```
The error is triggers on line 89: `=> ReadListVector3(reader, new List<Vector3>());` and line 94: `buffer.Capacity = Math.Max(buffer.Capacity, count);`
It is indeed mentioning a certain Capacity @flint sage
i guess all those methods will just be internal to the camera component, but actually maybe i can just yoink things from the source reference ...
... and that part probably isn't in C# is it, lol
ah thankfully orthographic is what i need so the projection matrix is actually pretty simple, and the culling matrix is just the world-to-local transform matrix with its handedness flipped and then multiplied with the projection matrix
no pointless cameras!
A bit late, but Matrix4x4 should have all the functions required to create projection matrices, both orthographic and projection.
lol yeah looks like it, figures
Hello, I was wondering if anyone could help me out. I have an app. It works 100% as intended on Android, Windows editor, MacOS editor, but on iphone, at a very specific points, it crashes with EXC_BAD_ACCESS. But it does so only when I try to reach a specific array of int that is clearly initialized. Can it be the consequences of some larger memory issues ? How to know where the memory problem is really coming from ? I would really appreciate some help on this as I have been trying things for a lot of hours.
It is to be noted that there is some unsafe code running before I try to access the array. Could it be related ?
Could it be that I have some null ref in my unsafe code that only pops when I leave the unsafe context and try to access another memory block ?
Yes, that can happen. An actual null dereference would usually show up immediately, but in unsafe code you can definitely corrupt memory in ways that don't show up immediately but at some random point later on, when something else tries to use the memory you accidentally messed with.
(Just realized you asked half an hour ago, so here's a ping so you see this @cosmic flame )
@agile yoke thank you for your answer, I'll triple check everything !
Hey, So i have this issue of i have a block builder and i want the ability to texture each side of a cube with different textures / materials, any ideas?
I suggest watching one of those "I built Minecraft in a day" tutorials on Youtube. They usually show how you can do that quite early on in the tutorial.
will take a look, though i want to change it on runtime with a coloring tool or something
Holy crap. Calling Camera.Render() generates >100 KB of garbage per frame in HDRP.
VolumeComponent.OnEnable is invoked 44 times per frame in the default OutdoorsScene.
0 bytes in Legacy.
Yeah I'll eventually go there. Started here while I was testing in case I was rendering to an offscreen canvas wrong (in general).
But yeah it looks HDRP-specific.
public abstract class BackgroundBase<T> : MonoBehaviour where T : ISystem<BackgroundBase<T>>
hmm
is there any way I can solve this generic puzzle?
so far, this errors on my system
which is T
I solved it
you'd have to show LoopingBackgroundSystem and MovingBackgroundSystem
public abstract class BackgroundSystem<T> : MonoBehaviour where T : BackgroundBase
{
protected List<T> list;
protected virtual void Awake()
{
list = new List<T>();
list.AddRange(GetComponentsInChildren<T>());
}
}
public interface ISystem
{
public void DoUpdate();
public void Register(BackgroundBase component);
public void Unregister(BackgroundBase component);
}
public abstract class BackgroundBase : MonoBehaviour
{
}
public abstract class Background<T> : BackgroundBase where T : MonoBehaviour, ISystem
{
protected T parentSystem;
protected virtual void Awake()
{
parentSystem = GetComponentInParent<T>();
}
protected virtual void OnEnable()
{
parentSystem.Register(this);
}
protected virtual void OnDisable()
{
parentSystem?.Unregister(this);
}
}
here my solution
adding additional empty layer
as base
without <T>
Is there a way to attach script in the inspector that isn't inhereting from the MonoBehaviour?
almost everything that is serializable can be attachable in inspector
But Im talking something like that example
public class FooBase
{
}
public class BetterFoo : FooBase
{
}
and I have another script with serialized field, and I want to assing in the inspector "BetterFoo" class instead of "FooBase"
public class FooUser : MonoBehaviour
{
[SerializedField] FooBase foo;
}
So I tried it and its not working :/
did you add serializable attribute to your class?
yes
I have a series of inherited objects (ObjectBase -> Object1). ObjectBase has a default sprite assigned through Unity but I want Object1 to show a different sprite. How can I do this upon initialisation?
public class Object1 : ObjectBase
{
[SerializeField] ItemBase item;
public void Init()
{
this.Sprite = item.Image;
}
It feels like something like this should work but the Sprite stays the same
item.Image is a Sprite. I should probably rename that...
Is this.Sprite a reference to a SpriteRenderer's sprite? It just some variable holding a reference to a sprite?
Also does Init even get called?
I'm having an issue where I cannot get my contextValue to show in editor. the value can be a bunch of things int, custom class, ect. Is there a way to tell the editor to show for a certain type based on what the "contextType" is? [System.Serializable] public class DialogContext { [HorizontalGroup("bool")] public bool setFlag; [HorizontalGroup("bool")] public bool setContext; [ShowIf("setFlag")] public Flag flagType; [ShowIf("setFlag")] public int flagValue; [ShowIf("setContext")] public ContextType contextType; [ShowIf("setContext")] public object contextValue; }
You probably need a custom PropertyDrawer or custom inspector for the class
bummer. But thanks for responding.
I'm using an Image GameObject where I can set the sprite. You make a good point about the Init() function - it may not be
Odin Inspector can probably do it with an attribute, too.
I'll check it out.
I think you can use OnValidate
No luck :(
😦
Is there something like OnAccess?
Share the parent class code
Where and when are you calling Init?
I'm not convinced I am calling Init at this point but I'm reading parameters out of the object. Here's the part that does the displaying of the image:
public class ItemSlotUI : MonoBehaviour
{
[SerializeField] Text nameText;
[SerializeField] Image itemImage;
[SerializeField] bool isRead;
RectTransform rectTransform;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
}
public Text NameText => nameText;
public Image ItemImage => itemImage;
public bool IsRead => isRead;
public void SetInformation(ItemSlot slot)
{
nameText.text = slot.Item.Name;
if (slot.Item.Sprite != null)
{
itemImage.sprite = slot.Item.Sprite; // This line displays the sprite
}
if (!slot.Item.IsRead)
{
nameText.fontStyle = FontStyle.Bold;
}
}
The slot one is pretty straightforward:
[Serializable]
public class ItemSlot
{
[SerializeField] ItemBase item;
public ItemBase Item => item;
}
Here are the relevant parts for the base class:
public class ItemBase : ScriptableObject
{
[SerializeField] string name;
[SerializeField] Sprite sprite;
public Sprite Sprite
{
get
{
return sprite;
}
set
{
sprite = value;
}
}
no idea what all this is. Where's the code for ObjectBase?
What does this code have to do with the earlier shared code?
If you don't call Init(), it will not run
And here is for the one that builds on the inherited object:
public class PeopleItem : ItemBase
{
[SerializeField] CharacterBase character;
public void Init()
{
this.Sprite = character.Sprite;
}
}
Some functions run by themselves. Awake(), for example, when the object is first loaded
If only there was a way to figure out what those magical functions are and when they run
Mazel tov, Init ain't one of them
This? I've been using it a lot https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
Yes Awake works
it's a thing
that's not really relevant to your Init function though
Also these are ScriptableObjects
which have very different rules
I need to ensure the function is called, either directly or indirectly, before the relevant line in the ItemSlot code
It's gone midnight here - I'll have another go tomorrow. Thanks for the suggestions
using (AndroidJavaClass UnityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject View = UnityClass.GetStatic<AndroidJavaObject>("currentActivity").Get<AndroidJavaObject>("mUnityPlayer").Call<AndroidJavaObject>("getView");
using (AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect"))
{
View.Call("getWindowVisibleDisplayFrame", Rct);
return Screen.height - Rct.Call<int>("height");
}
}
Anyone got an iOS equivalent code for this? Basically it just gets the height of the virtual keyboard on a mobile device. Thanks in advance
does Start() get called before a scene is fully initialized?
I ask because I have a script where, in Start(), I call GameObject.FindObjectOfType<PlayerInMap>(); (yeah, I know FindObjectOfType isn't recommended, and I should refactor ...)
and it returns null, despite that scene absolutely having a PlayerInMap object in it.
is it just because Unity is still creating all of the scene's objects? or is something else going on here?
no it doesn't get called before the scene is initialized
ah okay. that's good to know. something else must be afoot here. I'll keep investigating 🕵️♂️
ahh found the issue now. I was wrong about that function call returning null. something else was happening, and I was looking at the wrong line number
Can anyone vouch for NetEase's plugin for integrating Unity with Node.js?
socket.io client for unity3d. Contribute to NetEase/UnitySocketIO development by creating an account on GitHub.
Might be weird, but I'm not trustful of Chinese software.
Why is screencapture not working?
You named your class screen capture
ohh yeah lol thanks
How can I calculate child position and rotation around parent pivot? e.g. in editor on Gizmos.DrawMesh(), I display all the meshes of a given prefab and I need to add a rotation offset to each child mesh, so Gizmos.DrawMesh() reflects the Instantiate prefab in play mode with the given rotation offset.
That's what localPosition and localRotation are
private async void StickToPlayer(Transform player, float duration)
{
var end = Time.time + duration;
while (Time.time < end)
{
transform.position = player.position + positionOffset;
await Task.Yield();
}
// That part
}
with this code, it means that commented part will run only after time duration is over?
meanwhile all inbetween transform will be modified
why not use IEnumerator? you can also cancel it anytime
coroutines are meh
and yes to this part
Hello, I am trying to make an gameObject with particleSystem teleport and replay the particle animation, this is the code I've got but doesn't seem to work.
Note: projectileExplosionOBJ is the particle gameObject, and projectileExplosionPS is the particleSystem on that gameObject
public void SpawnProjectileExplosionEffect(Vector3 pos)
{
projectileExplosionOBJ.transform.position = pos;
projectileExplosionPS.Stop(true, ParticleSystemStopBehavior.StopEmitting);
projectileExplosionPS.time = 0;
projectileExplosionPS.Play();
//projectileExplosionPS.Emit(40);
}
Does anyone know if I can set the vertices on a submesh with point topology to be bigger than they are when created as a mesh?
Okay I have no idea why but the exact same code now works lol, no more help needed
Is there a way to get the thread name of an async task that points to a thread you can see in profiler?
no. however, unitask does provide profiling for UniTask instead of Task
hmmm
I thought Thread.CurrentThread.Name was a thing
Maybe it doesn't work in Unity
Or even the ManagedThreadID, if you can get by ID
just use begin profiler nameof method
it doesn't make sense
to look for a thread corresponding to an async task
in a unity profiler
i don't think it traces managed threads specially unless you ask it to, and the way to ask it is to use beginprofile
Well, if they can see the thread in the profiler, they did that
it just won't mean what the user thinks it will mean
One way to find out, get the thread name from code and compare
you can cancel stuff like this. but you would have to use UniTask to make it easier
i'm not sure why people are not using UniTask for async in Unity
lol the advertisement pushing, UniTask here, UniTask there, UniRX over here
lol
yes i am encouraging people to use the only good free library to solve these problems
it's bad.
create a custom editor.
The problem is, they probably have a fully-fledged system already (since asking in #archived-code-advanced), and can't be bothered to switch the whole architecture to one of these "only good libraries"
Or the solution is overkill for them
hard to say without seeing what is going on at those specific points. EXC_BAD_ACCESS will happen with a real, managed null
there's nothing to switch over for unitask
besides, i don't know, that's just how it goes with Unity. you gotta use libraries
In what way?
even if it weren't buggy, it won't provide value.
does anyone author new socket.io based servers anymore?
most of the value in this stuff is in the IDL
grpc is painful to set up for unity though
Have any suggestions for handling large numbers of players?
The Node.js is more meant for REST calls, I don’t actually need socket.io for that at all.
what kind of game are you trying to make?
is your approach right now to relay networking
or is there an actual hosted game server
are you trying to do p2p
Oh man I don’t know how to answer that without giving away a whole lot.
Absolutely no P2P.
giving away?
i don't know if there's anything sensitive about a multiplayer architecture
Welp, alright, here goes
I need to handle groups of star systems on their own instances. If a player goes from one group of stars to another, the two instances need to communicate to facilitate that transfer.
A single group might contain anywhere from 10-100 star systems, each of which the player is free to move around in on 3 axes.
Most likely Unity.
Like I said, Node is going to be for handling REST calls, like retrieving system data; planets, moons, stations, etc.
All of that information is permanent, but there needs to be an additive layer of information for things like temporary objects. Asteroids that disappear when they’re depleted of materials, non-NPC stations that can be destroyed, etc
Need 1000 more people like you.
lol
what's nice about committing to use unity as a server is, what you see is what you get
Yeah, absolutely.
if you like building the rules of your game in unity - like if colliders & physics are important to the rules especially - it makes sense
it's just a pain to deploy
Plus it handles a lot of stuff that makes the overhead worth it
there is no easy way to do it
there are a lot of networking libraries that are designed to deal with synchronizing two unity processes in a general way
which is also pretty useful
This will almost certainly require DOTS, so I’m gonna have to bite the bullet on that one.
there are ways to gracefully go from syncing transforms and such to syncing the small pieces of information you need
hmm... DOTS doesn't really exist as a product yet
i wouldn't commit to that from the get go
if i were you
I'd double that
dots is pre alpha
Fair
if you wanted to do this "easily" i would start with photon, since it has the best developer experience for a graceful move from "Level 1" syncing transforms to "Level 100" syncing something logical
but that is essentially Relay
you can do hosted stuff with photon
i'm not sure who does
but you can
in terms of doing the networking yourself... it can become a big faff
Would it make a fully authoritative server any less painful?
Photon Fusion and Quantum absolutely would
Is fully authoritative even preferred for an MMO?
Noted
Though I don't think you would use those for an MMO 😄
it really depends. in some sense, a blog post will tell you it is the only way to do things
but if it's meant to be experiential
i don' tknow how important fully authoritative is
Might aswell experiment.
it places a large burden on you as a developer for little gain for the average user (who doesn't cheat)
in principle, a single vertically scaled unity host can be pretty capable
BRB. I’ll keep reading when I come back. I value your input.
it isn't worth introducing clustering (i.e., having multiple instances share the world together) unless you absolutely have to
$001
it's just so complicated
lol
clustering on the backend is a huge faff
for, again, little gain for most of the lifetime of the project
it's more valuable to learn to scale a lot of independent, vertical instances - and to design your game that way - rather than have one, unified game world that is all clustered together
Shouldn't be too bad if your world is split, so you can properly treat each area as a different server
it just takes a very large amount of content arranged in a pretty idiosyncratic way, like Eve Online, to justify clustering
even then, i don't know if they cluster nowadays
in all but the absolute biggest boss fights
Boss fights being large pvp battles between factions? 😄
yeah
Eve has sectors afaik, so the splitting is relatively easy
They cluster. You’ll notice when TiDi takes effect, or Time Dilation. It’ll affect several systems, and not just the ones where shit’s going down
Also, I guess that’s my big secret..
Hello, everyone, I’m your friendly neighborhood psychopath
truthfully i think for what they do it's very reasonable, it's tricky to have 24k concurrents share state in a complex game
but 24k concurrents is really high
even 300 concurrents is like 20k DAU
which will easily run on a single machine (not necessarily a unity server)
but by then you'd have a really successful game
processing 300 concurrent users in one unity server instance is hard
and i would just focus on that.
it is free ot have more planets and geometry and whatever
it's not free to have more rigidbodies
there's limitations in unity physics that are painful
conversely, you could adopt an architecture where that matters less
eve online is estimated to have like 250k-400k DAU
if you don't use unity as the backend
then you're signing up to write a game engine
How do i get the color of 1 specific pixel from an image?
and how to i set a color with a script privately, as in one material or shader shows up differently on every object i place it on
Exactly what I’d like to avoid
This is good shit. MMO stacks are like a dark art. Getting information is like learning sex ed in America. They’ll tell you not to, you’re not ready, but they never say what to do when you are ready.
you are never ready, thats the point
you just have to be stubborn (and rich) enough to pull through
Applies to having children lmao
what helps tremendously is understanding and checking your bottlenecks constantly, build with minimal shared state in mind, make clever content decisions that minimize the actual need for sync, you brought up EVE, thats a nice example of design minimizing the realtime-requrements
Appreciate the help, though. I like being able to decide for myself if I really want to do this.
Eve has its issues, but all things considered, it really shouldn’t work as well as it does.
most of EVE is a RDB that is infrequently synchronized
the little bits where you see other players could almost be fortnite-type battle royale instances
Yeah, the tick rate is pretty abysmal
But
That’s also part of why it works
Do you know where I could read some technical writeups on various backends? I know most companies keep this stuff close to their chest.
also look at WOW as an example back in 2004... it could only handle 1 raid boss per server concurrently
eve launched in 2003 iirc
Old as hell
its also had some major architecture updates since
and wow has world phasing and server groups and various other things since then
I only got into it around 2014, and I couldn’t fathom back then even knowing where to start. But I’ve been slowly learning about the backend stuff that makes general web applications tick.
the hassle in MMOs comes from having to integrate various systems that have totally different sync needs
and fuse them together such that they appear to be part of a continuous world
From what I’ve read, this is why there’s nothing close to turnkey. Every system is custom.
I want to get the GameObject position below the player, remove the collision box of the player then make the player move without gravity, slowly toward that GameObject. Then when the player is at the GameObject position, destroy the GameObject and add the collision and gravity back to the player. How can I achieve that? I want a result similar to Motherload game.
is anyone familiar with steamworks?
I think people who are aren't allowed to talk about it
oh mbmb
Nah, Steamworks is not as secret as console SDKs. The documentation is public.
https://partner.steamgames.com/doc/home
i think for now try to get to 10 simultaneous players
it's better to make an interesting game with 10 concurrents on a single instance than an uninteresting game that doesn't exist yet with 20 concurrents on a cluster
Fair point.
Do you think I should go with a cloud provider or self-hosted hardware?
I have hardware of my own that I do some light homelabbing on. Ubuntu server, etc.
But that also means configuring that much stuff myself where Amazon probably knows how to configure Redis better than I do.
scaling beyond a single instance is challenging in either case. there's no open source load balancer with a default configuration that makes sense for games.
the economy of self-hosted hardware on a single instance isn't that great compared to an aws instance
it is really challenging to set up a unity server build pipeline. it's 2022, and unity doesn't have an easy way to build a player in a docker container
they are just not interested in helping you do that
most of the pain is around this stuff
I was kind of expecting to have an array of either VMs or on-metal servers anyway. Going by how quickly Unity catches up to stuff, we’ll have a solid Docker workflow by 2030
it just all winds up being this huge distraction
to a certain extent the number of players you have is 1 right now
you can always use photon to transition to something networked multiplayer
photon is appropriate for "early access" multiplayer
Subjectively, do you enjoy working with PUN?
i have never used it
lol
i know right?
i guess that's not true - the one prototype i used it for it was perfect
in my experience, basically no one knows how to create multiplayer games
it's just too hard
you get mired in months of bullshit
I get that.
Doesn't help that Unity is on.. what.. its third iteration of the transport layer since 2015?
mind that, unless you are only focusing on prototyping gameplay, PUN based code will not reveal the required architectural choices for an actual MMO-style game with full server authority. And a too optimistic gameplay prototype can doom any chance of converting it into an actual MMO. So ideally, gameplay prototyping also checks for bottlenecks in the required netcode to realise it the desired scale.
I love that you guys are actually presenting information
StackOverflow would say "why are you making an MMO? no one plays MMOs, and they blah blah blah use PyGame instead"
it's a tricky problem
this is all just advice derived from first-principles, netcode theory and a tiny bit of experience mixed in. It is almost impossible to get anything more than that since everyone who has done a MMO will probably only know what has worked for them and i suspect very few people will really have expert-level experience in MMO networking
usually for solo game developers you are going to benefit the most from assuming you're making a regular multiplayer game
where the server just runs longer
because by the time you're done, computers will be faster anyway 🙂
assuming your bottleneck is the CPU that works
and assuming your code can scale horizontally
Scene MainScene = SceneManager.GetSceneByName("Main");
GameObject[] SceneObjects = MainScene.GetRootGameObjects();
Transform ObjectRoomList = SceneObjects.Find("Room").transform.Find("ObjectRoomList").transform;
How I get "Room" GameObject from specific Scene? I tried this, but don't work..
This is why I was hoping DOTS was further along in the few years it's been public knowledge
Ok :p
data oriented design has been around since the 90s and before, it is a well understood problem it is just not very commonly used outside relational databases and some inhouse-game engines... if you want to build netcode for lots of CCU you'll have to use it in some form anyway... cant make an MMO without making data your primary citizen
so "waiting" for DOTS to automatically solve all problems will probably never happen.
Totally fair. I figured there was a possibility I'd be making my own solution. As long as I understood the principles, that's what would be important.
private IEnumerator TestCoroutine() {
const float TIME_DELAY = 2.0F;
float audioLength;
// delay before start
yield return new WaitForSeconds(1.0F);
for (int i = 0; i < 3; i++) {
audioLength = AudioClips[i].length;
sceneinfo.audioSource.PlayOneShot(
sceneinfo.AudioClips[i]);
yield return new WaitForSeconds(
audioLength + TIME_DELAY);
}
yield return null;
}
With the above code snipped, the clip seems to want to play, but it's extremely stretched out / slowed down. Am I missing something?
Turns out I was calling StartCoroutine every frame... 😅
well then
Before I get too far down this rabbithole, if I set a local variable to a dictionary reference, when I change the local variable does it change the underlying value? I.E player = Data.characters[Data.player];
If I change a value in player does it effect the dictionary?
Kind of hard to get a read on what you're trying to do. May I see a little more context code?
depends, if player is a reference type you can change any of its members and they will be changed for all references to that same object (since they are all the same object of course). However if you change the value of player by setting it to reference a different object or if it is a value type then the object stored in the dictionary will not be affected
Character player;
if (Data.player != null)
{
player = Data.characters[Data.player];
}
else
{
player = new Character();
player.ID = Guid.NewGuid();
Data.characters[player.ID] = player;
Data.player = player.ID;
}
player.name = value;
player.tooltip = "Not Set";
player.description = "Default String";```
if Character is a class, then changing the properties at the bottom will affect the object in the dictionary since it's a reference to the same object
Like Box said, it depends on if it's a reference type (class) or data type (struct)
It is a class
Oof Discord, that is fugly
then it will work like that. What won't work though is setting player to a new instance of the class as that won't update the reference in the dictionary
Awesome! I'm trying to do a big code refactor and that makes alot of my work with dictionaries much more readable.
2 lines after I do a direct change. will that work? player = new Character(); player.ID = Guid.NewGuid(); Data.characters[player.ID] = player;
yeah, that's actually a good example of what I mean, you are updating the reference stored in the dictionary there to be the same object the player variable points to. If you didn't update the reference in the dictionary then the dictionary would not reference the same object
Heck yea. Love when I get it right the first time. 🙂 Thank you and @ocean raptor for your help.
Hi, I'm doing a jrpg game like final fantasy 13. Am up to setting animations.
I've taken a look at animation events but it seems to be like the opposite in terms of logic flow to my game, where I does anim and calls a function, but I can only see my game doing a function that calls the anim.
Just having trouble tryna work it into the game. Does anyone have any tips?
For reference my game does this.
- Charge an atb bar.
- at 100, perform action and reset the bar
I just don't know how to fit in animations. My thought process is maybe make a coroutine and have some waitforseonds thing for whatever action/animation timing I need? But it seems very janky coding
Every time the bar moves, check if it equals 0.
What you’re describing is a cycling action.
When the bar is fully charged, you have a method that resets it, correct? So fire off the animation in that method aswell.
Or better yet, learn about events so they don’t have to be so closely coupled
Hello, I am in a programmer for a few year and I still don't fill like i'm a good coder, most of the time i try to use some c# tricks turns out that was overkill and unnecessary, i mean Generics, interfaces, abstraction and so on. i don't need primitive or mediocre tutorials nor some posts of about what are those and some silly unrealistic examples on "City building" or "Car manufacturing", so if here is anyone who can show me path they went and think it's worth shearing to refine coding skills, i am not looking for easy one, i am looking for good one. And yeah googling gives me some results, but i wanted to ask here too just for more opportunity to find something cool.
P.S. i am working in a company where i am only unity developer and before this i was upwork developer, so i never ahd opportunity to work on someone else's good constructed arcitecture.
I don't believe anyone will be willing to hold your hand through the process but here's some practical designs to be understood and principles to follow by:
https://refactoring.guru/design-patterns/csharp
https://www.dotnettricks.com/learn/designpatterns/solid-design-principles-explained-using-csharp
Theses are simply tools to be considered and aren't necessary to game development. You may never use any of the above but they are things to consider. Otherwise, focus more on productivity and less on perfection. Good habits are only useful if you use them; including when to know that excessive overhead design isn't necessary - small projects (embrace the primitive designs as sometimes they're the most appropriate solutions).
I haven't asked my hand to be held through process, I'm just looking for direction and your suggestion was great ty ❤️
Hey, I have a class DeckCase which has a property:
List<GameObject>allDecks;
and each Deck GameObject inside this list has its own property list:
List<GameObject>cardList;
I want to save in the local storage the deckcase/allDecks with a button click and load them on load of the app.
Any suggestions cause every tutorial seems a little rushed.
Hey, can anyone help in API Key security while sharing game? Like suppose I use an API key to integrate weather in my games. If I set its value from inspector won't anyone get it by finding my source files? How can I secure this?
You can use PlayerPrefs for less sized saves and text or binary compression for bigger ones. I think this video is great https://youtu.be/XOjd_qU2Ido
Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.
● Easy Save: https://bit.ly/2BzgdXb
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
·····················································...
Does it contain Save for objects I thought it was only for int/string etc
let me check
thanks
any UniTask users - i'm considering using them and wondering if i can convert something using Coroutines into UniTasks by just replacing the StartCoroutine call with some UniTask equivalent and leave the IEnumerators and yielding etc. down the line as-is and get identical behaviour? and no significant relative performance loss to the more idiomatic UniTask code with async/await
because i'm in a situation where i'd like to keep working with Coroutines because i know them and they're already in a bunch of places, and then just do a refactor afterwards if performance is ever actually an issue ... but just replacing StartCoroutine calls vs. having to go actually through all the return types and yielding etc. are very different prospects
Idk if UniTask has an api that does that for you but it sounds like there's no point in doing that
If you want to start adopting it then you should write all new things in tasks and when you change old things, take a bit of extra time to rewrite them as well
hm yeah i guess
This is possible via UniTaskVoid which is a non-awaited task that does not report back, just like coroutines. UniTask also has several converter methods to await/wrap coroutines and a few other async idioms which makes it easy to incrementally replace coroutines in a codebase or use them together.
don't use that tutorial. binary formatter is found to be insecure and shouldn't be used for anything. consider using json instead
Above is a good advice, you can look upto json saving process, although I have confusion whether it's good for storing large data @somber swift
idn't call it bad but not the greatest. protocul buffer or binarywriter could be faster and more memory efficient tho
HI I am trying to add IK to my game but I have some problems. Can someone help?
Is it possible to somehow serialize scriptableobjects attributes?
the public SO_Item itemInformation is my scriptableobject.
Now the thing is, depending on the item it has different attributes due to inherits.
Like a weapon will have different attributes than a normal item.
is it possible to serialize that?
hi devs, any one experiences the raycast hit point is off like this ? I have no clue, I do not modify the hit point, just draw Gizmos. The yellow lines are ray cast down.
the blue and green ball are raycast hit points, which is off by the side for some reason.
public void Update(Animator animator, int mask)
{
if (Physics.Raycast(new Ray(rayOrigin + Vector3.up * rayFromAbove, Vector3.down), out RaycastHit hit, groundDetectRange + rayFromAbove, mask))
{
mIKData.IKPosition = hit.point + (footTr.position - rayOrigin);
var forward = Vector3.ProjectOnPlane(animator.transform.forward, hit.normal);
_IKData.IKRotation = Quaternion.LookRotation(forward, hit.normal) * Quaternion.Euler(footRotationOffset);
_IKData.SetData(animator);
groundDetected = true;
hitPoint = hit.point;
hitNormal = hit.normal;
return;
}
groundDetected = false;
}
this is the code block to cast ray, as you can see I don't do anything to modify the ray cast hit value.
can you show where you're drawing the lines?
public void DrawGizmos(Color col)
{
if (!rayCastHelper) return;
Gizmos.color = Color.yellow;
//line from above cast down
Gizmos.DrawLine(rayOrigin + Vector3.up * rayFromAbove, rayOrigin + Vector3.down * (groundDetectRange + rayFromAbove));
Gizmos.color = col;
Gizmos.DrawLine(rayOrigin, groundDetected ? hitPoint: rayOrigin + Vector3.down * groundDetectRange);
if (groundDetected)
{
if (shouldLowerBody) Gizmos.color = Color.red;
Gizmos.DrawWireSphere(hitPoint, 0.01f);
Gizmos.color = Color.cyan;
Gizmos.DrawLine(hitPoint, hitPoint + hitNormal*0.3f);
}
}
nothing fancy in the gizmos code too, I just snatch that hitPoint cached above and draw
is there any chance you're messing with https://docs.unity3d.com/ScriptReference/Gizmos-matrix.html in any other code?
I do not play with matrix.
damn coding with "simple" foot snapping to ground give me load of headache 
new Ray(rayOrigin + Vector3.up * rayFromAbove, Vector3.down)
is this the correct ray you want to raycast?
have you tried checking that?
the ray is correct, since it is debug as yellow rays you can see in the image attachment. but the ray cast hit points are off to the side
the rays are cast direct through middle of the foot ( correct here )
rayFromAbove looks close to (0,0,1)
assuming rayOrigin is 0,0,0 adding the directional vector to it makes the origin as 0,0,1 which is what you're seeing as offset in the forward direction
my character looking like a goat lol
Is this being called from the normal DrawGizmos?
yes
Like I'm just wondering if somehow you're drawing the hitpoint from a different frame or something
the gizmos code are called from the OnGizmosSelected, and the Update code is called OnAnimatorIK. hmm I should try to put it to late update and testing out
You can try with Debug.DrawLine intermingled with your actual raycast code to rule it out
my code now work okay although the hit points are off for some reason, the feets is place corrected which is surprising since the hitpoints are off. Only problem left is how to make it offset up the environment. The foot placed on the flat ground is correct, but on the ledge with rotation involved still make the feet looks sinking into the ground.
is your goal to make a nicely animated character for walking around?
I think I should let It be in this state for now since as an indie dev I don't have much time to perfect this.
my goal is just a ground snapping system for foot.
As the tutorial shown here
https://www.youtube.com/watch?v=rGB1ipH6DrM
but in the tutorial he doesn't test it with a cliff like I'm testing so he didn't encounter the problems I got 😆
JOIN THE DISCORD SERVER!
ABOUT THE VIDEO
It's another Quick Bits video! In this one we're going over how to achieve a more natural, realistic looking foot placement for your humanoid model's tootsies. No more feet hovering just abov...
the highest quality thing you can do as an indie dev is https://forum.unity.com/threads/released-motion-matching-for-unity-advanced-character-animation.685489/
which has things like placing feet "for free"
Is there a way to turn this series of if statements into something like a switch? This feels hacky. SkillData.tags is a HashSet. ```
if (skillData.tags.Contains(SkillTag.CON))
{
stats[Stat.CON] += 1;
}
if (skillData.tags.Contains(SkillTag.AGI))
{
stats[Stat.AGI] += 1;
}
you can literate through all the tags
the problem is that there's no mapping between skilltag and stat
you can make one in line with tuples
foreach (var (skill, stat) in
new[] {(SkillTag.CON, Stat.CON),
(SkillTag.AGI, Stat.AGI)} {
stats[stat] += 1;
}
@severe grove
probably better to just make something like that static or something...
Hmmmm. I don't know that it is worth creating a new structure for readability. :/
Linq has a .Intersect which you can check the size of the result
I'll take a look.
foreach (var skillTag in skillData.tags)
{
switch (skillTag)
{
case SkillTag.CON: stats[Stat.CON]++; break;
case SkillTag.AGI: stats[Stat.AGI]++; break;
}
}
WTF why a switch
?
Just stats[skillTag]++
SkillTag and Stat are different things?
not my dicision ¯_(ツ)_/¯
Thank you very much. this is more like what I was wanting.
i agree with the mapping thing, or even just lining them up in the enums
so you can just do stat[SkillTag.CON]++
private static Dictionary<SkillTag, Stat> = new()
{
{ SkillTag.CON, Stat.CON },
{ SkillTag.AGI, Stat.AGI },
};
i do wonder though
Alrighty. I don't think this is too far along to match up enum values.
lol i guess you could do
foreach (var skillTag in skillData.tags)
{
var stat = (Stat)Enum.Parse(typeof(Stat), skillTag.ToString());
stats[stat]++;
}
I have put all character stats into a big dictionary on a character called Stats with an enum of Stat. This is so that I can easily pass the enum to other functions and they can modify those stats. I.E. Buffs ect.
probably dogshit for performance though
Skill tag contains data like passive, toggle, single target, aoe, and it's primary modifying stat value. I am experimenting with increasing base stats based on skills chosen and not from allocating stat points.
im currently workin on the VR interactive elements of the project im working on, as far as i understand the XR unity plugin dont really help much if we are doing more than picking things up, selecting or selecting things on UI. did i miss something or is there a way to use the UnityEngine.XR.interaction namespace?
Hi, i made my bot a child and gave it a trigger collider. Now when i tell it to stay in position(Horizontally) it keeps rotating with the player even though i made a script to backwards calculate the rotation from the player to stay in the horizontal position. When i start the game and the bot starts moving in his direction the collider rotates with him but as soon as I rotate the Child with the collider on it changes its position to the calculated one. So that means as soon as i change the rotation it starts doing what the crpit says cs void FixedUpdate(){ //Damit sich die Hitbox für den Enemy detect nicht dumm bewegt. Quaternion norotation = new Quaternion(0f,0f,Bot.transform.rotation.z - transform.rotation.z,0f); transform.rotation = norotation; transform.position = Bot.transform.position; }
even though i made a script to backwards calculate the rotation from the player to stay in the horizontal position
Yeah don't do this it's a nightmare
Just use https://docs.unity3d.com/Manual/class-ParentConstraint.html and freeze/constrain the rotation axes
instead of parenting
I have a dialog box that's got a number of states that display different gameobjects. Typically, I've managed this by putting all the elements relevant to one state in a container gameobject and then turning that one on/off as necessary. The problem is that I have a few gameobjects that have multiple appearances through the states. I didn't want to get into the granular turning each and every game object on/off depending on the state of the dialog box, but the dialog box is starting to have enough elements that managing which ones are duplicated and need some detail set is a bit much.
Anyone have any thoughts?
Here's some mocks so you can see what I'm talking about - something like the mission description appears in multiple states (step 1 and step 2, shown) but is in different locations in each.
this looks really nice
thanks.. i'd like to take credit, but it's the wireframes 🙂
I mean, mine's close, but there's obviously some differences
i use the ScreenManager from the Material UI toolkit for toggling
it sounds fine to me
so it goes with UI
also looks really good
it's just getting pretty tedious to get through the heirarchy and remember all the components that need to be turned on/off for each state
i like the portrait mode angle a lot
if UIElements were more mature when you started this
would have been a good fit
UI games are tedious to make in unity
yeah, I'm finding that
you could try
the layout groups are mostly good, but it's .. really fiddly
hm, i'll have a look
it won't help
it'll just make you sad
using prefabs instead of components... what can you do
UIElements has Components with a capital C
i don't recall if they did a proper React diffing tree
or whatever
never touched it
if you look at 0:22 sec in that video - just getting that "triangle" to line up with the currently selected item was a pain
since the layout group doesn't update until "sometime later"
so when I add the buttons to the layout group, the x position is 0.0f until a frame or two later.. so i don't know where to align the triangle until then
so i had to do a little magic deferred position setting
@undone coral : this? https://pub.dev/packages/flutter_unity_widget
hi guys... i have quit a problem right here...
I'm making a game like simCity buildit where you can build your road, then the AI will move on said road.
The problem i'm encountering is that... i don't know how to make the AI check if the road can be walked on
since the player is building it (therefore i can't just use a Vector3.lerp)
oh and also: for the road building tool i have two types of road: the straight one and the "angle" one.
You probably don't want to add it to your AI's pathfinding until the road is complete, then, that seems straightforward enough..?
yeah.
U wanted to let players build the road first, then simulate.
btw, the one i'm making is 2D and grid based
the game, i mean
I guess I'm not really sure what your question is.. If it's a 2d grid based game, then you'll want a matrix or data structure to hold finished pieces of road and then write a pathfinding algorithm to identify the path for your AI to take. Once you've got that, then you feed that path into the AI agent and have him move to the closest road entry/exit point (in worldspace) based on what grid he's supposed to go to next. Constantly refresh your pathfinding matrix while having your AI travel around.
Not simple, but shouldn't be too hard conceptually. Lot of details to work out, for sure.
Hey so I'm just curious, what are the actual benefits of applying principal of least privilege in unity? Like public vs [SerializeField] private both expose a variable on a script for parameters. Not to mention across tons of tutorials it feels like its applied randomly, some tutorials seem to have no idea the private modifier even exists and others are like incredibly formal. What are the actual benefits of both workflows in this engine?
for a single developer it matters little. when you work with other people, [SerializeField] private ... is a way to expose to the editor something that should be internal to that script and not meant to be read by code elsewhere. privileges are really like documentation, after all anyone can always change the source to whatever they need
Got it, thanks for the insight!
you're right. Maybe i can get that working by finding the starting position of the road and, since it is a 2d game, shooting a ray in 4 directions checking for other "roads". If i find any other road i keep doing that until i reach the end of the road
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
DriveInfo dInfo = new DriveInfo(driveLetter);
long freespace = dInfo.AvailableFreeSpace;
int freevalue = (int)freespace;
diskLoc.text = "Free: " + freevalue + " Drive: " + driveLetter;
``` Anyone spot what might be wrong with this? the output is a long negative number, and D:\
To add to what the illustrious doc said - having the protection level as tight as possible prevents you from accidentally or otherwise doing things you're not supposed to later on down the line.
Example - I have a data structure that has two dictionaries internally, but externally it "looks" like a single data structure (one of the dictionaries is a cache). By keeping the internal ones private, whenever I come back to the code and want to use the dictionary, I just can't because I haven't made any access to it internally.
Obviously that's not a Unity specific thing - but the same principle applies. I like to make my UI elements in unity completely separate from the business logic singletons/managers - the UI elements (screens, dialogs, panels, icons, whatever) only care about their UI - they get the data from elsewhere, and that data should be tightly controlled so the UI doesn't accidentally muck with data it's not supposed to.
what do you think casting a long to an int does?
heh heh heh
unless you know what 0x5f3759df is, you probably ought to not be downcasting your data types
I got that conversion idea from windows docs.. So I suppose they are wrong
i mean it works, so long as your hard drives have less than uh.. (where's my calculator) 2 gb free?
just change it to
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
DriveInfo dInfo = new DriveInfo(driveLetter);
long freespace = dInfo.AvailableFreeSpace;
diskLoc.text = "Free: " + freespace + " Drive: " + driveLetter;
and it should work
and use implicity type, what's going on in this discord lol
everyone is so insistent on using explicit declaration
I sorta hate var but I'm a relic 😛
auto 
Thanks. I was only trying to convert it to use in a if statement comparison
and you can
it's a numeric type, you can compare it to anything
any other numeric type
Ill use a different drive then xd
i hate it
🤷♂️ 🙂
meanwhile in my code
~230 occurences in my one project of 6.5k lines
When suitable nowadays I tend to use a blank new instead of var, but often that isn't relevant
yeah it doesn't really help much. it's technically less characters, but i prefer lining up the declarations on the left
I don't often type that stuff anyway
tab-tab-tab-tab-tab is pretty much how i code
declare the content, get rider to autocomplete the declaration
the autocomplete AI stuff in the IDEs is getting pretty stinkin amazing
AI/ML, whatever you want to call it
literally type "M" and it's ... pretty good
pretty much what I do all the time
do you guys have any tips on debugging errors that only occur in the build and not in the editor?
Depends what kind of error they are. Getting deep with the debugger is usually the solution for code problems.
it's a nullReferenceException 😭
probably reduce the number of .'s on a line
some (stupid, imho) rule is that you should only dereference once per line so you know where your NREs are, exactly
is this a reply to me
🤷 use the debugger and you don't need to do that
yup
can I debug the build?
I know I can see the player log but it's not super useful
Yes, if you build it as a development build you can connect the debugger to it
OHh developement build I completely forgot that existed
If it happens immediately on startup you can even make it wait for you to connect a debugger before continuing
Ok wait so is connecting a debugger the same as attaching to unity basically?
If you mean that button in your IDE, yes
This playlist is pretty comprehensive https://www.youtube.com/playlist?list=PLReL099Y5nRdW8KEd59B5KkGeqWFao34n though aimed at a beginner style
welp having the debugger wasn't very useful
or at least the console
WindowsPlayer(SONY-SIJ4392380-5) NullReferenceException: Object reference not set to an instance of an object at Interaction.CoreComponent.OnPickUp () [0x00001] in B:\Unity Projects\Store\Assets\Scripts\Interaction\CoreComponent.cs:250
I have the error line, but that's the only useful information I've gained, and I already knew where the error was because the method is only one line long
The debugger is not a log, it's breakpoints and stepping over code
ok so this confirmed my suspicion that my itemSlot was null.. but I'm not sure why it would be null in build and not in game
the component isn't created at runtime or anything
You should provide some more context then if it's just a serialized component. If it's being created or found at runtime you can use the debugger to step over the code that's doing that and see what's different.
it was a combination of two factors:
itemSlot was private and not serialized with serializefield
and it was being gotten OnValidate
OnValidate is editor-only, so it makes sense that that would not hold up. You need to serialize things for them to persist to a build.
I've never used this method of getting components before and I never even considered that maybe OnValidate doesn't get run in builds
so I guess I will just continue with getting components in awake instead
I personally barely if ever use OnValidate. I serialize components and assign them in Reset, which is run when components are added or reset in the editor. That way components are set up when first used, and can be modified afterwards.
I don't assign anything in Awake or Start unless it's runtime-only to avoid overhead during initialisation
well it does a quick check to see if itemSlot is null or not, it won't try to get a component if its already filled
im not sure how fast that is though
i kind of needed it to check if it was null because getting a component on validate every time would be extremely slow
Checking Unity objects for null is cheap, but expensive relative to other operations like checking normal objects for null
I should be able to serialize my itemSlot and keep the onvalidate code
the reason I didn't serialize it is because theres no reason for it to be visible in the inspector
for hiding it in the inspector you can use this
https://docs.unity3d.com/ScriptReference/HideInInspector.html
I would advise against hiding serialized values in the inspector. It tends to just cause more trouble than it's worth. I might suggest using a [ReadOnly] property drawer (there are plenty out there), I also have an [EditorOnly] one to stop people fiddling with values at runtime.
Then it wouldn't be serialized, which is the entire problem
I mark the class as serializable to I can use JsonUtility on it, but the data can be around 60mb fully generated, so I hide it in the inspector
Or atleast mark it as private so it doesn't show
I think we're confusing the ambiguity of "serialize"
I don't think bringing a very specific scenario where it is practically required to hide it relates to my general advice given in relation to a solution to a normal problem
Right, hence the confusion. Sorry.
i have odin inspector which includes a readonly attribute
I think that should work the same as those free ones
Can you have a script connected to a scene?
add it to a gameobject.
Say I have a TitleManager (for a title screen), where would I put this?
@raw schooner You can add a script to a gameObject inside of a canvas if that's what you mean or a panel, for a title screen?
oh TileManager
empty gameobject
Hi guys i have a very weird problem about my code. The code it self is pretty simple the enemy take dmg base on an int of dmg amount e based on the type ( a string parameter) of dmg there is a scaling of the dmg. When I call the methods in the update based on an input this dmg isnt applied. i tried using a debug.log i the message get printed so the method get called. I tested more and i found that if i the string parameter is null the dmg is applied, I have no idea what's wrong.
Post the code to #💻┃code-beginner
I’m trying to get the min and max points on the bounds of a collider while accounting for rotation, this is what I found:
I used the mathematical equation for circles, where r^2 = x^2 + y^2, where I get the radius first using collider size.x and y, then reapply into the equation again, by assigning x = collider.bounds.min.x, and r = radius found, and finally I can get the y value where the point is having min x on collider.
Which led me to making this:
//r^2 = x^2 + y^2
float radius = Mathf.Sqrt(Mathf.Pow(col.bounds.size.x, 2) + Mathf.Pow(col.bounds.size.y, 2));
min.y = Mathf.Sqrt(Mathf.Pow(min.x, 2) - Mathf.Pow(radius, 2));
min.x = Mathf.Sqrt(Mathf.Pow(min.y, 2) - Mathf.Pow(radius, 2));
min = transform.parent.InverseTransformPoint(min);
max.y = Mathf.Sqrt(Mathf.Pow(max.x, 2) - Mathf.Pow(radius, 2));
max.x = Mathf.Sqrt(Mathf.Pow(max.y, 2) - Mathf.Pow(radius, 2));
max = transform.parent.InverseTransformPoint(max);```
It doesn’t work though and I’m having trouble understanding the instructions, can anyone help me?
This is the formula Im trying to use:
// r^2 = x^2 + y^2
// r = root(x^2 + y^2)
// y = root(x^2 - r^2)
// x = root(y^2 - r^2)```
And heres the website I found the "solution" on
https://answers.unity.com/questions/1439812/bounds-getting-y-value-of-the-point-where-its-on-t.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Heres what Im currently getting rounded to 2 decimals:
col.bounds.size.x = 1.76
col.transform.rotation = (0.2, -0.1, -0.1, 1.0)
radius = 2.55
What Im getting for min = (12.7, 6.5, -52.3)
What I should be getting = (-0.75,-0.25,-1)
Of course if anyone has any other better way to get the max and min points of a rotated collider please tell me
It is a box collider so is there a way I can just find the corners or something?
Could I get the bounds points and rotate them to the right positions manually?
Ok using mesh.bounds seems to be working but it is very slightly off, are meshes slightly larger than they seem?
min is slightly below on all axis, max is closer but also slightly below
I'm guessing you want aabb of collider?
aren't there helper methods for that?
Collider.bounds
I cant use collider.bounds because it doesnt account for rotation but Im getting very close with this
//Get closest point to collider
Vector3 colPos = col.transform.position;
Quaternion colRot = col.transform.rotation;
Vector3 closestPoint = Physics.ClosestPoint(transform.position, col, colPos, colRot);
closestPoint = transform.parent.InverseTransformPoint(closestPoint);
//Get max and min of bounds
Vector3 min = col.GetComponent<MeshFilter>().mesh.bounds.min;
min = col.transform.TransformPoint(min);
min = transform.parent.InverseTransformPoint(min);
Vector3 max = col.GetComponent<MeshFilter>().mesh.bounds.max;
max = col.transform.TransformPoint(max);
max = transform.parent.InverseTransformPoint(max);
Debug.Log(max);
//Find if collider is in direction player is trying to move
bool minIsGreater = min[axis] >= transform.localPosition[axis] && _input[axis] == 1;
bool maxIsLess = max[axis] <= transform.localPosition[axis] && _input[axis] == -1;
if (minIsGreater || maxIsLess)
{
//Move player up to collider
newPos_Local[axis] = closestPoint[axis] - transform.localScale.x * 0.5f * _input[axis];
}
else
{
//Move player normally
newPos_Local[axis] = possiblePos_Local[axis];
}```
Heres what I have so far, it almost works but somethings off
are in world space
while mesh is local space
oh wait, my bad
renderer bounds
world space
mesh - local
Yeah so I have to convert local to world and then back to the players local
Its probably not great to be calling GetComponent every frame so Ill have to find a workaround for that later
GetComponent without caching is a red flag when hiring programmers kek
It works almost perfectly when the player is to the right of a collider albeit for some small jittering but the player goes right through the collider from other angles
Actually above works fine as well so the problem is obviously with this:
bool minIsGreater = min[axis] >= transform.localPosition[axis] && _input[axis] == 1;```
Im trying to check if the min point is greater than the players center from each angle while they are trying to move up/right in those directions
Im doing the exact same thing with max but instead checking if it is less than so I dont see any problem
[axis] just means either .x or .y, Im running them separately in a for loop
_input is just the arrow keys/ WASD
Basically I dont want to stop/push back the player from a collider unless they are moving in that direction
Ok actually its even weirder than I thought, from below it half works and is just really jittery but from the left you just walk right through it
Oh god its so much worse, when I start rotating the cube it stops working altogether
Im going to die trying to get this to work
Im gonna save the code and undo like 5 hours of work, this isnt happening
I really think you overcomplicate it
i'm gonna ask the same thing here, since it is quite an advanced thing (i guess)
i'm making a game where you have to connect two points by placing "wires" on a grid.
the problem is that i have no idea how to check if the path is right. I can check if the starting wire is there and the ending one, but i can't go any further.
I tried with Physics2D.CircleCast, i tried with Physics2D.RayCast... nothing seems to work.
I can even link the code that i used, but i think the problem isn't the code, it is the way i'm trying to fix this problem.
I'm fairly certain you can get world space AABB without manual calculation
what exactly are you trying to check in path?
if the start point and the end point are linked together by
wait i'm gonna link a phto
this is what the game looks like:
the start and the end are connected
i have to check that the wire looks like this, and that the player isn't leaving spaces in the wire.
based on how you implemented the tiling system, and how the circlea are placed, it should be fairly easy with linked list
you mean... by using an array?
if your nodes are stored in a world matrix, you can start traversing from the first element.
The complexity of this will increase if there ever comes a path with 2 new paths
Linked lists arent arrays. Just classes which reference next classes (also previous classes if its a double linked list)
can you elaborate what are you trying to check?
I really don't get what you are trying to do
okay.
Ok back to basics
This code is in FixedUpdate()
It takes in the players input for each X and Y axis
It finds what local position it would put them in
It places an overlap box on that position with the exact scale and rotation of the player
If there is no collisions then it moves the player to the new position
If there is collisions then it tries to move the player right up to the collider (Ignore this for now)
Problem is that overlap box seems to failing sometimes
Because of this the player can end up slightly in a collider
Then when they try to move in an adjacent direction they get sent flying
Anyone see anything wrong with this?
//Find where player could be based on movement
Vector3 possiblePos_Local = transform.localPosition;
possiblePos_Local[axis] += _input[axis] * _speed;
//Convert to world position
Vector3 possiblePos_World = transform.parent.TransformPoint(possiblePos_Local);
//Find all colliders in position
Collider[] possibleCollisions = Physics.OverlapBox(possiblePos_World, _halfSize_World, transform.rotation, _colLayer);```
One possible solution would be to store the "tiles" in a 2d array. So each item in the array is either a circle or empty. Now pretend you have a unit moving from start to finish tiles. It can move either vertically or horizontally, one tile at a time, in the direction of the finish tile. If it is able to reach it before it cannot move anymore then there is a valid path.
this is an example of what the player should not be able to do, i need to check that the whole path is linked together and has no "flaws"
oooh
i already have implemented something like that, i'm gonna try that out. thanks
that is actually quite complex system to do, as far as I know
potentially you might want to do simple pathfinding implementation I think
This is easier than using raycasts etc.
since there's only 3 direction to go to
it's simple as
for (i=0; i< 3; i++) {if (tile[i] is green) moveCheckTo(tile[i])}
Kind of like this
and i can store them to an array...
i'll try that out and I'll make you know
thanks!
My simple pathfinding is flawed. If the line of circles can turn away from the finish point you will need something more advanced.
Look at flood fill. I often use it for simple 2d pathfinding.
Should I try using 2 or more overlap boxes at the same time to make sure it gets it?
I finally fixed it, turns out making the colliders flat on the z axis was a bad idea, why didnt I think of that earlier
Oh well moving on
Hello,
For the past few months, I've been developing a procedural chunk-generation system. Think of it like other voxel games: as you walk around the chunks are generated and removed constantly. Though the generation is relatively fast, the framerate of rendering it is not. I've tried multiple items: Making a chunk share materials between blocks, making chunks share materials across ALL rendered chunks, removing any vertices within the mesh that you can't see, reducing texture size by only the single texture the block appears as, etc., etc. What should be my next form of approach? Let me know any questions you may need answered. Thanks.
Are they individual cubes or merged?
Hey there, i am having bizare issue with performance of my game on android.
I released a game for fun long time ago in mid 2019, uploaded to playstore and was happy and moved on.
Now i got a new phone(one plus 9 pro) and noticed a bug, decided why not fix and publish update?
I never formated my pc/cleaned since 2019 so i still have unity installed, the project and everything.
I fixed the bug and made a build, all good but the performance is halved.
Extremely weird as the only fix i did is change scale of ui canvas and changed some text.
I start debugging by removing game objects step by step, trying without shadows, trying without light, trying without scripts. nothing helps, ofcourse when i remove shadows/light etc it does run better but still worse than my version on playstore with everything on.
I tried going quality/player settings and unticking/ticking random things step by step but nothing works, fps is just halved.
I also changed the most important thing( i thought) the Target API, to my newer android version, but didnt help.
Its like my 2 year code decayed or something i am so confused.
And now i am in bigger problems, the game wont even start, just crashes.(after i ticked something, and then unticked back, its still dead)
I tried build again pretty much empty scene and it still crashes. its just dead
cursed project i am so confused
Is anyone here familiar with compute shaders?
Im getting an error: Kernel index (0) is out of range
Im copying somones code to try and make boids, this is one of the lines giving an error:
compute.SetBuffer(0, "boids", boidBuffer);```
are you using the same unity version you built the project 2 years ago?
your best bet is to profile the game in your old unity version in which you published the game, and the new one
You need to get the kernel ID with https://docs.unity3d.com/ScriptReference/ComputeShader.FindKernel.html then use that instead of 0
your unity version probably updated. do you use source control?
Anyone knows of a script or an asset that allows to export the gameobjects on scene as an FBX at runtime including the character rigs and skinned mesh renderers?
I know the FBX exporter does this but it only works inside the unity editor and not on a compiled project.
I know this is possible because otherwise software like Vroid wouln't exist, which is made in Unity. But after searching on the internet I haven't been able to find a script or asset for this, even thought I saw many people asking for such thing on forums.
Start() :
the size of my rectTransform (height) is 700 when i debug it, which is correct.
then i run an if statement where i use that value and debug again and it shows as 0
run a Vector3 assignment in which i use the value, it changes again to 300
Update () :
constantly outputting 700
You can use the Autodesk FBX SDK
@undone coral @tough tulip hey, thanks for response. i found the issue 😄
The game stopped crashing for no reason, dont know why but fps issue remained but then i fixed it.
i indeed updated unity(thinking it will solve issue , updated from 2019 to 2021) but the problem was that i had post proccesing profile on camera, disabling it doesnt help as i noticed it turns it self on when game running.
so i removed it( i guess before when i deployed game i did the same, and readded for pc version 🤦♂️ )
that solve 90% of performance, post proccessing is very bad on mobile.
Then i found a couple things in code regarding settings that was force setting PC things.
fixing all of it i got butter smooth 60 fps(25 before).
Lesson for my self: add a damn readme
Thanks
Interesting, I don't know if that would only work with rigs made in Maya tho
Hey All, I am trying to read and write to json in unity. part of the data I am saving is SOs, which according to the api, are supported. It works in editor but in build it fail. Here is what the json looks like in editor vs build
"barrelsStored":[{"instanceID":52458},{"instanceID":52458}],
"barrelsStored":[{"m_FileID":0,"m_PathID":0},{"m_FileID":0,"m_PathID":0}],
version 2021.1 btw
bool[,] tiles = new bool[5,5]; is perfectly valid... anyone have a serialization tip on this one?
Has anyone used this [https://github.com/yasirkula/UnityNativeFilePicker] or a similar library to interface with native Android functionality like file selection? Just curious if anyone has any libraries for this that they've found useful or would recommend.
Are you creating those IDs manually or are you having them set from the instance IDs unity generates? Looks like that kind of info isn't available in a build. I would manually assign IDs you create yourself, perhaps with something like https://github.com/moonpyk/ncuid
Collision-resistant ids for .NET (port of https://github.com/dilvie/cuid) - GitHub - moonpyk/ncuid: Collision-resistant ids for .NET (port of https://github.com/dilvie/cuid)
No idea if this is the right place, but does anyone have a nice tutorial on how to create 3D drawing with either line renderers or, preferably, meshes?
Not a tutorial but this tool might be what you need https://acegikmo.com/shapes/
Shapes - a real-time vector graphics library for Unity
That looks really cool, but a bit overkill for my usecase. I just want to be able to recreate a tilt brush mechanic
Just use Mesh class https://docs.unity3d.com/Manual/mesh.html
Yeah, I was looking into the doc already, trying to figure out how to create line meshes in runtime. Whether I need / can use a line renderer and somehow transfer its points to a mesh 😄
https://docs.unity3d.com/Manual/AnatomyofaMesh.html
here read about** topology**
set line topology and you can draw lines
What about vertex data? Set everything to the same color?
But this looks more promising, thanks for the hint
Should be able to create a mesh like I would draw a line like that.
I'm wondering what the performance difference would be
line renderer vs mesh
Why doesn't Rider show decompiled code for .NET base class libraries (e.g. standard List, Regex, etc) when using Unity 2021, but it works in 2020? The newer version says the assembly location is somewhere within the Unity editor installation folder and is named netstandard.dll while the older version says its using System.dll of the NetFramework64 directory in my Windows folder. Is something just weird and broken on my system or is there something I request Unity fix/implement here? Not sure how this actually works. As far as I understand, the DLLs just live somewhere and Rider decompiles the IL code, but the newer DLLs only show the method signatures without their content or everything is replaced with "throw" instead of the actual method content. I've never heard of any sort of security/obfuscation feature that would protect .NET assemblies in this way. Also no reason, because the BCL code is open source hosted online anyway, I just like to check things quickly in my IDE.
it only shows the function namy only for mee too
From 2021 on forward unity uses .net standard 2.1 and not net framework anymore.
but there is the IL code "link" that opens the IL viewer witht he code in it
But why wouldn't I be able to decompile net standard? It's just a DLL or is there some magic going on?
Net standard is only a stub
Do you know where the real code is coming from? There's probably a way for Rider to retrieve it, but the question for me is whether that's a missing Rider feature or Unity thing.
Neither. .net standard defines the stub. There should be the remappings in the file somewhere. But I don't know from memory. Just easily look up the code online. It's open source afterall
Thanks!
that's interesting - didn't know that about 2021+.
why can't I call a protected interface method from the class implementing said interface?
All methods in interfaces must be public. You can make there implementation protected
you have outdated knowledge
It's true in Unity
Maybe you C# version is less then 8.0
does anyone know how to set up obi cloth particle filters?
I'm struggling a bit with getting them working.
Does anyone know anything about the new input manager? My problem is that, (World > Battle > World <= Gameplay Loop) When I load from Battle to World, The first time I press/Hold the move button, everything works EXCEPT, that the value that comes out is 0.0
If i release and press again, it works fine. Anyone know what the problem is??
as a start, you should use the event workflow instead of whatever you are doing.
??
You implemented the method explicitly, so the method is both considered private not only to external consumers of the class, but within the class itself. You need to cast this to the interface type in order to call NetworkTick
((INetworkable)this).NetworkTick()
hey, i want to loop through all materials of the children of an objects and add each one to a material list but only if it isnt already present. this is my code:
for (int i = 0; i < parent.transform.childCount; i++)
{
current = parent.transform.GetChild(i).GetComponent<MeshRenderer>().material;
if(!loppedMats.Contains(current))
loppedMats.Add(current);
}
//current is declared 'Material current;' loppedMats 'List<Material> loppedMats;'
but it adds all materials to the list, even duplicates, why?
Do you want to prevent duplicate shaders or duplicate materials?
Also .material will return Instantiate(sharedMaterial)
So Contains will always return false there
yeah it's technically a different material according to unity
The .material property is probably one of the worst API design mistakes that Unity is still stuck with
Same for all of the other awful properties that just do hidden instantiations
yeah
what's even worse is that they don't get GCd
so using .material or any of those other ones results in memory leaks
unless you handle it properly
I want to not include duplicated materials.
How would the correct approach be?
Thank you.
Btw, I found a solution to my problem. I ended up using only LineRenderers for 3D Drawings, but needed the mesh of it to detect collisions, for example when wanting to delete them. Did some more research and - no idea why I didn't find this the first time I looked it up - there is actually already a function on the LineRenderer class that creates a mesh out of it. Works exactly how it should 🙂
https://docs.unity3d.com/ScriptReference/LineRenderer.BakeMesh.html
Imo there are use cases for .material, if you create a pen and want to dynamically change its color, it's better to instantiate a material with different color for a line than changing the sharedMaterial, which would also change the color of every other drawn line
If you want to do that, then you should use MaterialPropertyBlock, not material
MaterialPropertyBlock is used by Graphics.DrawMesh and Renderer.SetPropertyBlock. Use it in situations where you want to draw multiple objects with the same material, but slightly different properties. For example, if you want to slightly change the color of each mesh drawn. Changing the render state is not supported.
There is almost no valid reason to use .material
There is a better way 99.9% of the time
Damn that's neat, didn't know about that before!
Does it change the number of draw calls for objects with same material but different material property block?
It depends on which properties you change
If the property is instanced (such as _Color), then it shouldn't affect draw calls
Sweet
It's a very useful API, shame it's not more well-known
That goes for a lot of stuff in Unity, really
I have the feeling the reason for that is that it's newer and from what I'm hearing, a lot of people are stuck with 2018 versions or below 😄
Fair point lol
Though MaterialPropertyBlock was introduced in Unity 5.2, so I dunno if I'd still call it new
I think the problem is more that a lot of people don't know why material is bad, so MaterialPropertyBlock doesn't get brought up much
I wonder what the adoption rate is for the new MeshData API
It's so much better than the old array properties on Mesh, but it was introduced in like... 2020.1? Or somewhere around there
The only downside is that it doesn't have anything exposed for blend shapes currently
Then it'll probably take fairly long haha
I'd be surprised if it happened at all, tbh
How's this work 😦
News to me
It gives you access to the raw vertex buffers, and allows you to define your own layouts for them (to an extent)
You can do multi-threaded manipulation of meshes with it
Oooh so it works with the job system. Awesome
Yep
Probably how MegaFiers 2 is working
Hi guys, when calculating the direction of a projectile, I use the following:
var direction = (new Vector3(targetPosition.x, 0, targetPosition.z) - new Vector3(sourcePosition.x, 0, sourcePosition.z)).normalized;
I'm trying to understand why the following calculation won't give me the same result:
var direction = model.transform.forward;
It seems to work except when the projectile travels from certain directions.
I forgot to show this part:
model.transform.LookAt(GetWorldPosition(targetPosition));
Also, I am not worried about the Y component because that movement is negligible.
What's with the "get world position"?
Are some of these positions in local space?
I think that is the source of my problems! I'll investigate and see.
The source and target coordinates are according to a 2d map where (0, 0) is top left. When I display the models I adjust Z to flip the map vertically.
How would I go about creating mesh info server sided, then passing the info to the client who when creates the actual object?
Probably best to avoid because that's a lot of data. Try to send the minimum info the client needs to make the mesh itself.
Worst case you send the data via rpc but expect it to take some time
Does someone know how to get the angle here? I just want the gun to point at the mouse cursor (Like a twin stick shooter)
Vector3 mousePos = Input.mousePosition;
mousePos.z = Vector3.Distance(_camera.transform.position, transform.parent.position);
Vector3 mousePosWorld = Camera.main.ScreenToWorldPoint(mousePos);
float angle = ???;
_gun.transform.rotation = Quaternion.Euler(0, 0, angle);```
#💻┃code-beginner you should use transform.right = ... for transform.LookAt except in xy 2d
otherwise you can use Mathf.Atan2
Ive tried using Atan2 but its very confusing
what's your objective?
have you looked at the Corgi Engine 2.5D from MoreMountains asset?
what about an array of points?
mesh.vertices = vertices;
mesh.triangles = triangles;
(these 2 fields)
i strongly recommend it 🙂
Ill take a look
basically I am creating a dynamically loaded universe (multiplayer)
planets are loaded using 6 meshes
your art and logical directions are not the same
the art is pointed one way, and your coordinate system is pointed in another
Yes that is the problem, thanks.
#archived-code-general i think maybe don't get ahead of yourself here and try to get something working single player, and don't touch anything multiplayer related for a long time
generally trying to create a mesh directly is a graveyard
why?
How and why is this setting the y rotation to 90?
float angle = Mathf.Atan2(mousePosLocal.y, mousePosLocal.x) * Mathf.Rad2Deg;
_gun.transform.rotation = Quaternion.Euler(0, 0, angle);```
based on your screenshots here, you have a long journey ahead of you
#💻┃code-beginner use transform.right = ???
think about what can go on the right hand side of that statement
lmao I was using transform.right hours ago before I started getting wacky results so Im trying to be more accurate
don't use Scenes
there's just a lot you have to learn is all. try going through a 2d game tutorial or use the asset i recommended
Dont be so passive aggressive
Ignore them. Atan2 returns an angle between two points, in radians.
We convert it to degrees with the Mathf.Rad2Deg constant.
That code is widely used for 2D aim systems.
Right, do you have any idea how its changing the y rotation since Im setting it to 0?
The angle is correct apart from that
Not exactly "points", but two floats that are derived from the direction between two points.
And using that I was also getting a 90° difference. Just add or subtract 90 before feeding it to the Euler call
Not sure if that happens on Y tho
I think when you view euler angles in the frontend it's not guaranteed to be the same as the ones used to set rotation in code?
Yeah that too, the ones displayed in the Inspector are the localEulerAngles
Ah thats it
So localRotation?
So you may have a difference if a parent object is rotated and you assign to .rotation or eulerAngles (the world ones).
If you get such weirdness, or want to locally rotate, use localRotation
Ayo, now its working thanks!
float angle = Mathf.Atan2(mousePosLocal.y, mousePosLocal.x) * Mathf.Rad2Deg;
Quaternion newRot = Quaternion.Euler(0, 0, angle);
_gun.transform.localRotation = newRot;```
If I do that, it says that I need to refer to the method through the implementing class, not the interface
I ended up using a publisher/subscriber pattern
So now all the network components subscribe to the networkcore's networktickevent
Wdym?
Ah, I skimmed over and missed that the interface method is protected
Why do you want to make it protected?
I don't see any benefit in your example
protected interface methods are to allow you to implement functionality on a class that a default interface method can call, to my knowledge
I have it working already, thats why I am stepping up to multiplayer
Because the method is kind of like Update(). Another class shouldn't be able to call it.
In that case an interface is likely not the right approach then, yeah
Best case scenario is networkcore and networkcomponent share a base class and I can implement the method there
Problem is that networkcore is already deriving Singleton
I figured it out, so no worries
However, there is a way to do what you want
It's just not obvious
Give me a moment
public interface INetworkable
{
protected void NetworkTick();
}
public class MyNetworkable : MyNetworkable.INetworkableOwner
{
interface INetworkableOwner : INetworkable
{
void InvokeNetworkTick()
{
NetworkTick();
}
}
public void SomeMethod()
{
((INetworkableOwner)this).InvokeNetworkTick();
}
void INetworkable.NetworkTick()
{
}
}
Of course, you need to be using a version of Unity that supports DIMs
So, Unity 2020.2 or newer
if you already have an event system, it's redundant to imitate unity's component model. i would suggest
void Start() {
NetworkingAware.instance.OnNetworkTickAsObservable()
.Subscribe(tick => ...)
.AddTo(this);
}
class NetworkingAware : MonoBehaviour, INetworkingPublicApi {
public static NetworkingAware instance {
get {
// this should return a dummy instance if
// the stuff needed to run a networked game isn't
// ready yet, which upgrades itself to a real instance
// when networking is ready/present
}
}
}
(I'd recommend looking at the singleton writeup I posted in #archived-unitytips on that note)
yeah this stuff is tricky to make really bullet proof, if you're trying to make a library for other people to use
That particular implementation of a singleton has problems that are hard to solve when they crop up
There are TONS of really bad singleton implementations thrown around for Unity, which is why I did that writeup
It's, so far, the most bulletproof method I've come across
on the flip side, it's okay to throw errors.
Even ensures things are wired up before Awake even runs
it all comes down to what you want your API to be
the appeal of the unity callbacks approach is that, once the user implements your interface, it is truly invisible to the end user the stuff going on underneath
you can look at EventSystem for a pretty good example of using Interfaces for callback-style APIs
there's a lot of crud involved
It's a shame that the actual dispatching code for that API isn't super optimized
yeah... but i don't know if that ever comes up in a profiler in a meaningful way
It allocates on every call, and the design makes it hard to work around the ones you can avoid
i think you should adopt UniTask and UniRx while you're ahead
Seems fine to me, a protected virtual on a base class more accurately describes the design you seemed to be going for earlier
But yes, move to tasks if possible
are you targeting a specific kind of game, like an RTS?
no
everyone says only use async void for "fire and forget" methods
and callbacks
and thats what start is
yes, but even then it's not a good idea
you won't receive the exceptions thrown in them
what would you have me do?
I'm writing it up as we speak
Instead of
async void Start()
{
await stuff;
}
it should be
async void Start()
{
try
{
await StartAsync();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
async Task StartAsync()
{
await stuff;
}
Task is what actually captures the exceptions
WaitUntil() doesn't throw exceptions
async void is unavoidable for the "entry point" method here since the signature is enforced by Unity, but the actual logic should be in a proper Task-returning method
Have you tried using SOs as singletons? I feel like doing that invalidates most of the complexity you're suggesting in that tweet thread.
I'm talking about in general
ok
why do I need this UniTasks thing instead of just using async/await?
I have, but it depends on what you need singletons for. A lot of the problems I have with many singleton implementations apply just as much to SOs
Callbacks are also a bit harder to manage with SOs since it's a bit less clear when they execute
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
private static T? s_instance;
public static T Instance
{
get
{
CheckNullAndCreateInstance(s_instance);
return s_instance;
}
private set => s_instance = value;
}
private static void CheckNullAndCreateInstance([NotNull] T? instance)
{
if(instance == null)
{
instance = Instantiate(new GameObject().AddComponent<T>());
instance.name = $"{typeof(T).Name}";
Debug.LogWarning($"{instance.name} had to be created because there was none. It will have default values.");
}
}
protected virtual void Awake() => SetupSingleton();
private void SetupSingleton()
{
if(s_instance == this)
{
return;
}
else if(s_instance == null)
{
s_instance = (T)this;
}
else
{
Destroy(gameObject);
}
}
}
It will have default values.
This is one of the many problems I set out to solve
I hate the "lazy Instance property" approach because of this
You lose control over initialization per component
and it masks errors if you forget to assign things properly
well what would be the alternative? how can you not have default values on a newly instantiated game object?
You don't need it per se, it's just a third party implementation of tasks that allocate less for Unity
I'd love some examples. It seems like mostly you're trying to control order of execution and dependency resolution, both of which SOs handle explicitly.
Why is it less clear when the callbacks execute? With SO singletons, you are managing them instead of unity so scheduling can be handled however you need
the only problem with async/await in unity is something you can see in the screenshot there
By callbacks I mean Awake, OnEnable and friends
take a look at the readme
it's not really the allocations. allocations don't really matter
And yes, order of execution & dependency resolution are some of the big ones
But also SOs don't receive Update for example
the async infinite loop runs even after you exit play mode, so it keeps trying to spawn new NetworkCore singletons infinitely
tasks are cancellable. unitask provides a way to tie the lifetime of the task to playmode transparently for the editor and standalone players. the real value of unitask is all the helpers.
this is what i mean by long journey 🙂
That's the whole point, imo. They are mostly isolated from unity's lifecycle (which is difficult to schedule and scale) so you can manage that stuff yourself. Implementing your own 'Tick' for singletons which can be called from a unity tick but doesn't have to be is so little code.
what kind of game are you trying to write? @cedar ledge
I'm fixing my professor's networking engine code
That's the whole point, imo.
Right, I don't disagree at all on that point, but that makes them unsuitable for a large portion of singletons/managers one may write
It's FULL of coroutines with sleeping threads
i see
replacing it all with async await tasks and then ill remove the hardcoded delays
what kind of game is it?
Meanwhile with the approach I outlined, you don't need to manually set up all the glue to get an Update callback on such a singleton, you just write it as you would in a normal component
no kind of game
or what's the application
huh ok, I've never run into a situation like that
coroutines don't use threads
he has coroutines and threads and thread.sleeps
got it
On some of the games I've worked on, it's been a rather important factor
that's fair, but I would argue that for most games I would prefer to set that up because unity's silly monobehavior priority system is a ridiculous way to manage execution order
well we can talk about, from a bigger perspective, how to deal with what you have
if you're interested
You can of course still do it with a SO, it's just more annoying
like a good approach to what you are trying to fix, and why
anyway, just curious if you had thought about it, because to me it feels like you are doing a ton of work to get what SO singletons give you mostly for free
but it sounds like you feel the opposite, so that's legit
100% agreed, I think 90% of the code I write in Unity is trying to work around the various garbage in the engine
Singletons are as prolific as they are because Unity's design pushes you towards them
You have to actively try really hard to avoid them
based on the limited knowledge i have re: what you are trying to do @cedar ledge , probably transitioning to libraries that solve the specific problems you have would have the greatest value, followed by fixing what you currently have with new code you author yourself
I don't see an SO singleton as a 'real' singleton because I can have multiple instances of one of i wanted to
and i can help you identify those libraries
i suspect you have this goal already, it's just about... well what ARE all the libraries?
and i might for different contexts, and they don't have any weird code which causes the old instances to destroy themselves
The same goes for the MonoBehaviour one, which is actually something I tried to account for in my design -- though it wasn't an explicit goal to support it
maybe i just never use real singletons so these patterns feel silly to me
The important functionality was the "persistent object" system, moreso than MonoSingleton which is just an example of a type you can build on top of it
yeah, and i used to do something similar, but over time feel like SOs just make more sense
you mean transitioning to libraries like UniTask?
yes, or say, Mirror
For example, I have the EventSystem object (one of Unity's "built-in" singletons) on my persistent objects prefab so I don't have to place it everywhere
It just works™️
really depends the scope of what this library does
the whole point of this networking code is to not need the more complicated libraries like mirror
yes, but you personally know that, unless it's a specific piece of example code that implements a specific style of game, your library and mirror are both inaccessible to students 🙂
My engine code will be a drop in replacement for his
It's used the same way, except for stuff like students won't have to make every NetworkTick an infinite while loop
it really depends on what the objective is
ah yeah i can see it being nice for cases like that
@cedar ledge for example, making a library to make any general multiplayer network game easy enough for a student is an impossible objective
you already know that though
and to be fair -- without comments the entire system including MonoSingleton is like 50 lines of code, I hardly did a ton of work 
so we could like, talk about a tractable goal
it being tiny and simple while solving the problems I had was the goal, which I got lucky enough to achieve
it's already done and being used by students, but it only runs at like 10 Hz because of how unoptimized it is. I'm just fixing that stuff behind the scenes
i mean, making multiplayer experiences easy to develop already exists, it's new input system and multi-display outputs. they're just not networked.
okay but think about how to get the most out of me
Ideally a networking library for Unity would make use of source generators, but Unity's support for them is garbage right now, and I don't think they support incremental generators so it's useless anyway
get the most out of you?
yes. like if you want to build a multiplayer networking library, what are some example games you would want to support? and the audience is for students?
does it really have to be backward compatible with existing, unmaintained code? or backward compatible with pre-existing educational content?
hmm, but what do students want to create generally?
FPSes, for example, they follow so many specific traditions, their networking implementation is pretty much incompatible with everything else
yes, because half of his class is about how to use his particular networking engine. if i give him some random unrelated thing, he'll think it's cool but useless to him. he has designed his entire class around his API
there's nothing wrong with his API on the front end
I'm just fixing the back end
what class is it?
i guess i can just look right? it's public online no?
Game Design and Development 2
florida polytechnic university
i'm struggling to find a public site or github here i'm sorry
the engine provides a way to
-client send a command to the server
-serversend an update to the client
-handle a command/update message
-run code when the client is connected
-run code every network tick
-instantiate prefabs
-etc
Students have made all sorts of games using it in the past. The problem is that he has to dissuade students from doing anything that would require lots of information or high tick rate
Online Catalog for Florida Polytechnic University undergraduate & graduates. View course descriptions, requirements, & programs on STEM curriculum.
looking for this?
or do you just want the code?
it's on his canvas
ill upload it here i guess
got it
he made a minor change to it within this assignment template, so that has the most updated version of the code
okay
Well, I can say one thing lol, this is definitely university course code
yep
so personally my suggestion is
I die every time I see this in Unity code
since the underlying API is pretty straightforward
i spent a few hours cleaning it up without changing anything lol
fixing variable names and stuff, code style mostly
i would import Mirror as a Package, and try to wire up all the pre-existing stuff using mirror
hey what is 16:9 aspect ration
well why?
is it alway 1920x1080
no
How are they always like this lol, like it's always insanely messy, mixing brace/indentation styles etc
Like do they just not care while writing it?
You don't even need to put in effort to get that stuff consistent
16:9 is the ratio of the horizontal to vertical resolution
you would just add Mirror as a unity package
is it 1920x1080
that resolution is 16:9, yes
one perspective here is that the API wouldn't need to change, and you personally would learn more from that experience
you would gain the knowledge of how to use mirror, which is valuable
you personally