#archived-code-advanced

1 messages · Page 167 of 1

honest hull
#

ffs sorry
turns out that if then never results in true
still dont know why the progressID that it chooses is like 500

flint sage
#

Haha

austere jewel
#

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

flint sage
#

Guessing the high progressId is some running number that never is decreased?

honest hull
#

I... yeah fair sorry, was something beat into me by my middle and high school

flint sage
#

Sublime can be fine imo

honest hull
#

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

flint sage
#

Just let Unity do it's thing then 😛

honest hull
#

ok lol

austere jewel
#

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?

honest hull
#

its notepad with autocomplete XD
its simple
thats about it

austere jewel
#

Yeah, that's what I would consider "not fine" 😄

flint sage
#

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#

honest hull
#

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

austere jewel
#

Support with it has probably gotten better in the 5+ years since I last tried to use it with C# 😄

flint sage
#

Idk, omnisharp was already a thing 5 years ago

honest hull
#

uugghh ok so seeing when its not equal to running isnt working apparently all are always running...

austere jewel
honest hull
#

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

flint sage
#

Probably, I unfortunately don't know that api

honest hull
#

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

flint sage
#

Well yeah if you don't do async correctly then errors will go poof

cursive tangle
#

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
flint sage
#

Sounsd like you have too much data

cursive tangle
#

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

flint sage
#

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

cursive tangle
#

That shouldn't be the case, the files are all below 1 MB (in size, that is)

#

Not sure about the memory.

flint sage
#

Lists capacity is 2.14 billion items

#

Idk if it throws an OOM exception if you try to create a bigger list

gilded wing
#

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

cursive tangle
#

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
gilded wing
#

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

gilded wing
#

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!

sage radish
gilded wing
#

lol yeah looks like it, figures

cosmic flame
#

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 ?

agile yoke
#

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 )

cosmic flame
#

@agile yoke thank you for your answer, I'll triple check everything !

bleak ridge
#

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?

winter yacht
bleak ridge
#

will take a look, though i want to change it on runtime with a coloring tool or something

red osprey
#

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.

red osprey
#

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.

remote drift
#

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

remote drift
#

I solved it

sly grove
# remote drift

you'd have to show LoopingBackgroundSystem and MovingBackgroundSystem

remote drift
#
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>

vivid prairie
#

Is there a way to attach script in the inspector that isn't inhereting from the MonoBehaviour?

remote drift
#

almost everything that is serializable can be attachable in inspector

vivid prairie
#

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;
}
remote drift
#

try SerializeReference attribute

#

both of them actually

vivid prairie
#

So I tried it and its not working :/

remote drift
#

did you add serializable attribute to your class?

vivid prairie
#

yes

remote drift
#

hm, maybe it can't be serialized then

#

simple objects usually can be serialized ez

nova gazelle
#

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...

gray pulsar
#

Also does Init even get called?

severe grove
#

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; }

gray pulsar
severe grove
nova gazelle
gray pulsar
severe grove
vivid prairie
nova gazelle
vivid prairie
#

😦

nova gazelle
#

Is there something like OnAccess?

sly grove
#

Where and when are you calling Init?

nova gazelle
# sly grove Share the parent class code

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;
        }
    }
sly grove
#

What does this code have to do with the earlier shared code?

#

If you don't call Init(), it will not run

nova gazelle
#

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;
    }

}
nova gazelle
#

Some functions run by themselves. Awake(), for example, when the object is first loaded

sly grove
#

If only there was a way to figure out what those magical functions are and when they run

shadow seal
#

Mazel tov, Init ain't one of them

nova gazelle
sly grove
#

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

nova gazelle
#

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

ancient sparrow
#
            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

full fjord
#

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?

sly grove
full fjord
#

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

ocean raptor
#

Might be weird, but I'm not trustful of Chinese software.

ancient sparrow
#

Why is screencapture not working?

austere jewel
#

You named your class screen capture

ancient sparrow
#

ohh yeah lol thanks

sterile meteor
#

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.

sly grove
remote drift
#
    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

tough tulip
remote drift
#

coroutines are meh

chrome breach
#

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);
    }
little mesa
#

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?

chrome breach
honest hull
#

Is there a way to get the thread name of an async task that points to a thread you can see in profiler?

undone coral
honest hull
#

hmmm

undone coral
#

alternatively, try to just use BeginProfile(nameof(Method))

#

don't overthink this

fresh salmon
#

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

undone coral
#

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

fresh salmon
#

Well, if they can see the thread in the profiler, they did that

undone coral
#

it just won't mean what the user thinks it will mean

fresh salmon
#

One way to find out, get the thread name from code and compare

undone coral
#

i'm not sure why people are not using UniTask for async in Unity

fresh salmon
#

lol the advertisement pushing, UniTask here, UniTask there, UniRX over here

undone coral
#

lol

#

yes i am encouraging people to use the only good free library to solve these problems

undone coral
fresh salmon
#

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

undone coral
undone coral
#

besides, i don't know, that's just how it goes with Unity. you gotta use libraries

ocean raptor
undone coral
#

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

ocean raptor
#

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.

undone coral
ocean raptor
#

RPG.

#

Yeah yeah. “Don’t make an MMO”

#

Not something I suggest to newbies, either.

undone coral
#

is your approach right now to relay networking

#

or is there an actual hosted game server

#

are you trying to do p2p

ocean raptor
#

Oh man I don’t know how to answer that without giving away a whole lot.

#

Absolutely no P2P.

undone coral
#

giving away?

#

i don't know if there's anything sensitive about a multiplayer architecture

ocean raptor
#

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.

undone coral
#

is an instance a Unity server

#

or a node.js application

ocean raptor
#

Most likely Unity.

undone coral
#

you're not 100% sure yet

#

which is okay

#

just wondering

ocean raptor
#

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

ocean raptor
undone coral
#

lol

#

what's nice about committing to use unity as a server is, what you see is what you get

ocean raptor
#

Yeah, absolutely.

undone coral
#

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

ocean raptor
#

Plus it handles a lot of stuff that makes the overhead worth it

undone coral
#

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

ocean raptor
#

This will almost certainly require DOTS, so I’m gonna have to bite the bullet on that one.

undone coral
#

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

remote drift
#

I'd double that
dots is pre alpha

ocean raptor
#

Fair

undone coral
#

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

ocean raptor
#

Would it make a fully authoritative server any less painful?

hushed fable
#

Photon Fusion and Quantum absolutely would

ocean raptor
#

Is fully authoritative even preferred for an MMO?

ocean raptor
hushed fable
#

Though I don't think you would use those for an MMO 😄

undone coral
#

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

ocean raptor
#

Might aswell experiment.

undone coral
#

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

ocean raptor
#

BRB. I’ll keep reading when I come back. I value your input.

undone coral
#

it isn't worth introducing clustering (i.e., having multiple instances share the world together) unless you absolutely have to

ocean raptor
#

$001

undone coral
#

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

hushed fable
#

Shouldn't be too bad if your world is split, so you can properly treat each area as a different server

undone coral
#

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

hushed fable
#

Boss fights being large pvp battles between factions? 😄

undone coral
#

yeah

hushed fable
#

Eve has sectors afaik, so the splitting is relatively easy

ocean raptor
#

Also, I guess that’s my big secret..

#

Hello, everyone, I’m your friendly neighborhood psychopath

undone coral
#

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

drifting yarrow
#

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

ocean raptor
#

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.

compact ingot
#

you just have to be stubborn (and rich) enough to pull through

ocean raptor
compact ingot
#

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

ocean raptor
#

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.

compact ingot
#

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

ocean raptor
#

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.

compact ingot
#

also look at WOW as an example back in 2004... it could only handle 1 raid boss per server concurrently

ocean raptor
#

Yeah, and EVE started development in 199..8?

#

Released before WoW?

compact ingot
#

eve launched in 2003 iirc

ocean raptor
#

Old as hell

compact ingot
#

its also had some major architecture updates since

#

and wow has world phasing and server groups and various other things since then

ocean raptor
#

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.

compact ingot
#

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

ocean raptor
bronze dock
#

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.

teal bluff
#

is anyone familiar with steamworks?

formal lichen
#

I think people who are aren't allowed to talk about it

teal bluff
#

oh mbmb

sage radish
undone coral
#

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

ocean raptor
#

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.

undone coral
#

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

ocean raptor
#

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

undone coral
#

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

ocean raptor
#

Right, so prototyping needs to get to ten

#

Reasonable goal

undone coral
#

photon is appropriate for "early access" multiplayer

ocean raptor
#

Subjectively, do you enjoy working with PUN?

undone coral
#

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

ocean raptor
#

I get that.

#

Doesn't help that Unity is on.. what.. its third iteration of the transport layer since 2015?

compact ingot
#

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.

ocean raptor
#

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"

undone coral
#

it's a tricky problem

compact ingot
#

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

undone coral
#

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 🙂

compact ingot
#

assuming your bottleneck is the CPU that works

#

and assuming your code can scale horizontally

random goblet
#
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..

ocean raptor
random goblet
#

Ok :p

compact ingot
#

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.

ocean raptor
#

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.

civic talon
#
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?

civic talon
severe grove
#

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?

ocean raptor
thin mesa
severe grove
#
        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";```
thin mesa
#

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

ocean raptor
severe grove
#

It is a class

ocean raptor
#

Oof Discord, that is fugly

thin mesa
# severe grove It is a class

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

severe grove
#

Awesome! I'm trying to do a big code refactor and that makes alot of my work with dictionaries much more readable.

severe grove
thin mesa
#

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

severe grove
mighty cliff
#

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

ocean raptor
#

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

deep scaffold
#

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.

orchid marsh
# deep scaffold Hello, I am in a programmer for a few year and I still don't fill like i'm a goo...

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).

deep scaffold
hazy hearth
#

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.

granite pasture
#

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?

granite pasture
# hazy hearth Hey, I have a class DeckCase which has a property: ```List<GameObject>allDecks; ...

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/

·····················································...

▶ Play video
hazy hearth
#

Does it contain Save for objects I thought it was only for int/string etc

#

let me check

#

thanks

gilded wing
#

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

flint sage
#

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

gilded wing
#

hm yeah i guess

compact ingot
gilded wing
#

oh ok, cool

#

thanks

somber swift
granite pasture
somber swift
#

idn't call it bad but not the greatest. protocul buffer or binarywriter could be faster and more memory efficient tho

sweet walrus
#

HI I am trying to add IK to my game but I have some problems. Can someone help?

unique ermine
#

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?

sullen halo
#

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.

sly grove
sullen halo
# sly grove 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

sly grove
sullen halo
#

I do not play with matrix.

#

damn coding with "simple" foot snapping to ground give me load of headache UnityChanOops

tough tulip
#

new Ray(rayOrigin + Vector3.up * rayFromAbove, Vector3.down)
is this the correct ray you want to raycast?
have you tried checking that?

sullen halo
#

the rays are cast direct through middle of the foot ( correct here )

tough tulip
#

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

sullen halo
#

my character looking like a goat lol

sly grove
sullen halo
#

yes

sly grove
#

Like I'm just wondering if somehow you're drawing the hitpoint from a different frame or something

sullen halo
#

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

sly grove
sullen halo
#

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.

undone coral
sullen halo
# undone coral 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!

https://discord.gg/aZgBgC2


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...

▶ Play video
undone coral
#

which has things like placing feet "for free"

sullen halo
#

I have that tool in my arsenal : >

#

glad to hear that

severe grove
#

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;
}

undone coral
#

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

raw schooner
#

probably better to just make something like that static or something...

severe grove
sly grove
severe grove
raw schooner
#
foreach (var skillTag in skillData.tags)
{
    switch (skillTag)
    {
        case SkillTag.CON: stats[Stat.CON]++; break;
        case SkillTag.AGI: stats[Stat.AGI]++; break;
    }
}
sly grove
#

WTF why a switch

raw schooner
#

?

sly grove
#

Just stats[skillTag]++

raw schooner
#

SkillTag and Stat are different things?

sly grove
#

Make a dictionary to map them then

#

And/Or an extension method on one of the enums

raw schooner
#

not my dicision ¯_(ツ)_/¯

severe grove
raw schooner
#

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

severe grove
#

Alrighty. I don't think this is too far along to match up enum values.

raw schooner
#

lol i guess you could do

foreach (var skillTag in skillData.tags)
{
    var stat = (Stat)Enum.Parse(typeof(Stat), skillTag.ToString());
    stats[stat]++;
}
severe grove
# raw schooner i do wonder though

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.

raw schooner
#

probably dogshit for performance though

severe grove
#

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.

modest sinew
#

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?

lusty sonnet
#

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; }

sly grove
lusty sonnet
#

hahaha 🙂

#

why

sly grove
#

instead of parenting

misty glade
#

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.

undone coral
misty glade
#

thanks.. i'd like to take credit, but it's the wireframes 🙂

#

I mean, mine's close, but there's obviously some differences

undone coral
#

i use the ScreenManager from the Material UI toolkit for toggling

#

it sounds fine to me

#

so it goes with UI

misty glade
#

here's what's "done" so far

undone coral
#

also looks really good

misty glade
#

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

undone coral
#

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

misty glade
#

yeah, I'm finding that

undone coral
#

you could try

misty glade
#

the layout groups are mostly good, but it's .. really fiddly

undone coral
#

the Flutter unity library

#

it sounds like it's only for Unity China

#

it's weird

misty glade
#

hm, i'll have a look

undone coral
#

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

misty glade
#

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
#

no

#

don't even bother with the other thing

tranquil dove
#

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.

misty glade
#

You probably don't want to add it to your AI's pathfinding until the road is complete, then, that seems straightforward enough..?

tranquil dove
#

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

misty glade
#

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.

ivory girder
#

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?

undone coral
ivory girder
tranquil dove
austere sundial
#
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:\
misty glade
# ivory girder Hey so I'm just curious, what are the actual benefits of applying principal of l...

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.

raw schooner
misty glade
#

heh heh heh

#

unless you know what 0x5f3759df is, you probably ought to not be downcasting your data types

austere sundial
misty glade
#

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

raw schooner
#

and use implicity type, what's going on in this discord lol

#

everyone is so insistent on using explicit declaration

misty glade
#

I sorta hate var but I'm a relic 😛

raw schooner
#

auto devious_hehe

austere sundial
raw schooner
#

and you can

#

it's a numeric type, you can compare it to anything

#

any other numeric type

austere sundial
misty glade
#

12 occurrences of "var" in 70k+ lines of source code

raw schooner
#

i hate it

misty glade
#

🤷‍♂️ 🙂

austere jewel
#

meanwhile in my code

raw schooner
#

~230 occurences in my one project of 6.5k lines

austere jewel
#

When suitable nowadays I tend to use a blank new instead of var, but often that isn't relevant

raw schooner
#

yeah it doesn't really help much. it's technically less characters, but i prefer lining up the declarations on the left

austere jewel
#

I don't often type that stuff anyway

misty glade
#

tab-tab-tab-tab-tab is pretty much how i code

austere jewel
#

declare the content, get rider to autocomplete the declaration

misty glade
#

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

austere jewel
valid flame
#

do you guys have any tips on debugging errors that only occur in the build and not in the editor?

austere jewel
#

Depends what kind of error they are. Getting deep with the debugger is usually the solution for code problems.

valid flame
misty glade
#

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

valid flame
austere jewel
#

🤷 use the debugger and you don't need to do that

misty glade
valid flame
#

I know I can see the player log but it's not super useful

austere jewel
#

Yes, if you build it as a development build you can connect the debugger to it

valid flame
#

OHh developement build I completely forgot that existed

austere jewel
#

If it happens immediately on startup you can even make it wait for you to connect a debugger before continuing

valid flame
#

Ok wait so is connecting a debugger the same as attaching to unity basically?

austere jewel
#

If you mean that button in your IDE, yes

valid flame
#

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

austere jewel
#

The debugger is not a log, it's breakpoints and stepping over code

valid flame
#

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

austere jewel
#

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.

valid flame
austere jewel
#

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.

valid flame
#

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

austere jewel
#

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

valid flame
#

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

austere jewel
#

Checking Unity objects for null is cheap, but expensive relative to other operations like checking normal objects for null

valid flame
#

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

austere jewel
#

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.

ocean raptor
#

@austere jewel what about making it private?

#

Sorry, forgot you don't like mentions

austere jewel
#

Then it wouldn't be serialized, which is the entire problem

ocean raptor
#

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"

austere jewel
#

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

ocean raptor
#

Right, hence the confusion. Sorry.

valid flame
#

I think that should work the same as those free ones

raw schooner
#

Can you have a script connected to a scene?

drifting galleon
raw schooner
#

Say I have a TitleManager (for a title screen), where would I put this?

native flint
#

@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

raw schooner
#

No, TitleManager was correct

#

As in Title screen

#

Main menu

drifting galleon
#

empty gameobject

late thunder
#

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.

devout hare
regal olive
#

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

#

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

remote drift
#

I'm guessing you want aabb of collider?

#

aren't there helper methods for that?

#

Collider.bounds

regal olive
#

I cant use collider.bounds because it doesnt account for rotation but Im getting very close with this

remote drift
#

hm

#

it says bounds returned by collider

regal olive
#
//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
remote drift
#

are in world space

#

while mesh is local space

#

oh wait, my bad
renderer bounds

#

world space

#

mesh - local

regal olive
#

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

remote drift
#

GetComponent without caching is a red flag when hiring programmers kek

regal olive
#

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

remote drift
#

I really think you overcomplicate it

tranquil dove
#

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.

remote drift
#

I'm fairly certain you can get world space AABB without manual calculation

remote drift
tranquil dove
#

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.

tough tulip
#

based on how you implemented the tiling system, and how the circlea are placed, it should be fairly easy with linked list

tranquil dove
#

you mean... by using an array?

tough tulip
#

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

tough tulip
remote drift
tranquil dove
#

okay.

regal olive
#

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);```
winter yacht
tranquil dove
remote drift
#

oooh

tranquil dove
remote drift
#

that is actually quite complex system to do, as far as I know

#

potentially you might want to do simple pathfinding implementation I think

winter yacht
remote drift
#

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

tranquil dove
#

and i can store them to an array...

#

i'll try that out and I'll make you know

#

thanks!

winter yacht
regal olive
regal olive
#

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

wintry dragon
#

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.

flint sage
#

Are they individual cubes or merged?

naive adder
#

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

regal olive
#

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);```
tough tulip
undone coral
regal olive
#

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.

hot kettle
#

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

compact ingot
naive adder
# tough tulip are you using the same unity version you built the project 2 years ago? your bes...

@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

regal olive
crisp narwhal
#

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

dense radish
#

bool[,] tiles = new bool[5,5]; is perfectly valid... anyone have a serialization tip on this one?

quartz stratus
#

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.

quartz stratus
# crisp narwhal Hey All, I am trying to read and write to json in unity. part of the data I am s...

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

GitHub

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)

proud gust
#

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?

quartz stratus
proud gust
#

That looks really cool, but a bit overkill for my usecase. I just want to be able to recreate a tilt brush mechanic

proud gust
#

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 😄

agile brook
#

set line topology and you can draw lines

proud gust
#

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

pseudo crown
#

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.

humble onyx
drifting galleon
humble onyx
#

but there is the IL code "link" that opens the IL viewer witht he code in it

pseudo crown
#

But why wouldn't I be able to decompile net standard? It's just a DLL or is there some magic going on?

drifting galleon
pseudo crown
#

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.

drifting galleon
#

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

pseudo crown
#

Thanks!

glass anvil
#

that's interesting - didn't know that about 2021+.

cedar ledge
#

why can't I call a protected interface method from the class implementing said interface?

agile brook
flint sage
#

It's true in Unity

agile brook
heady bane
#

does anyone know how to set up obi cloth particle filters?
I'm struggling a bit with getting them working.

mighty cliff
#

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??

drifting galleon
#

as a start, you should use the event workflow instead of whatever you are doing.

mighty cliff
#

??

final steeple
#

((INetworkable)this).NetworkTick()

regal olive
#

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?

final steeple
#

Do you want to prevent duplicate shaders or duplicate materials?

#

Also .material will return Instantiate(sharedMaterial)

#

So Contains will always return false there

hollow garden
#

yeah it's technically a different material according to unity

final steeple
#

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

hollow garden
#

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

regal olive
#

How would the correct approach be?

final steeple
#

Use sharedMaterial instead of material

#

Never use the material property

regal olive
#

Thank you.

proud gust
# agile brook https://docs.unity3d.com/Manual/AnatomyofaMesh.html here read about** topology**

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

proud gust
# final steeple Never use the `material` property

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

final steeple
#

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

proud gust
#

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?

final steeple
#

It depends on which properties you change

#

If the property is instanced (such as _Color), then it shouldn't affect draw calls

proud gust
#

Sweet

final steeple
#

It's a very useful API, shame it's not more well-known

#

That goes for a lot of stuff in Unity, really

proud gust
#

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 😄

final steeple
#

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

proud gust
#

True

#

Same with meshes lol

final steeple
#

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

proud gust
#

Then it'll probably take fairly long haha

final steeple
#

I'd be surprised if it happened at all, tbh

sly grove
#

News to me

final steeple
#

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

sly grove
#

Oooh so it works with the job system. Awesome

final steeple
#

Yep

sly grove
#

Probably how MegaFiers 2 is working

winter yacht
#

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.

sly grove
#

Are some of these positions in local space?

winter yacht
placid seal
#

How would I go about creating mesh info server sided, then passing the info to the client who when creates the actual object?

flint sage
#

You don't

#

You tell the client what to create and then it recreates it

sly grove
regal olive
#

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);```
undone coral
#

otherwise you can use Mathf.Atan2

regal olive
#

Ive tried using Atan2 but its very confusing

undone coral
placid seal
undone coral
#

i strongly recommend it 🙂

regal olive
#

Ill take a look

placid seal
#

basically I am creating a dynamically loaded universe (multiplayer)

#

planets are loaded using 6 meshes

undone coral
#

the art is pointed one way, and your coordinate system is pointed in another

winter yacht
undone coral
#

generally trying to create a mesh directly is a graveyard

regal olive
#

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);```
undone coral
undone coral
#

think about what can go on the right hand side of that statement

regal olive
#

lmao I was using transform.right hours ago before I started getting wacky results so Im trying to be more accurate

undone coral
regal olive
#

Dont be so passive aggressive

fresh salmon
regal olive
#

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

fresh salmon
#

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

winter yacht
fresh salmon
#

Yeah that too, the ones displayed in the Inspector are the localEulerAngles

regal olive
#

Ah thats it

fresh salmon
#

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

regal olive
#

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;```
cedar ledge
#

I ended up using a publisher/subscriber pattern

#

So now all the network components subscribe to the networkcore's networktickevent

final steeple
#

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

placid seal
cedar ledge
final steeple
#

In that case an interface is likely not the right approach then, yeah

cedar ledge
#

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

final steeple
#

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

undone coral
# cedar ledge So now all the network components subscribe to the networkcore's networktickeven...

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
   }
  }
}
final steeple
undone coral
#

yeah this stuff is tricky to make really bullet proof, if you're trying to make a library for other people to use

final steeple
#

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

undone coral
#

on the flip side, it's okay to throw errors.

final steeple
#

Even ensures things are wired up before Awake even runs

undone coral
#

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

final steeple
#

It's a shame that the actual dispatching code for that API isn't super optimized

undone coral
#

yeah... but i don't know if that ever comes up in a profiler in a meaningful way

final steeple
#

It allocates on every call, and the design makes it hard to work around the ones you can avoid

cedar ledge
#

NetworkCore

#

NetworkComponent

#

anything wrong with this?

undone coral
final steeple
#

Seems fine to me, a protected virtual on a base class more accurately describes the design you seemed to be going for earlier

undone coral
#

it really depends on what you're trying to do

#

this is well worn ground

final steeple
#

But yes, move to tasks if possible

cedar ledge
#

they can't share a base class unfortunately

#

wdym move to tasks?

undone coral
#

are you targeting a specific kind of game, like an RTS?

cedar ledge
#

no

final steeple
#

Also async void is bad

#

It will eat exceptions

cedar ledge
#

everyone says only use async void for "fire and forget" methods

#

and callbacks

#

and thats what start is

final steeple
#

yes, but even then it's not a good idea

#

you won't receive the exceptions thrown in them

cedar ledge
#

what would you have me do?

final steeple
#

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

cedar ledge
#

WaitUntil() doesn't throw exceptions

final steeple
#

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

cursive horizon
final steeple
#

I'm talking about in general

cedar ledge
#

ok

cedar ledge
final steeple
#

Callbacks are also a bit harder to manage with SOs since it's a bit less clear when they execute

cedar ledge
#
    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);
            }
        }
    }
final steeple
#

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

cedar ledge
#

well what would be the alternative? how can you not have default values on a newly instantiated game object?

final steeple
cursive horizon
cedar ledge
#

the only problem with async/await in unity is something you can see in the screenshot there

final steeple
#

By callbacks I mean Awake, OnEnable and friends

undone coral
#

it's not really the allocations. allocations don't really matter

final steeple
#

And yes, order of execution & dependency resolution are some of the big ones

#

But also SOs don't receive Update for example

cedar ledge
#

the async infinite loop runs even after you exit play mode, so it keeps trying to spawn new NetworkCore singletons infinitely

undone coral
#

this is what i mean by long journey 🙂

cursive horizon
# final steeple But also SOs don't receive `Update` for example

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.

undone coral
#

what kind of game are you trying to write? @cedar ledge

cedar ledge
#

I'm fixing my professor's networking engine code

final steeple
#

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

cedar ledge
#

It's FULL of coroutines with sleeping threads

undone coral
#

i see

cedar ledge
#

replacing it all with async await tasks and then ill remove the hardcoded delays

undone coral
#

what kind of game is it?

final steeple
#

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

cedar ledge
#

no kind of game

undone coral
#

or what's the application

cursive horizon
undone coral
cedar ledge
#

it's an networking engine for his students to use for any kind of game

#

i know

undone coral
#

sleeping them is often okay

#

i see

#

okay

cedar ledge
#

he has coroutines and threads and thread.sleeps

undone coral
#

got it

final steeple
cursive horizon
undone coral
#

well we can talk about, from a bigger perspective, how to deal with what you have

#

if you're interested

final steeple
#

You can of course still do it with a SO, it's just more annoying

undone coral
#

like a good approach to what you are trying to fix, and why

cursive horizon
#

but it sounds like you feel the opposite, so that's legit

final steeple
#

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

undone coral
#

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

cursive horizon
#

I don't see an SO singleton as a 'real' singleton because I can have multiple instances of one of i wanted to

undone coral
#

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?

cursive horizon
#

and i might for different contexts, and they don't have any weird code which causes the old instances to destroy themselves

final steeple
cursive horizon
#

maybe i just never use real singletons so these patterns feel silly to me

final steeple
#

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

cursive horizon
cedar ledge
undone coral
final steeple
#

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™️

undone coral
#

really depends the scope of what this library does

cedar ledge
#

the whole point of this networking code is to not need the more complicated libraries like mirror

undone coral
cedar ledge
#

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

undone coral
#

it really depends on what the objective is

cursive horizon
undone coral
#

@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

final steeple
undone coral
#

so we could like, talk about a tractable goal

final steeple
#

it being tiny and simple while solving the problems I had was the goal, which I got lucky enough to achieve

cedar ledge
undone coral
#

i mean, making multiplayer experiences easy to develop already exists, it's new input system and multi-display outputs. they're just not networked.

undone coral
final steeple
#

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

cedar ledge
undone coral
cedar ledge
#

fps, sandbox, whatever the students want to create

#

yeah

undone coral
#

does it really have to be backward compatible with existing, unmaintained code? or backward compatible with pre-existing educational content?

undone coral
#

FPSes, for example, they follow so many specific traditions, their networking implementation is pretty much incompatible with everything else

cedar ledge
#

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

undone coral
#

i guess i can just look right? it's public online no?

cedar ledge
#

Game Design and Development 2

undone coral
#

that might be most useful

#

at cal?

cedar ledge
#

florida polytechnic university

undone coral
#

i'm struggling to find a public site or github here i'm sorry

cedar ledge
#

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

#

looking for this?

#

or do you just want the code?

#

it's on his canvas

#

ill upload it here i guess

undone coral
#

got it

cedar ledge
#

he made a minor change to it within this assignment template, so that has the most updated version of the code

undone coral
#

okay

final steeple
#

Well, I can say one thing lol, this is definitely university course code

cedar ledge
#

yep

undone coral
final steeple
#

I die every time I see this in Unity code

undone coral
#

since the underlying API is pretty straightforward

cedar ledge
#

fixing variable names and stuff, code style mostly

undone coral
#

i would import Mirror as a Package, and try to wire up all the pre-existing stuff using mirror

regal olive
#

hey what is 16:9 aspect ration

cedar ledge
#

well why?

regal olive
#

is it alway 1920x1080

cedar ledge
#

no

final steeple
#

Like do they just not care while writing it?

#

You don't even need to put in effort to get that stuff consistent

cedar ledge
undone coral
#

you would just add Mirror as a unity package

regal olive
cedar ledge
#

that resolution is 16:9, yes

undone coral
#

you would gain the knowledge of how to use mirror, which is valuable

#

you personally

final steeple
#

1920x1080 is a 16:9 resolution, but there are an infinite amount of 16:9 resolutions

#

It is just one of them