#archived-code-advanced

1 messages · Page 46 of 1

velvet rock
#

Does anyone know if there is a way to exclude whole namespaces from stack traces in the console? I am using a loggging api, and the entire thing is showing up in the logs.

strange sparrow
#

I'm trying to do something similar to Render Scale option of URP to built-in rendering. Which :

  1. Render the cameras onto a render texture with 1/2 or 1/4 native size of screen.
  2. Render the result to the screen on real-time.
    Set resolution works fine to reduce screen res, but it also reduces UI quality.

(1) is easy to work, but I'm struggling with (2), as I can't find or get the current Render Texture which Unity is using to draw onto the screen.
Does anyone face the same problem?

nova summit
#

Today I saw some code like this

        internal void InstantiateScoreFlyer(GUIFlyer scoreFlyerPrefab, int score)
        {
            if (!scoreFlyerPrefab) return;
            if (!parentCanvas)
            {
                Debug.Log("no canvas");
                GameObject gC = GameObject.Find("CanvasMain");
                if (gC) parentCanvas = gC.GetComponent<Canvas>();
                if (!parentCanvas) parentCanvas = FindObjectOfType<Canvas>();
            }

            GUIFlyer flyer = scoreFlyerPrefab.CreateFlyer(parentCanvas, score.ToString()); //Focus here
            if (flyer)
            {
                flyer.transform.localScale = transform.lossyScale;
                flyer.transform.position = RectTransformUtility.WorldToScreenPoint(Camera.main, transform.position);
            }
        }

Here scoreFlyerPrefab is a prefab thats dragged in the inspector. Surprising thing is it's calling CreatePrefab without even instantiating. This how CreateFlyer looks

public GUIFlyer CreateFlyer(Canvas parentCanvas, string flyerText)
        {
            if (!parentCanvas) return null;
            GUIFlyer gF = Instantiate(this, parentCanvas.transform); //Focus here
            if (gF && gF.text) gF.text.text = flyerText;
            return gF;
        }  

Surprisingly, whole thing works without a problem. I understand that Instantiate will clone the object passed but here it's able construct the whole object by just passing "this" which means the GuiFlyer already got instantiated but more like an orphan copy (as there is no gameobject shown in scene hierarchy yet) and this whole thing is totally confusing.
Can someone explain how this whole thing works?

sly grove
#

it copies the entire GameObject

#

(including all components, children etc)

#

and it just gives you back the reference to the component you copied on the new instance

#

it's the preferred way to Instantiate IMO because it skips unecessary GetComponent calls and GameObject referneces

clever urchin
#

^ this

nova summit
# sly grove You can Instantiate from a component reference. It doesn't create an "orphan"

Probably something is not clear from my question. Let me make it step wise

  1. Add a serializefield in a script to hold a prefab ([SerializeField] Gun m_gunPrefab)
  2. Drag a physical prefab asset to the above serialize field (m_gunPrefab)
  3. Hit play
  4. I can literally call methods with m_gunPrefab variable (without calling even Instantiate)

In step 4, if im able to call Gun methods, it actually means there is an instance of Gun already. But I don't see this component attached to any gameobject in scene hierarchy. Thats why im calling this orphan

clever urchin
#

Is Gun a monobehaviour in this example?

#

Also when you run the scene, search the hierarchy for t:Gun which should show every gameobject with Gun monobehaviour attached

#

Step 4 shouldn't work without having an active (in the scene) reference

sly grove
#

it is not an "orphan"

#

but it does not exist in the scene yet. The prefab is there in its entirety

#

Just note that since it's a prefab and not in the scene, it will not have had its Awake, OnEnable, Start, etc. called on it. Also it will not Update etc..

nova summit
sly grove
#

what do you want proof of?

nova summit
# sly grove it is not an "orphan"

So, it's created but not added to the scene. It may have got added to a gameObject too right? Just that it's not presented in the scene.

sly grove
#

They are just GameObjects as assets

nova summit
sly grove
#

And they behave just like any other asset

sly grove
#

you can see it in your project folder

#

it's an asset

#

just like other assets (Materials, ScriptableObjects, Textures, etc..)

nova summit
#

ok, thanks @sly grove

sly grove
dapper cave
#

been moving things with asmdef and running into this, can't figure out which package I must add to the reference bucket of this asmdef: You must add a reference to assembly 'PackageTools, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

#

it's aron's Astar

crystal parrot
#

Is there a Vector3.Slerp equivalent to Vector3.MoveTowards?

Verctor3.MoveTowards for spherical?

untold moth
#

That would be just rotating the vector over time.

crystal parrot
#

Yeah

#

Max deg rotation but i want it to use the vector length too

#

they are not normalized

crystal parrot
#

i`m doing steering behaviour and i want to blend from current steering to desired steering

#

are the inputs from vector3.rotatetowards two rotation vevtors? normalized

untold moth
#

They're direction vectors as explained in the description

crystal parrot
#

And is there a vector3.rotatetowards for ecs? with float3

#

i found it probably

    {
        // replicates Unity Vector3.RotateTowards
        float delta = Vector3.Angle(current, target) * Mathf.Deg2Rad;
        float magDiff = target.magnitude - current.magnitude;
        float sign = Mathf.Sign(magDiff);
        float maxMagDelta = Mathf.Min(maxMagnitudeDelta, Mathf.Abs(magDiff));
        float diff = Mathf.Min(1.0f, maxRadiansDelta / delta);
        return Vector3.SlerpUnclamped(current.normalized, target.normalized, diff) *
        (current.magnitude + maxMagDelta*sign);
    }```
#

looks slow ..

tall igloo
#

Hi everyone,

I'm running into a weird issue with Scriptable Object deserialization. I have scriptable objects which contain a simple custom class. This class has a bool array and a string array. The class is marked as Serializable, and both arrays are public. If I open the SO .asset files in a text editor, I can see the bool and string array data is serialized there. However, if I close and open the editor, the bool array data is appears as all false in Unity. It is seemingly not deserialized, because the .asset files still contain the original bool array data. The string array data is properly deserialized. If I change the name of the scriptable object in the editor, the original bool data appears.

Who knows what is happening here?

#

Using Unity 2019.4 btw

EDIT: solved! The problem was an OnValidate function which checked a non-serialized field which lead to the bool array being reset.

zealous tide
#

Hey guys, I am trying to run Code Coverage for my game however, it is stick on "Generating report" since 5 minutes. Could there be a reason behind this?

unborn current
#
ZenjectException: Assert Hit! Could not find component with type 'MeshRenderer' on game object 'SceneContext'
  at ModestTree.Assert.IsNotNull (System.Object val, System.String message, System.Object p1, System.Object p2) [0x00032] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Internal\Assert.cs:275 
  at Zenject.GetFromGameObjectGetterComponentProvider.GetAllInstancesWithInjectSplit (Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Action& injectAction, System.Collections.Generic.List`1[T] buffer) [0x0005b] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\ComponentProviders\GetFromGameObjectGetterComponentProvider.cs:60 
  at Zenject.CachedProvider.GetAllInstancesWithInjectSplit (Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Action& injectAction, System.Collections.Generic.List`1[T] buffer) [0x00071] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\CachedProvider.cs:100 
  at Zenject.IProviderExtensions.GetAllInstances (Zenject.IProvider creator, Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Collections.Generic.List`1[T] buffer) [0x00008] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\IProviderExtensions.cs:31 
  at Zenject.IProviderExtensions.GetAllInstances (Zenject.IProvider creator, Zenject.InjectContext context, System.Collections.Generic.List`1[T] buffer) [0x00001] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\IProviderExtensions.cs:22 
  at Zenject.DiContainer.GetDecoratedInstances (Zenject.IProvider provider, Zenject.InjectContext context, System.Collections.Generic.List`1[T] buffer) [0x0002b] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:1199 
  at Zenject.DiContainer.SafeGetInstances (Zenject.DiContainer+ProviderInfo providerInfo, Zenject.InjectContext context, System.Collections.Generic.List`1[T] instances) [0x00094] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:1128 
  at Zenject.DiContainer.ResolveDependencyRoots () [0x00113] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:399 
  at Zenject.DiContainer.ResolveRoots () [0x00017] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:333 
  at Zenject.SceneContext.Resolve () [0x00059] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:299 
  at Zenject.SceneContext.RunInternal () [0x00016] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:141 
  at Zenject.RunnableContext.Run () [0x00015] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\RunnableContext.cs:36 
  at Zenject.RunnableContext.Initialize () [0x00016] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\RunnableContext.cs:22 
  at Zenject.SceneContext.Awake () [0x00002] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:113 

(Filename: D:/Praca/sowclean/Assets/Plugins/Zenject/Source/Internal/Assert.cs Line: 275)
#

Getting this Zenject error

#

any ideas how to fix this monster?

#

for some reason it only happens in the build of my game

#

not in the editor

lofty inlet
#

is there a way to replace the text of a function?
so if I have a property and function

public bool edible = true;
public void DoSomething(){
Debug.Log("eating");
}

in class "Fruit"
and I have

private Fruit apple;

can I do something like

apple.DoSomething = "Debug.Log("cutting");

like how I can do

apple.edible = false

basically is there a property that accesses the text of a function

flint sage
#

No, but you probably want virtual methods instead

lofty inlet
#

I know of virtual and asbtract methods but I'm not sure how I would use that for what I'm trying to do
ex. if it's a card game
every card in the deck is a blank "Card" class until attached with a specific "Card Name" card script that inherits from a parent "Card" class
would I be able to call the "Card Name" function from the parent "Card" class?

#

sorry if this is a basic C# concept I haven't worked with inheritance in a while

orchid marsh
lofty inlet
#

each function that replaces DoSomething would do something drastically different

#

completely different function bodies

#

I guess I should have gave a better example

orchid marsh
#
public virtual void DoSoemthing()
{
    Debug.Log("Do basic default stuff");
}```
flint sage
#

If you have a base class Fruit, that has a method DoSomething, the default implementation can be Debug.Log("Eating") and then Apple will be it's own class and override DoSomething

lofty inlet
#

yes but is there a way from the example I gave to call the child's method from the parent class

#

based on the child script that is attached

orchid marsh
#

Overriding methods would change the behavior of the method regardless if on the parent or child.

flint sage
#
Fruit appl = new Apple();
appl.DoSomething()

In this case DoSomething will do whatever Apple defined

lofty inlet
#

hmm
so if I have
Parent: Fruit
Children: Apple, Pear, Orange

would I be able to do
Fruit.DoSomething

and call each of the children's DoSomething?

flint sage
#

They're different instances so you'd have to keep a list

lofty inlet
#

so I have a gameobject with Fruit Class
then I attach one of the three child scripts

orchid marsh
flint sage
#

What, no you attach the Apple class

lofty inlet
#

now "DoSomething" would do something different based on what's attached

lofty inlet
flint sage
#

Because we're trying to fix your understanding of inheritance

orchid marsh
lofty inlet
#

it will depend on which child is attached

orchid marsh
#

There's a lack of knowledge that's keeping the discussion from furthering.

lofty inlet
#

I think it's misunderstanding not lack of knowledge

orchid marsh
#

Inheritance is pretty straight forward.

lofty inlet
#

What I'm asking is a practical use of it based on the situation I described though

orchid marsh
#

The body of the base virtual/abstract method would be completely replaced by overriding method.

#

Plain and simple.

lofty inlet
#

but that's calling the method from the child class

#

I'm talking about calling the method from the parent class

orchid marsh
#

Doesn't matter, it's been replaced.

dusty wigeon
#

And that is why we say that you do not understand inheritance/polymorphism.

orchid marsh
#

Overload and override are two different things. Should probably consider looking that up as well - overload would be what you're thinking about where behavior is relative to the current type.

lofty inlet
#

ah I think polymorphism is what I need

#

thanks

dusty wigeon
#

You should read the whole section that is listed as Fundamentals.

compact ingot
lofty inlet
compact ingot
# lofty inlet awesome this looks useful thank you

this is essentially functional programming, in that you are supplying partial implementation details in a different scope, potentially even injecting a closure over that scope.

        class Foo
        {
            public Action DoSomething = () => Debug.Log("Foo"); // default behaviour
        }

        void SomehwereElse()
        {
            Foo instance = new();
            instance.DoSomething = () => Debug.Log("Bar"); // assign a different behaviour
            instance.DoSomething(); // invoke it
        }

Note however that a delegate maintains a list of potentially multiple behaviours assigned to it and you'll have to be careful on managing what is registered into each one, making sure they don't refer to null objects.

hardy nymph
#

How can I edit the properties of a .mat file from code ?

dapper cave
#

getting something odd with asmdef, scripts in my main assembly (no special folder and no asmdef) aren't getting access to hand-rolled asmdefs... am I reading the doc wrong? "Specify whether the predefined assemblies should reference this Project assembly."

sage radish
dapper cave
hollow gull
#

asnap akayysnns HnnSNaPaPa nsnns

hardy sentinel
#

anyone found a way of using file-scoped namespaces in Unity?

mental sorrel
#

Do you know good online references for unity game architectures ?

plush hare
#

How exactly do anti-cheats work? Can't this just be reverse compiled and edited out of the application?

split folio
#

local anti cheats are most of the time ignored as it can be tampered with offline and all
what developers focus on, just as galaxyshard said, is making server anti cheat to protect other players
anything other than server anti cheat is most of the time a waste of time

split folio
# plush hare How exactly do anti-cheats work? Can't this just be reverse compiled and edited ...

and to answer your question on this, server version
it can include having a weak client "anti cheat" that basically verifies the player data before sending a request to the server
a legit player should only send requests of data is legit
you can then on the server compare the request with the player data and see if its correct

for example:
player wants to buy a new gun
it cost 25k
player has 2k
a cheater could have code rewritten and sends a request to fake it
verify on the server the player have enough money
if they dont, its most likely a cheater
done

plush hare
#

It seems like every major game has a local anticheat running on the client

split folio
#

well most do now, i believe its a company (just assuming) that has made a fairly strong anti cheat and sells it to the game developers

#

but they do also include their own small anti cheat (again assuming)

scenic forge
#

Client side anti cheat is very effective at stopping 95% of the novices trying to follow some tutorials to cheat.

#

It won't stop the 5% that know what they are doing, but for the 95% that doesn't even know how to attach a debugger and just open Cheat Engine, it does extremely well.

#

Commercial anti cheat solutions stop even more of the 5%, but that's a hefty investment that's very likely not worth it.

ripe scaffold
#

is there any reason why switching on the deep profiler while a build is running (and restarting build) would cause a nullreferenceexception?
I can start something with the deep profiler on and it seems to work fine, and i can start profiling without it on, but when it gets switched on as something is running and rebuilds then issues start

tender crow
#

i'm a beginner programmer so this prob sounds really dumb, but if someone is using speedhacks or something like that, can you just program a few conditions to check if those variables are within a normal range?

clever urchin
#

Not hard to introduce method detours and rewrite addresses of method calls

tender crow
#

oh okay, I don't know how any of it works but I guess if you can overwrite code iniatially to cheat then you can probably also overwrite those checks

distant tree
#

so i have this base Node class for a behaviour tree editor im making

[Serializable]
public class Node
{
    public virtual void Run() { }
}

and i have other classes based on this class, including the InputNode, which is the opening node for a behaviour tree:

[Serializable]
public class InputNode : Node
{
    public Node pass;

    public override void Run()
    {
        if (pass != null)
            pass.Run();
    }
}

and the ActionNode, which contains a script that it will execute when run:

[Serializable]
public class ActionNode : Node
{
    public Node pass;

    public Action action;

    public override void Run()
    {
        action.Execute();

        if (pass != null)
            pass.Run();
    }
}

this is all in a scriptable object.

my problem is im trying to save an ActionNode (for example; could be any other type based on Node) to the pass variable in InputNode, but whenever i run the game the pass variable reverts to a Node type, even tho it was assigned with an ActionNode value. I've tested this in edit mode and it works fine, but i guess the data in the scriptable object is edited in some way so it doesnt save the different type. any way to get around this?

austere jewel
#

To serialize subclasses you need to use [SerializeReference]

#

Or, your nodes need to be UnityEngine.Object types in themselves (like ScriptableObject or MonoBehaviour)

distant tree
#

do i put this above the class or the variable

austere jewel
#

Above the variable, it's like SerializeField

#

Except more complex, I would look at the !api

thorn flintBOT
distant tree
#

it works, ty

grim oxide
#

Is using messages bad performance? thinkPeepo

#

My instincts say it has to be since it's using reflection, and has to scan thru every component... but colliders use messaging and don't seem to have a problem? thinkPeepo

#

I'm using events currently and it'd be real nice to decouple further

cursive horizon
#

bad for performance, bad for the soul

hushed fable
violet shoal
#

@grim oxide Everything is bad for performance if not compared against anything. Performance considerations are also highly context dependent.

#

SendMessage doesn't actually use reflection, but it still does a lookup which is ofc. slower than a direct call or dereferenced one.

#

The bigger issue with SendMessage is how error prone it is - given that the name check only exists at runtime.

stuck onyx
#

I'm trying to do myMeshCollider.GetVertices() but im getting a list of v3 like this:

[Log] (-3.20, 0.10, -3.20)
[Log] (-3.10, 0.10, -3.20)
[Log] (-3.20, 0.10, 3.20)
[Log] (-3.10, 0.10, 3.20)
[Log] (-3.20, 0.00, -3.20)
[Log] (3.20, 0.00, -3.20)
[Log] (-3.20, 0.00, 3.20)
[Log] (3.20, 0.00, 3.20)
[Log] (-3.20, 0.00, -3.20)
[Log] (3.20, 0.00, -3.20)
[Log] (-3.20, 0.10, -3.20)````
#

Does it make any sense?

#

all the coords of the vertices oscillate between -3.2 and 3.2 which is my world coord

#

but shouldnt the vertex of the mesh be in world pos ? i dont get it

sly grove
stuck onyx
#

yeah im trying to do transform.TransformPoint(vertex)

#

as suggested here:

#

finnally i could

autumn locust
#

isnt it InvereTransform to go local=>world?
could be wrong tho, its stated in the docu

stuck onyx
#

now im taking the vertex from the meshFilter.mesh

#

and those seem fine

rose harness
#

I have the weirdest error. I have a IDialogue Script which is called when the player interacts with the gameObject that has the script. It then calls the dialogue manager and passes the dialogue and object info so it can display it on the screen. It works fine on debug mode, but when I build it with more than 1 dialogue gameObject, it always shows the newest dialogue even if i interact with an object on the other side of the map.

#

Its really confusing me lol

#

and knowing me its a stupid mistake i keep looking over

#

This is the interact code

protected override void OnCollide(Collider2D collider)    {
        if (Input.GetButtonDown("Interact"))
        {
            FindObjectOfType<DialogueManager>().StartDialogue(this);
        }
        else base.OnCollide(collider);
    }

And this is the StartDialogue code

public void StartDialogue(IDialogue dialogue)
    {
        this.dialogue = dialogue;
        npcName.text = dialogue.npcName;
        dialogueBox.SetActive(true);

        sentences.Clear();

        foreach (string sentence in dialogue.dialogue) 
        {
            sentences.Enqueue(sentence);
        }
        DisplayNextSentence();
    }
#

ooh i just realised its detecting the collision everywhere on the map because it was colliding with the wall collider

#

sorry for the spam

hybrid notch
#

hi guys,
a question regarding DOTS:
Why does the Random here get the same seed for every job? The System exists once and Jobs are newly created objects, so
shouldn't each object creation get a new random value?

 var rndSeed = SystemAPI.GetSingletonRW<RandomValue>();

 var jh = new SpawnJob {
     buffer = cmdBuffer,
     deltaTime = deltaTime,
     // not sure why, but this still generates all jobs with same seed           
     rndSeed = rndSeed.ValueRW.value.NextUInt() 
  }.Schedule(state.Dependency);
  jh.Complete();
#

i get a new seed/value for every frame but all Spawnjobs within the same frame get the same seed

harsh nexus
#

hmm you are passing in the rndSeed to the job, and every execute() call reuses that same seed

#

would have to see more of the implementation but thats a really common thing, you want a different Random instance for each one

hybrid notch
#

what do you need more of the implementation?

#

it is very basic. if my reference is wrong and Random.value actually gets copied, then all frames should have the same seed

#

thats not happening, they are changing, so next() is correctly called on the random object

#

but how can Next() be called multiple times without increaseing the seed for each call?

#

obviously thats not possible

#

so it means the job object gets copied(?) for execution?

#

its the only explanation i have

#

here is the job:

[BurstCompile]
public partial struct SpawnJob : IJobEntity
{
    public float deltaTime;
    public EntityCommandBuffer.ParallelWriter buffer;
    public uint rndSeed;

    [BurstCompile]
    public void Execute(RefRW<SpawnZone> spawnZone, TransformAspect tf, PostTransformScale scale) {
        spawnZone.ValueRW.elapsedTime += deltaTime;
        if (spawnZone.ValueRW.elapsedTime >= spawnZone.ValueRW.SpawnTimer) {
            spawnZone.ValueRW.elapsedTime -= spawnZone.ValueRW.SpawnTimer;
            var rnd = new Random(rndSeed);
            // calculate random spawn position in spawn Zone
            var x_max = tf.LocalPosition.x + (scale.Value.c0.x / 2);
            var x_min = tf.LocalPosition.x - (scale.Value.c0.x / 2);
            var z_max = tf.LocalPosition.z + (scale.Value.c2.z / 2);
            var z_min = tf.LocalPosition.z - (scale.Value.c2.z / 2);

            var x = rnd.NextFloat(x_min, x_max);
            var z = rnd.NextFloat(z_min, z_max);

            var spawnedEntity = buffer.Instantiate(0, spawnZone.ValueRW.UnitPrefab);
            buffer.SetComponent(1, spawnedEntity, new LocalTransform {
                Position = new float3(x, 1, z),
                Scale = 1,
            });
        }
    }
}
harsh nexus
#

yes so you are passing in a random seed to the job object, and every time the Execute function is called it creates a new random using the same seed

#

so new Random(2) -> next() function will always give the same value

#

because the seed is deterministic

hybrid notch
#

yes, but the Job object itself should get a differnet seed for each instantiation

harsh nexus
#

there is one job and many executions i think

hybrid notch
#

so the new Job() part only gets called once

#

ah, the execute function itself is what gets called x times, not the job

harsh nexus
#

thats it

hybrid notch
#

well, then the only solution would be having a random object inside the SpawnZone component

harsh nexus
#

more people who use dots in there

#

not that it was wrong to post here

hybrid notch
#

ok, will post there next time thy

harsh nexus
#

yeah i have a test project with 100,000 units that wander to random destinations and each unit has their own Random component lol

hybrid notch
#

but to add to this, if i would create spawZones in a job, i would have the same problem, not being able to init a Spawnzone with a different random value

#

i know no way of getting different random values into the execute then

harsh nexus
#

each spawn zone has a RandomComponent : ComponentData with a mathematics.Random instance in it

#

and the job accesses 'SpawnZoneAspect', the aspect has RW access to the random component

#

that way all the spawn zones can generate random numbers without waiting for the Random instance to be free

hybrid notch
#

yes but that only works if you create the SpawnZone not in a parallel job itself

#

otherwise you cannot create differnet seeds for each spawnZone

harsh nexus
#

true, but how many spawners do you really need?

hybrid notch
#

is there no way of accessing static variables with mutexes out of execute?

harsh nexus
#

is it not ok to do it once on the main thread at the start of the program?

hybrid notch
#

its not about the actual spawner, its more about the concept

harsh nexus
#

there would have to be an original spawner to spawn the spawn zones, and that original spawner would have the original seed made on the main thread i guess

#

and from there the seeds branch out into a tree graph i guess haha

hybrid notch
#

yes, but the problem still persists... having many random values in parallel requires setting them up in a non-paralel way beforehand. Normally i would access a mutexed static variable,
but i'm not sure if unity even supports mutexes

#

thanks for your input

harsh nexus
#

i think there's a method where you can count the possible number of threads and have an array of Random instances, and then inside the job you access the Random instance using the currentThreadID

#

i havent tried it and don't know how safe it is lol

hybrid notch
#

yeah i read it somewhere, i think the BatchEntity job provides access to some index, but i didnt spend more time investigating, as it comes with a whole lot of other strings attached

sage glen
#

Is there a message I have to send from a TCPListener -> TCPClient to tell the client it's finished connecting? I have a client that can connect to an existing service and works fine, but when I have a server on my localhost the server fires the BeginAcceptTcpClient callback, calls EndAcceptTcpClient, and says the client is connected and the networkstream is readable, but the client never fires the on-connected event

hybrid notch
#

no idea about TCP-APi, but OnConnected sounds more like a server side event, rather then a client side event. menaing maybe its only fired on the server once a new client connected

sage glen
#
Client.BeginConnect(Dns.GetHostAddresses(ServerAddress), ServerPort, new AsyncCallback(onConnect), Client);
``` The client fires the callback when it gets some sort of connection confirmation, and that callback starts the stream reading thread while also sending the first packet to the server. This works fine for the existing server that isn't under my control
#

When I try to connect to my localhost server, that callback never fires but the server-side says it made a connection which is why I'm a bit lost lol

west scarab
#

How does the StringLogger sink work? How do I access the in-memory string?

#

Nevermind, you can just read it from the sink

undone coral
#

i assume your'e spawning more than one job, and with distinct values right?

#

there's a lot of mental noise around hwat's really going on. to put it simply

#

@hybrid notch
[1]

var seedGenerator = new System.Random();
foreach (var jobSpec in jobSpecs) {
 var job = new Job(jobSpec, new Random(seedGenerator.NextInt()));
}

is correct.

var seedGenerator = new System.Random();
var seed = seedGenerator.NextInt();
foreach (var jobSpec in jobSpecs) {
 var job = new Job(jobSpec, new Random(seed));
}

is not.

[2] also, you should know, that your random implementation may be of the form

class Random {
  int seed;
  int NextMutable() {
   seed = XORShift(seed);
   return seed;
  } 
}

let's pretend int XORShift(seed) => seed + 1;. it sort of is, essentially. then clearly a lot of your spawned sequences, in your current code, will be exactly the same

#

since your code is incomplete it's hard to say what exactly your bug is, but it's 70% likely to be [2] and 30% likely to be [1]

west scarab
#

Unity.Logging

undone coral
#

gotchya... what is your goal btw?

west scarab
#

Wanting to set up a more extensive logging setup

undone coral
undone coral
#

and use standard .net ecosystem tools

west scarab
#

Those aren't burst compatible

undone coral
#

why would you need to burst compile a job that prints logs

west scarab
#

Because I want to log from inside burst compiled jobs

undone coral
#

👀👀👀👀👀👀👀

undone coral
#

if you need logging

west scarab
#

?

#

I am

undone coral
#

i'm saying you can

#

turn off burst compilation if you need logs

west scarab
#

The microsoft logging libraries will not work in burst

#

I don't want to turn off burst

undone coral
#

okay

#

why do you think you can't log from burst compiled jobs*?

west scarab
#

I can, with the logging library

undone coral
#

with whose logging library?

west scarab
#

Unity's

undone coral
#

you mean unity's?

#

hmm

west scarab
#

It most likely won't work with microsofts

undone coral
#

what exactly are you logging?

#

what's the goal?

west scarab
#

Just general logging stuff?

undone coral
#

logging from a burst compiled job... you could easily wind up with logging taking 10,000x longer than the job itself

west scarab
#

It's not just jobs

#

Systems too

undone coral
#

it's not like unity's implementation is any good

#

alright well i'm sure it'll make sense

west scarab
#

It's probably as fast as it can be

west scarab
sage glen
# undone coral what is your objective?

There is a game server I already have a working connection and functionality to use with it for non-malicious reasons that even the CEO is aware of (or was, probably doesn't remember who I am by now). Instead of now using the actual game server, I want to emulate my own to a much more limited extent just for my own usage

undone coral
#

okay, so your question is, how do i communicate with a game server backend i have no control over?

#

which game is it?

sage glen
#

The client initiates contact, and when that callback on connect fires it sends the first higher level packet of info to start the login process

undone coral
#

based on the one line of code you shared, you are still at the beginning of a long journey

#

it is hard to say

sage glen
#

But on my own barebones server, the client doesn't get that invisible go ahead even though the server accepts the connection

undone coral
#

i see. so you're asking, "how to i author a correctly working tcp server in c#?"

sage glen
#

The client is basically finished and I can even use it on my phone

undone coral
#

what is the type of Client in your snippet?

sage glen
#

Tcpclient, though I also refer to the whole program that I can run, log into the game, and message people with

undone coral
#

okay

sage glen
#

The client is ready to go, but my attempt at the server can't get the tcpclient on the client program to fire the on connect callback even though the server accepts the connection and is waiting to read data from the stream

undone coral
#

this is an example of a feature already in aspnet core

#

are you authoring your server in c#?

sage glen
#

Yes

undone coral
#

your server isn't written correctly

#

we don't have to investigate that

#

as soon as you said you create the threads, you're taking a bad approach anyway

#

the thing i link is just a sample

#

showing how easy it is to set up a tcp server that is "enterprise grade" so to speak

#

your client looks dubious too, but that's okay

#

if it works it works

sage glen
#

I'll take a look, I use a thread so I don't need to use async and lock up the main unity thread waiting to read

ancient talon
undone coral
#

wait

undone coral
sage glen
#

No, separate process

undone coral
#

okay

#

just checking

#

so look at the sample i shared on github

west scarab
#

(not too uncommon with "playing" hosts though)

undone coral
#
namespace KestrelTcpDemo
{
    public class MyEchoConnectionHandler : ConnectionHandler
    {
        private readonly ILogger<MyEchoConnectionHandler> _logger;

        public MyEchoConnectionHandler(ILogger<MyEchoConnectionHandler> logger)
        {
            _logger = logger;
        }

        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            _logger.LogInformation(connection.ConnectionId + " connected");

            while (true)
            {
                var result = await connection.Transport.Input.ReadAsync();
                var buffer = result.Buffer;

                foreach (var segment in buffer)
                {
                    await connection.Transport.Output.WriteAsync(segment);
                }

                if (result.IsCompleted)
                {
                    break;
                }

                connection.Transport.Input.AdvanceTo(buffer.End);
            }

            _logger.LogInformation(connection.ConnectionId + " disconnected");
        }
    }
}
sage glen
#

I built the client and then run the server in unity for easier debugging

undone coral
#

@sage glen do you see what's going on here?

undone coral
#

so IS IT a separate process, or is it NOT a separate process?

#

you say run the server in unity

#

i wouldn't use that expression for thes ame process

#

do you mean you new Process() in unity, an executable you built elsewhere?

sage glen
#

The client works in the editor or as a standalone build on pc and on my phone I'm using now

undone coral
#

okay

#

i think you'll figure this out, sorry i can't be more help

sage glen
#

Yeah I'll check out the example l, there's probably a single thing I'm missing. Thank you zarameeYosiyosi

undone coral
#

none of it will transfer

sage glen
#

Yeah async

undone coral
#

but on the other hand, it will work 100% more lol

#

not just async

#

it isn't the async part that's essential

#

it's just... totally different conceptually

#

from a way you organize your code

#

to what you are concretely doing

#

anyway, if you told me what game it is, i could be more helpful

sage glen
#

I went with tcplistener since tcpclient worked for the actual game server

undone coral
#

but you didn't. it's not sensitive

sage glen
#

Apb reloaded

undone coral
#

okay

sage glen
undone coral
#

alright i think you'll figure this out

#

i have no special insights here

sage glen
#

All good, appreciate the help already nicethonk

tender hull
#

Does anyone have a trick for counting main thread allocations without resorting to the full-blown profiler window? I'd love to be able to directly instrument my code with a couple extra lines and ask "between point A and point B, how many allocations (and how many bytes) were allocated on the main thread?"

You could even imagine wrapping this in a unit test and saying "calling this function shouldn't allocate".

tender hull
quartz nymph
#

I'm getting the following crash report. I can't tell what the actual cause it. Is it FMOD or VFX? There seem to be a number of similar posts online but none seem quite right. Running 2022.2.8f1 but it was happening on older versions too.
See thread for stack trace.

livid dawn
#

Does anyone have any idea why my raycast appears to be hitting an object that is on an ignored layer? The lasers are all on the Laser layer.

#
Physics.Raycast(transform.position, player.transform.position - transform.position, out RaycastHit hit, myMask);
Gizmos.DrawLine(transform.position, hit.point);
autumn locust
#

what the myMasks value

livid dawn
#

um hang on, unity just crashed lol

lament salmon
#

Make sure that its a LayerMask not a Layer

livid dawn
#

it is

#

[SerializeField] private LayerMask myMask;

#

myMask.value is 14793

rich anvil
livid dawn
#

The first screenshot shows the selected values for myMask

#

Here is the full list

#

Here are the values for each layer

lament salmon
#

Are you saying that the ray is hitting the Laser layer?

livid dawn
#

It looks like it

autumn locust
#

get the hit collider to make sure, you can access its layer

lament salmon
#

Confirm with debug.log

autumn locust
#

bc the mask doesnt include the layer 9 afai can tell

livid dawn
#

print("Hit object: " + hit.collider.gameObject.name + "\thit layer: " + hit.collider.gameObject.layer.ToString());
Result
Hit object: Detection Laser (5) hit layer: 9

livid dawn
#

Hello?

#

Did everybody that was helping me just happen to log off at the same time?

#

Or is it just that nobody has a clue what is wrong with my thing?

mortal gust
#

Seems odd, are you sure you're checking the correct Turret object?

autumn locust
#

sry yeah i went off. everything looks okay so far. layermask seems to exclude the actual layer of the hit object, but its still the most likely point of failure

livid dawn
#

There are other turrets in the scene, but they have a range that doesn't reach the player at this point. I can disable all but this one and check again.

#

Yep, same result.

autumn locust
#

at this point i would write assertions

mortal gust
#

Log the object that hit with this result, click on the log to find it in the scene.

autumn locust
#

he did, its in the 9er layer

#

its something non-obvious

mortal gust
#

I mean something like

Debug.Log("My layer mask " + gameObject.layer, gameObject);

So he can confirm he's looking at the correct objects mask.

livid dawn
#

It hits two different lasers because they move back and forth but it's the ones I expect.

#

I had to modify your print to make it print the right things but I think it's doing what you wanted.
Debug.Log("My layer mask " + hit.collider.gameObject.layer, hit.collider.gameObject);

mortal gust
#

And inspecting those lasers mask also does not have the 9th layer of Laser selected?

livid dawn
mortal gust
#

No I mean their "myMask" variable.

livid dawn
#

Lasers don't have a myMask. Turrets have a myMask.

#

Turrets are the ones doing the raycast.

mortal gust
#

My bad, your log should not log the thing they hit, but the object that is checking.

livid dawn
#

oh

mortal gust
#
Debug.Log("My layer mask " + hit.collider.gameObject.layer, gameObject);
#

If they do, I would restart unity, and if that doesn't work redo their mask (set to everything, and then uncheck etc) 😅

livid dawn
#

I've restarted already. I started having this issue two days ago and have rerun it multiple times. It actually crashed an hour ago too after I started asking for help here lol. I'll try reselecting the layers tho.

#

It's acting like the laser is on every layer greater than water.

#

I unchecked everything and most of them it shows not hitting anything, but if any individual layer from 4+ it shows it is hitting the laser.

regal olive
#

Hey guys asked this question in beginner and general. Dont seem to be a response for it maybe someone here knows.

UnityEditor has the following functions to get and modify the animation curves

  • AnimationUtility.GetCurveBindings, AnimationUtility.GetEditorCurve
  • AnimationUtility.SetEditorCurves

Now my animations are all generated ondemand, in runtime because my characters have interchangeable body parts and rig.

I noticed there is no way in UnityEngine to:

  • Get animation curves for a clip
  • Set curves in bulk instead have to use a function called clip.SetCurve which does it singly and is REALLY slow....

Does anyone have any solution to getting animation curves for a clip without UnityEditor?
Does anyone have any solution for setting curves in bulk without UnityEditor?

livid dawn
tawny sand
#

in light of the fact that the masked setting on TMP text is known to be bugged and busted
is there a known work around?

undone coral
#

what is your objective?

#

you can also look at how the various model importers generate animation data. you are not familiar yet with the whole API

#

you can definitely create keyframe data "in bulk"

regal olive
# undone coral > Does anyone have any solution to getting animation curves for a clip without U...

In my case writing the data straight to a text file from editor isn't viable enough of a solution for me. As there can be a huge combination of animations which can be created from different body parts. I've put a image of the various unique models i have then the second image has these body parts combined randomly. Each 20 of the unique models on the left have base animations .e.g. Idle, Walk etc.....

When a combination of these meshes and rigs are combined, the relevant keyframe data from each animation needs to be copied and a new animation is made. If there are 8 body parts in the system there can be a possible of 8^N animations, not viable really for me to use text assets

#

The next best option i have is to dockerise unity editor and generate these animations in the cloud which i dont really want to do

#

:S

regal olive
#

My code works fine until i try to build then it throws Unity editor methods cannot find 😦

undone coral
#

what is the idea*

#

are you trying to use unity to generate video assets?

regal olive
#

So based on the combination of the meshes i have in the model i want to generate a new animation on runtime for .e.g. idle

undone coral
#

what is the end product? a unity .exe?

#

or a video .mp4

#

a unity webgl player?

regal olive
#

This is for a game, so the end product is webgl, exe, osx executable

undone coral
#

okay

#

Now my animations are all generated ondemand, in runtime because my characters have interchangeable body parts and rig.
what do you mean? are you saying you're generating keyframes for bones procedurally?

#

it looks like you have generated the models procedurally. however, they appear to be roughly the same size

regal olive
# undone coral > Now my animations are all generated ondemand, in runtime because my characters...

So yeah each of these models have animations.

.e.g. Idle, Run, Walk

Now i can mix and match these models....

.e.g. i make a new model with

  • Kitsune Head
  • Lucky 777 Body

Now what the code does is it gets the animation keyframes to copy from the Kitsune Idle animation (Head keyframes only) and Lucky 777 Idle animation (Body keyframes only) and makes a new animation and attaches it to the animation override controller

undone coral
#

it looks like they should all have the same avatar?

#

why are you copying animation keyframes

regal olive
#

because the idle animations are unique for each kitsu

#

and it was made by a game studio to be like this

undone coral
#

i am missing a lot of context here to be helpful

regal olive
#

So they can interchange parts

undone coral
#

this isn't going to be one of those things where there's just some api you're not aware of

#

the thing you're doing right now doesn't make sense

regal olive
#

I guess im not explaining it good enough

undone coral
#

no

#

i understand what you are trying to do

#

your approach sounds really bad

#

and the more i learn, the worse it sounds lol

regal olive
#

How do you think i should do it without creating a new animation 😐

undone coral
#

all of these characters are roughly the same. you can treat each customizable limb/body part/whatever as its own skinned mesh, bound to a single unified avatar

regal olive
#

hmm interesting

undone coral
#

it doesn't matter if each kitsune has its own idle animation

#

you would have 100x idle animation clips, sure, that's fine, they're all animated against the same skeleton

regal olive
#

the skeletons are also different

#

We only share some bones

undone coral
#

then you guys made a colossal error nothing bad has happened yet*

regal olive
#

Stuff like the head, ears, wings, tails are not shared

undone coral
#

well

#

there's lots of runtime retargeting approaches, specifically for this use case

#

but it's not really different

#

the skeletons can be slightly different sizes, and everythying will just work

#

your unified avatar should always have wing bones, regardless of the customized model. you don't HAVE to show the wing mesh

#

if there is really a one-off bone, like a specific tail, then that's duplicated out and treated separately

#

but the same concept applies

regal olive
#

hmm interesting so i would put all possible bones inside the unified avatar

undone coral
#

you can do whatever makes sense to you

regal olive
#

and only display a few

undone coral
#

the purpose of the avatar idea is to enable retargeting like this

regal olive
#

thanks doctor i will look into avatars

#

im a newbie to unity 😄

undone coral
#

i think you might want a more comprehensive tutorial

#

i don't know a lot about this either unfortunately

regal olive
#

not aware of the full systems yet

undone coral
#

@regal olive so to clarify, try to share as much skeleton as possible. for unshared stuff, make a new skeleton and avatar

#

mix and match skinnedmeshrenderer (i.e. body plan pieces). you will want to animate each piece against that skeleton. so you can imagine an arm just attached to that one skeleton

#

the whole skeleton hierarchy with the 1 body part geometry

#

the avatar describes how to interpret your 3d modeler bone hierarchy. it isn't that important / special in and of itself

regal olive
#

Thanks will do ❤️

undone coral
#

i think you're way closer to a working thing that you think you are

#

you're maybe a day or two away from having htis all work @regal olive

#

once you start to comprehend the meaning of all this animation rigging stuff

#

it will go fast

regal olive
#

nice hopefully a quick one i've done this multiple times just not in unity

distant tree
#

how can I prevent my graph view from clearing when I enter play mode

tender scaffold
#

Hey all, I have a question regarding running post processing during runtime
I have assetbundled some a bloom fx and I'm trying to use it in a game
I run the code

var pap = GameCameras.instance.mainCamera.GetUniversalAdditionalCameraData();
GameCameras.instance.mainCamera.GetUniversalAdditionalCameraData().renderPostProcessing = true;
var a = flowers.GetComponent<Volume>();
a.enabled = true;
var cs = a.profile.components;
Log($"length is {cs.Count}"); // length is 1
Log($"CS is {cs[0].name}"); // name is Bloom (clone)
Log($"Was able to get {a.profile.TryGet(out Bloom b)}"); // prints true
b.active = true;
b.threshold.value = 1f;
b.intensity.value = 1000f;

I get no errors but the object I wish to glow does nothing

#

This is unity 2020.2.2 if that matters

old swallow
tender scaffold
#

it's white

old swallow
#

then it wont bloom that much

tender scaffold
#

It blooms in the unity editor, but stops blooming in-game

old swallow
#

ah

#

does it bloom in editor Game Preview

#

and then stop blooming when you enter play mode

#

or is it never blooming

tender scaffold
#

Errr, it stops blooming when I instantiate the object from the assetbundle in the real game.
Now that I think about it, could it be because in the built version of the game, this isn't set?

#

If so, is there a way to set it outside of the editor?

pallid violet
#

can you have an event called from 2 different classes (same event name) so that the listeners can be called from either class?

old swallow
#

so if that is not an issue then the asset is working as intended

tender scaffold
#

Hmm then why else could it be doing nothing in the actual game. The sprite looks just fine except it doesn't bloom. And there are no errors.

old swallow
#

you could go around that by using (maybe) reflection or inheratance

pallid violet
#

but could you create an event with the same name in another class

tender scaffold
tender scaffold
old swallow
tender scaffold
#

It's because I'm modding a game.

old swallow
#

oh damn

#

now thats interesting

#

does the original game have URP

tender scaffold
#

No, I had to get the dll from a fake unity project I built. It doesn't give any errors when I use the URP functions so I assume I referenced the correct stuff.

old swallow
#

oof

#

then you are in a world of pain

tender scaffold
#

oh boi

old swallow
#

if the game uses buildt in RP the shaders will be incompatible with URP ones

old swallow
pallid violet
#

@old swallow i think i found a way to do it without duplicate events. Thanks for the help though!

tender scaffold
#

hmm, I'm actually trying to add bloom to a new asset, not one that's already in the game
but I guess the bloom affects in-game assets to so your point stands
is there a reason why it's not even turning pink rn?

old swallow
tender scaffold
#

Sprites-Default

old swallow
#

and full path?

tender scaffold
#

Sprites/Default
the one that comes with unity

old swallow
#

yeah ok so that shader is compatable with both Buildt in RP and Universal RP

#

but it was made for Buildt in RP

#

that is why nothing is ping in the game and editor

#

now the code you add (the volume stuff) is cind of just doing nothing

#

you add the components and change values

#

but at the end of the day URP volume just checks if the render pipeline is set to URP and if not (witch happens in the game) just does nothing

#

if you would force the game to use URP everything would turn pink because most Buildt in shaders dont work with URP

tender scaffold
#

Do I have any options?

old swallow
#

it would work, it would change the render pipeline, but I dont think you would like the outcome (pink world unless you change every shader in the game)

tender scaffold
#

Could I use the Post Processing package instead?

old swallow
#

yes

#

that supports Buildt in RP

#

and only Buildt in RP

tender scaffold
#

Ah well that's a relief I can try that.

old swallow
#

if we are talking about the same one that is

tender scaffold
#

my only problem with that package is that I can't get it to only affect one object

old swallow
#

at the end of the day you should have your modding environment the exact same as the game

tender scaffold
#

I make a layer for the bloom fx and add a Post-process layer component to the camera (this is all in the editor so far not the real game), and set the layer. And yet all the sprites, even the ones that dont use that layer still bloom.

#

Err but that goes outside this question. Anyways, thank you so much for the help, that cleared up a lot.

#

If I have questions on how to use the post processing package so it doesn't affect every object, should I ask here or #archived-code-general ?

old swallow
tender scaffold
#

oh 🥴
thank you

old swallow
#

but I will say that most ppl there are using URP PP now

#

might be tough to get an answer

tender scaffold
#

It doesn't seem like I have much of a choice unless I change every shader, do I?

old swallow
#

yup

#

and honestly if this is a 2D game I would just add the bloom effect in photoshop

#

would help performance too

tender scaffold
#

If I want a bloom effect that flashes, could that also be done with static sprites?
Well I guess it has to because that's what the base game does.

kindred tusk
#

You can set your bloom threshold so that only things with brightness greater than Color.white bloom

#

And then push various colors beyond that to make them glow

tender scaffold
#

Unfortunately it seems like I cant even get the post processing package to work.
When I add the Post-processing layer to the main camera, the following error gets spammed

[ERROR]:[UNITY] - NullReferenceException: Object reference not set to an instance of an object
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.AmbientOcclusion.IsEnabledAndSupported (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetLegacyCameraFlags (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetupContext (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
#

This happens when I run GameCameras.instance.mainCamera.gameObject.AddComponent<PostProcessLayer>().volumeLayer = 31;

tender scaffold
tender scaffold
#

alrighty

kindred tusk
#

I'd look into that null reference error

#

before any of the others

solar plank
#

my people
what counts as an advanced coding concept? /gen

kindred remnant
# solar plank my people what counts as an advanced coding concept? /gen

just my 2 cents, but:

in the context of this thread, I'd say just about anything that can't be reasonably googled or stepped through (or understood by someone with little experience). any question that is relatively common or has a google-able answer (i.e. "GetComponent is null!!!! why???") would be very much beginner

solar plank
#

:3
ty for an honest answer

kindred remnant
#

in general coding, it really does just depend on experience - i know devs who would call a concept advanced, whereas others who have been working for 20+ years would laugh at it

#

that's kind of the curse of being a human - everything seems advanced when you're learning, but everything seems beginner once you know (see: dunning-kruger)

solar plank
#

:3
thank you very much

kindred remnant
#

is there something in particular you had in mind?

solar plank
#

I was afraid that any questions I had for here would be looked down upon from mount olympus lol wheeze

#

yes

kindred remnant
#

it can't hurt to ask. people don't bite if they know you have done your due diligence. the only time you'll get that sort of attitude is if you're asking something that takes someone 2 seconds to answer and involves them writing your exact q on google

solar plank
#

I'm trying to refactor my code with the SOLID principles (trying to learn them at the same time, really I have no idea if I'm doing it right or not)
and I have this class that I want to be able to manage the selectable card objects on my screen by triggering their behaviors and stuff

but, I want to know where I should draw the line with how much complexity to allow in my selection logic class (because of single responsibility)

kindred remnant
#

you've kind of answered it yourself - you should draw the line when your class no longer serves it's single responsibility. i'd suggest posting your code and explaining where exactly you're considering splitting out the logic

#

it's v late for myself but if it goes unanswered i'll take a look tomoz

#

!code

thorn flintBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

solar plank
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SelectionLogic : MonoBehaviour
{
    private bool _selected; // whether selection behavior is currently active

    private Collider2D _currentHover; // current object under the mouse
    private Collider2D _lastHover;    // last object under the mouse

    void Update()
    {
        if (_selected)
        {
            if (Input.GetMouseButtonDown(0))
            {
                // Initiate DE-selection behavior
            }
        }
        else
        {
            _currentHover = MyNamespace.Selector.UnderMouse(); // gets the highest-rendered object under the mouse

            if (_currentHover)
            {
                if (!_lastHover || _lastHover != _currentHover)
                // Check if there was no last object or the object under the mouse is new
                {
                    // Initiate hovering pre-selection behavior
                }

                if (Input.GetMouseButtonDown(0))
                {
                    // Initiate selection behavior
                }
            }
            else
            {
                _lastHover = null; // "Forget" _lastHover if the mouse starts hovering over nothing
            }
        }
    }
}
#

(I've removed all the technical stuff to focus mostly on the logic for this question)

#

I just want to know, is this too much to be considered a single responsibility?

#

or is it fine?

kindred remnant
solar plank
#

(I changed the name of the class for the question as well, my apologies)

kindred remnant
#

what was it named before?

solar plank
#

original spaghetti code was named ToggleFollow
newest iteration is named SelectionManager which I realize isn't much better

kindred remnant
#

hmm

#

i don't see an issue, but with most of the code stripped out it's hard to say; all it's doing at the moment is reading inputs, which isn't unreasonable. an argument could be made that you should keep everything that registers inputs separate from classes that actually do stuff - so you could always separate things out that way

#

anyway, nothing too crazy going on here, it's not a monolith. i wouldn't worry so much about whether or not it's perfectly SOLID, it's not bad

solar plank
#

Thamk you

#

The reason I wanted to build this separately is because it's actually triggering events and stuff

#

But thank you for your time

brave orchid
#
public IEnumerator AnimateBubbleText()
    {   
        //text alpha starts at 0
        for (int i = 0; i < mainText.Length; i++)
        {
            //make i'th character alpha 255
            textComponent.ForceMeshUpdate();
            TMP_TextInfo textInfo = textComponent.textInfo;
            int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
            int vertexIndex = textInfo.characterInfo[i].vertexIndex;
            
            Color32[] vertexColors = textInfo.meshInfo[materialIndex].colors32;
            vertexColors[vertexIndex + 0].a = 255;
            vertexColors[vertexIndex + 1].a = 255;
            vertexColors[vertexIndex + 2].a = 255;
            vertexColors[vertexIndex + 3].a = 255;
            
            textComponent.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);

            yield return new WaitForSecondsRealtime(0.05f);
        }
    }

Can anyone help me figure out why this code produces this behavior? It's supposed to updated the alpha of each character to 255 and keep it that way.

distant tree
#

I have a serialized custom Action class (in a separate namespace so it doesn't cause problems with the built in action class) in a scriptable object and I'm trying to assign a value with a type of TestAction : Action. the variable is using [SerializeReference] but when I try to assign it it says theres type mismatch in the inspector. I'm doing a similar thing in a list (of a custom class which includes the same kind of serialized variable) and it seems to work fine, but outside a list it doesn't seem to work right. the value also doesn't seem to be showing up at all in the inspector (only variables in the base class) but it seems to be working fine otherwise so ig something about that is getting around the type mismatch problem

#

sorry if that wasn't very clear, im typing on my phone which isn't very good for long paragraphs like this when i can only see like 2 words at a time

undone coral
#

what are you trying to do

undone coral
undone coral
solar plank
#

I don't know how those work yet, I'm working on implementing actual C# events but I'll enlighten myself with google soon I'm sure enough

#

okay, googled it, not really interested in using something 40x slower that basically just serializes an event in the editor
humble me if you wish

quartz nymph
#

I'm having an issue where particle effects are waiting until they are on-screen to fire and a ton of them are building up and crashing my game. Does anyone know if there's a setting to fix this?

obsidian glade
west scarab
#

Why doesn't the UnityEditorConsole sink respect output formatting pensive

knotty sage
#

I'm trying to copy a material that uses compute buffers but it looks like when I call 'instantiate' on a material, it seem to mess up the compute buffer internal stuff somehow. On the mac it gives an error relating to these computer buffers (I don't have the exact error to hand), on the PC it gives no error but also fails to render.

#

does anybody know if there are issues with the shader/computer buffer interface ?

#

The mac error is 'requires a ComputeBuffer at index 4 to be bound, but none provided'

#

note that this works fine on a material created as an asset but if I try to create a material at runtime, it fails in this way.

undone coral
#

Culling Mode Choose whether to pause Particle System simulation when particles are offscreen. Culling when offscreen is most efficient, but you may want to continue simulation for off-one effects.

undone coral
#

"i want to use bloom in a 2d sprite game" ? for now, try creating a new scene, and right there in the editor, figure out how to show bloom the way you want first

#

using the postprocessing volumes in the scene, without code

tender scaffold
#

I have that already

undone coral
#

okay

distant tree
undone coral
#

and you're asking how you programmatically turn bloom on and off?

#

don't tell me the bug in your implementation

#

it's bad

#

we're going to get rid of it

#

tell me what you're trying to do @tender scaffold

#

what is your goal?

undone coral
#

there's no such thing as a serializable action

#

remove serializable, remove your scriptable objects. if you want to declare a behavior tree, for now, try to do it in code. here is an example:

class BehaviorTreeDefintions {
 public static BehaviorTree Patrol(Vector3[] positions, float speed) {
  var bt = new BehaviorTree();
  bt.AddState(new State() { ... });
  ...
  return bt;
 }
}
#

you will have like 20 of these max, and the thing you will not be editing is the actual code. you're going to be making changes to the paramters like positions and speed.

#

you don't want to program in the inspector anyway

#

you can make those changes in the editor

distant tree
#

-im not using unitys actions, this is a different namespace
-im not trying to use this in the inspector, im making this for a custom graph view window which uses this SO to save

undone coral
#

but whom is this for?

distant tree
#

im making this for my own projects

undone coral
#

based on this code snippet you've shared, you are at the beginning of a very long journey

undone coral
#

why code using graphs?

#

there is no value there

#

you already know how to program

distant tree
#

the code is in c#

tender scaffold
# undone coral what is your goal?

I want to make a sprite bloom and flash in the game. I already know how to change the bloom settings, I just want the bloom to at all show up when the game runs.
I need to edit during runtime because the in-game camera doesn't use post processing.
I already learned here that the project renderer needs to be set to URP. I know I can change this with GraphicsSettings during runtime but that still won't work because according to others here I will have to go through all of the game's shaders and make sure they are URP compatible.
So I decided to go with the Post Processing package instead since that uses the default renderer.
Again I got the bloom to work in the editor with Post Processing package.
But that lead to #💥┃post-processing message

distant tree
#

the graph will change how it's executed

#

if I wanted visual scripting I'd just use bolt

undone coral
distant tree
undone coral
undone coral
tender scaffold
#

yes

undone coral
#

okay

#

does the original game have URP
oh i see

distant tree
undone coral
#

none of this will work, sorry. you will have to figure out bloom another way

tender scaffold
#

Just because I'm curious, do you know why bloom wont work with the post processing package? That just uses the default render pipeline and I'm not getting any errors as far as not having the right dll files referenced.

undone coral
#

your best bet is to write an email to the developer and ask to add a postprocessing v2 component to the camera in unity

tender scaffold
#

Alright, is my only other option to figure out how to add bloom statically in photoshop?

#

Someone else recommended to draw it since it's a 2d game

undone coral
#

yes, you can create a bloomed version of the sprite and swap it out

tender scaffold
#

alright thank you

distant tree
#

heres the class for action data

[Serializable]
public class ActionNodeTreeData : NodeTreeData
{
    [SerializeReference] public NodeTreeData pass;

    [SerializeReference] public Action action;

    public override void Run()
    {
        if (action != null)
            action.Execute();

        if (pass != null)
            pass.Run();
    }
}
#

heres the other class thats working perfectly fine in the list i mentioned before

[Serializable]
public class ActionNodeGraphData : NodeGraphData
{
    [SerializeReference] public Action action;

    public string inputPortGUID;

    public string outputPortGUID;

    public override BehaviourNode CreateNode()
    {
        ActionBehaviourNode actionBehaviourNode = new ActionBehaviourNode()
        {
            GUID = GUID
        };

        actionBehaviourNode.Create();

        actionBehaviourNode.SetPosition(new Rect(position, Vector3.zero));

        actionBehaviourNode.actionObjectField.value = action;

        actionBehaviourNode.inputPort.GUID = inputPortGUID;

        actionBehaviourNode.outputPort.GUID = outputPortGUID;

        return actionBehaviourNode;
    }
}
undone coral
#

you should probably use a custom serializer to serialize graphs

#

and not use the unity serializer

#

[SerializeReference] on an Action doesn't make sense to me

#

because you wrote that, it makes me feel like you don't know what's going on

distant tree
#

thats what i was told to do when i came here before

undone coral
#

i think if you want to achieve this, there are existing behavior tree implementations

#

unless you specifically aspire to create unity editor tools

#

you are on a journey that is low ROI

#

graphs are not that valuable.

#

especially if you are a solo developer, and you already know C#

#

part of this journey, why i keep saying you're at the beginning of it, is ditching code

#

ditching this stuff and fighting the inertia of having a lot of code written

#

let me show you an example of inertia: https://github.com/weaveworks/eksctl/issues/5256#issuecomment-1130313683
here i am reporting a design flaw in a tool i use. i fixed it and used my fork in 15 minutes. i reported it may 13. because of inertia, a bunch of guys had these big conversations about how they are trying to avoid admitting they made an intellectual mistake. it took them until august 17th to fix it, which is 3 months

#

so i am telling you now, with no uncertainty, that the design of what you are doing is flawed, and there is a lot of inertia around the fact you have already written a lot of code and feel like you are close to the finish line

#

i mean this in a positive way

#

it's just about the why.

#

there's no why to having the graph

#

there are existing behavior tree tools

#

unless you specifically aspire to create unity editor tools

#

here's another perspective: Unreal engine has blueprints, and people use blueprints not because they are good but because C++ is so bad

#

do you know how many people with $0 budgets ship games with unreal? basically no one

#

you need a $250k budget to ship an unreal prototype

#

programming a game in unreal is essentially vaporware

#

every single person who has to make a game inside of unreal eventually has to become an expert in its peculiar kind of C++ development that vastly exceeds the expertise needed to master Unity's C#, so it's as though a game development SDK doesn't exist at all

#

so you don't need blueprints

#

you already know how to program well

#

you already have the superpower

#

you don't need to serialize graphs. you can express the graph in code if it's that important

#

it's not that bad

#

you don't need a whole authoring tool

#

lol

#

okay i don't know if i've persuaded you

#

i'm done

mortal jacinth
#

Is there an easy way to differentiate between None and Missing GameObjects?
I've found this post https://forum.unity.com/threads/how-to-check-if-a-property-is-missing-or-not-set-none.642919/ that implies that ReferenceEquals(gobj, null) should be true when gobj is None and false when it's Missing, but that doesn't seem to be true - it's false in both cases.

tender scaffold
undone coral
#

i would probably test it on your own project if you feel ike you have only one shot at this

distant tree
# undone coral graphs are not that valuable.

in most cases i agree and usually prefer sticking to code, however im working on a complicated character controller that id like to be very flexible, allowing for multiple characters with different behaviors without requiring u to rewrite the code for each individual character. I considered many option including state machines (and this solution isn't necessarily instead of state machines as I could still have other state machines within the graph, however in the way that this is a solution to the problem it does replace it), but decided that a graph would be a good solution for this. (i didn't actually know behaviour graphs were a thing before getting into this, im not surprised that they are since it wasn't a very revolutionary idea but the idea was reverse engineered from my specific problem).
im not sure if that explanation is satisfactory and i can elaborate if u want but im not sure if it really matters anyway...
as for the idea of expressing the graph in code I have considered this but there are a few reasons i decided against it:

  • it's a behaviout tree- it isn't just one linear execution of events, there are many branching paths of where the graph will go. trying to cram it all into a one dimensional list of instructions could work however it could get very messy.
  • i do plan to release the controller for others to use in their projects, most of them not having as much experience with c#. most of them can't even figure out how to install the input system so a bowl of spaghetti code definitely wouldn't be as friendly as a graph
#

anyway thanks for coming to my ted talk

undone coral
distant tree
#

clearly not

#

could u elaborate

undone coral
#

lol

#

you know a lot more about what you want to do than i do. in my experience, behavior trees are very useful for designing enemies in platformers

#

that's kind of the tradition they fit inside of

#

a lot of innovation in those games is in the level and npc design

#

the character usually behaves within a very narrow set of traditions. pretty much every 2d platformer authored by an indie game developer either has no meaningful complexity of movement (amanita design games) or it's megaman

#

and megaman explored this design space, it's very tightly coupled, it's almost 30 years old or whatever. to nail the megaman character behavior you need to write very tightly coupled stuff that a behavior tree, state machine, etc. - abstractions cannot conquer this

#

there are basically no solo developers developing games like overwatch, tf2, mobas inside of unity. they rely on engines like the warcraft 3 map editor to implement "spells." a really big design space. there's so so much engineering to support that design space. the WC3 editor, the roblox editor, hammer editor, etc. essentially have an in-game LISP that is disguised as an editor tool, and people like this, and they use it to program. it's not a graph, but it could be a graph, but it doesn't matter - the thing that matters is that the engine provides working multiplayer and graphics

#

roblox is also programmed in lua, and 14 year olds learn lua and it's fine, because the value is tied up in having working networked replication and correctness of rules

#

overwatch has a multi million dollar budget. if they want to explore the full team fortress 2 "FPS with spells" design space, they could do it literally however they want

#

they use literally everything. they have behavior trees, i'm sure, because one of their designers asked for it, and they have 1 billion dollars, so they delivered it

#

it doesn't mean that it makes sense

#

kinematic character controller in unity has figured out the 3d platformer tradition

#

and it's free now

#

2.5d corgi engine - i haven't even used it. i don't know if it nails the megaman movement

#

you give someone who doesn't know how to program a 2d platformer character and ask them to create an innovative movement, and they'll author a grappling hook. listen, it's been done

mortal jacinth
#

мб ты не будешь спамить в чат на целый экран в канале для помощи своей философией?

undone coral
#

@distant tree so on the one hand, it's a big goal. on the other hand, you don't really need flexible character controllers in practice. they are in fact in opposition to the real goals.

#

people don't want to explore the whole design space of 2d platformer character movement. that's just not the tradition. you give a player a character that doesn't move exactly like megaman does, they will just quit your game

#

flexible character controller makes it much harder to implement megaman movement

#

i've said this a lot of times in this chat because so many people want to do innovative 2d platformers

mortal gust
undone coral
#

you gotta put on your ludology hat and think what innovative 2d platformer really means, that's part of the journey.

#

especialyl if you want to author tools, which you do

#

you want other people to use this

distant tree
undone coral
#

i haven't personally tried to make a behavior tree coexist with a megaman character controller, where the behavior tree lets you implement extra stuff the character can do

#

i know that it is essentially not possible. you wind up leaking all the abstractions of the megaman character movement. as long as you want a working game that people actually want to play*

#

if you just want to explore concepts for movement, make a video.

#

you can watch that video and be like, "okay, hanging off of pipes this way is innovative"

#

but the implementation of that character is tightly coupled. there's no behavior tree there

#

someone who is going to do soemthing genuinely innovative also will learn how to program

distant tree
#

im not sure this is relevant to ur specific point but I think it'll help to give a little more context...

#

the character controller im working on is a 3d sonic the hedgehog character controller (however I plan to use much of the code in more original projects as well). the code for the actual character controller has already been done, I've just been exploring better ways to do it than my original approach of just cramming it all into a single script.
but sonic isn't a very simple character. you've got the spin dash, drop dash, homing attack, boost, and a million other abilities (especially if u plan to have multiple characters, which would add on another few million abilities) that execute differently depending on the state of the character
so i drew the logic out like this and thought "woah, it's a tree. maybe this will work well as a graph". and so I did a little research on similar things other people had come up with but I couldn't find anything that looked like it had what I needed, so i decided to try doing it myself, and here we are

undone coral
#

i see from your diagram that you already know all this stuff

#

but it's hard to abstract away the things that make this actually work

#

the sonic attacks are all very tightly coupled

#

you already know this! it's in your lived experience

#

actualyl you would gain al ot from looking at corgi engine 2.5d

#

which has to be all things to all people

distant tree
#

ur saying I should cram everything into a single script?

undone coral
#

and you would see that basically the developers author a specific script, in their framework, to implement a traditional 2d platformer movement

undone coral
#

if your goal is to make something correct and feeling good

#

i don't even have an opinion about big or small scripts, it misses the forest for the trees

#

i don't think i've had an opinion about that for a decade at least

#

it's not bad if it's one big script

#

sometimes that's just what it looks like

distant tree
#

actually one of the reasons I didn't stick to the single script thing was that i got a lot of comments saying it would be better to use a state machine or something and split everything up

scenic forge
#

Why not implement that tree, except instead of as an editor tree or whatever, just implement it as a tree in the code?

distant tree
distant tree
scenic forge
#

You seem to be talking about “one giant script” which is a code organization problem, yes technically ditching code completely will avoid the problem, but you could also just architect the code.

distant tree
#

im not ditching the code tho

undone coral
#

you know, not everyone is a john carmack

#

or whatever

#

they can't just mozart the code out of their head

#

they look at a big file and get scared

#

those people may still be really good at programming though

#

even though it doesn't really matter, people who use tools do care a lot about vibes

#

and it's funny because the quintessential actionable feedback is people's vibes

#

my opinion: those other commenters were giving their approach to dealing with the bad vibes of big script files

#

i don't know. i can't get inside their heads

undone coral
#

maybe their advice was wrong

#

they didn't Know

distant tree
#

organization wasn't the only reason, in fact my initial reaction was that it didn't really matter that much

#

the other problem is that when u want to include multiple characters it's more than just a script, u get functions that go unused for some characters and it gets really hard to work with. organizing the code like this (whether with a graph or with the same concept thru code) allows u to reuse functions between characters if u need to reuse them or only use them once if that's what u want

#

only reason it isn't just a list of functions u can assign in the inspector or something is because, like I said, it isn't just one dimensional logic

undone coral
#

unless you mean expanding the design space to "overwatch, but in 3rd person sonic controls"

#

which... is hard.

distant tree
#

much of their behaviour is the same

#

so u want to reuse the code instead of copying and pasting it for each character

#

but some of the code is different, so why have it in the same script that will be used for a character that doesn't use that code

#

so my solution was to have each function act independently, so it doesn't matter how many times it's used

#

the behaviour tree is just there to determine which functions to run. like I said, it could have just been a list if it were just one dimensional and didn't branch out

undone coral
#

Okay I see this specific perspective… but then why not configure it with bools

scenic forge
#

I’m only very loosely following the conversation so was pointing out that making it an editor one wouldn’t have much advantage over just code; if you are going to implement it in code then I don’t see much issue, maybe someone that have done it this way will have more insight.

undone coral
#

Once the graph is authored it will never be changed

distant tree
#

unless I don't understand ur point

scenic forge
#

Personally when I don’t have a clear picture of how things should be architected, an easy way is to just write it the simplest way that works without employing any design patterns. Once it gets far enough and repetitiveness shows, the correct design pattern becomes apparent and you can factor it then. This is very similar to the green and refactor phases of TDD.

distant tree
#

this is exactly what im doing

distant tree
distant tree
distant tree
#

anyway looks like the problem was that the scripts were monobehaviour which scriptable objects apparently cant serialize- or they can, since they were doing it in the list, but that seems to be unintentional

#

might be able to get around this by serializing them in a monobehaviour and passing that onto the graph which i should've done in the first place. the list thing kind of threw me off

terse cape
#

ARFoundation HumanBody tracking won't work on an iPhone X will it?

#

Tech too old?

livid dawn
#

How could I get the amount of change around a given axis between two rotations?

bronze lark
#

ECS: In a baker, I need to add the following Shared Components to all child entities of the GO being baked (it's not a prefab entity).

Baker says I can't do that: [Worker38] InvalidOperationException: Entity Entity(28:1) doesn't belong to the current authoring component.

        public override void Bake(BubbleAuthoring authoring) {
//....
            foreach (var child in GetChildren(true))
            {
                var e = GetEntity(child);
                AddSharedComponent(e, new BubbleGroup {value = bubbleKey});
                AddComponent<DisableRendering>(e);
            }

What's the correct practice to do this?

#

I tried adding a LinkedEntityGroup Authoring, but that also didn't work.

#

Wow, first time I really do not like Bakers, normally the pattern was really good, but for this case? Like, how is that even supposed to work now. 😄

bronze lark
#

Ok, I did the following, feels SUPER hacky:

 public class BubbleChildBaker : Baker<BubbleChildAuthoring>
    {
        public override void Bake(BubbleChildAuthoring authoring)
        {
            var parent = GetComponentInParent<BubbleAuthoring>();
            var group = new BubbleGroup {value = BubbleAuthoring.GenerateKey(parent.gameObject.name)};
            AddSharedComponent(group);
            AddComponent<DisableRendering>();
        }
    }

But it works, and since it's on a prefab I don't have to keep adding these.

wanton copper
#

I could use some advice. I had written some helper functions that would serve as no allocation versions of common Linq methods. (Where, Average, OrderBy, Count, etc)

I was aware of GetEnumerator and lambda expressions causing allocations, so I avoided those. I was not aware that passing an instance method also caused an allocation.

Consider the example code:

var count = CountNoAlloc(IsValid);

public int CountNoAlloc(Predicate<SomeType> predicate)
{
   // Do Work
}

public bool IsValid(SomeType type)
{
  // return true / false;
}

Is there a way I can call a common looping method without causing an allocation?

Or is there a known solution to this problem that I can leverage?

timid carbon
#

You can cache IsValid as a predicate and pass that into count

wanton copper
#

Are you saying the act of storing IsValid in a predicate variable is what is causing the allocation? So by setting it to a Predicate var I'm incurring that operation only once?

sly stag
#

Passing an instance method or lambda shouldn't cause any allocations, unless the method has some kind of closure involved

austere jewel
#

Instance methods allocated in the past, I'm not sure what version of C#/.NET fixed it to behave the same as a lambda

austere jewel
#

Actually, it's not so much instance methods as just methods as arguments vs lambdas. Instance methods involve closures to pass the instance itself

timid carbon
#

Closure will also allocate, this case is allocating on the heap to store the predicate

wanton copper
#

That helps me understand whats going on under the hood.

austere jewel
#

You could create overloads that took additional arguments to be used in the predicate, that way nothing is captured

#

There are lots of minimal alloc Linq libraries out there though

fresh salmon
#

Yeah as long as it needs to capture a variable from outside the lambda's scope, the compiler creates a whole class (sometimes struct for late .NET versions) and instantiates it. That's pretty much where most of the garbage comes from

wanton copper
#

@austere jewel I assume they'll have the same problem though.

#

regarding the other linq libraries (I'm happy to check out a recommendation though!)

austere jewel
sly stag
#

I focus more on minimizing allocations in bottleneck areas than trying to use a generic low-allocation solution across the board, personally

#

Keep in mind Unity's GC is (optionally) incremental, too, so some garbage creation isn't as much a problem as it used to be

plucky sparrow
#

Hey could someone help me with a Vector3Int?

#

Vector3Int SpawnHere = new Vector3Int((int)SetGridPosition.transform.position.x, (int)SetGridPosition.transform.position.y, 0)

#

I am trying to add that SpawnHere to this

#

I have been looking over it and I still can't figure it out

#

my two best guess would be

#

adding it to this line

#

or

sly grove
#

What are you trying to do

plucky sparrow
#

somewhere in this

#

I am trying to change the set position of tilemap grid that generates an island

sly grove
#

I don't understand, this is all too context-free

plucky sparrow
#

what the code does in short is procceduly generate an island on top of a grid

#

with

#

verts

#

I have gotten it to spawn the island fully

#

but when I try to find a way to move it to a new location

#

it doesn't move

#

I know it's not Falloffmap

plucky sparrow
#

(don't mean to sound rude)

sly grove
#

I don't understand why you're coming in with a line of code and asking where to put it, like a jigsaw puzzle

plucky sparrow
sly grove
#

If you're just trying to offset your noise map, you would just add the offset at the end right before spawning an object or placing a vertex or whatever you're doing

#

The code that you showed doesn't spawn anything

plucky sparrow
plucky sparrow
#

then after start calls a DrawTerrainMesh(grid);
DrawEdgeMesh(grid);

plush hare
#

Can someone tldr slip friction for me? In terms of vehicle physics? I completely understand how raycast suspension works and I've implemented sideways friction without any issues

#

I assume I'll have to model an actual "engine" and transmission for slip friction to work properly right?

undone coral
#

the industry trend right now is huge caches, so all the garbage allocation mumbo jumbo is about to get even less relevant

#

which, by the way, all those game engines that people relentless try to avoid garbage allocation in, they all benefit immensely from huge caches, they were not necessarily correctly optimized for real hardware in the first place

#

i'm not even going to speculate why because it requires a degree in CPUology that some random tutorial author on the internet is not going to have

livid dawn
#

!code

#

oh... ok

latent sorrel
#

hey guys i am struggling so hard setting up a database in unity does anyone have some suggestions? I tried mysql but the app for it was to much so i switched to firebase got around with the website easily but anytime i go to write code for auth functions it keeps saying my app is not found and ive re downloaded the sdk have the auth installed and my json for google

pastel geyser
#

Hi 🙂 I am trying to find a way to edit the 2d animation package to fix a known bug, but every change I make reverts. I've been searching how to edit Unity packages, and the best thing I have seen says I have to remove the copy the package and edit the copy, but that would break everything else even if it did fix my issue 😄 anyone have a direction for me?

pallid violet
#

@latent sorrel have you tried mysql?

whole juniper
#

Does anyone have any experience working with receiving software clicks/keyboard presses sent from Pynput to Unity?

daring pelican
#

So in Unity, interfaces are not serialized by default, right? However, we can get a component that implements an interface using GetComponent or serialize it using custom attributes or, for example, Odin. It seems to me that in terms of modularity using interfaces beats every other approach, so where's the catch? There must be disadvantages to it, other than it's not serialized by default?

latent sorrel
novel plinth
daring pelican
novel plinth
solar plank
#

(I wanna talk but just tell me when there's room for me to ask my question, I can wait and I see there's a conversation going atm 🥺)

#

Okay there hasn't been any messages for like 10 minutes sooo

#

I was on here yesterday getting help about making my selection logic class more solid

#

So I've realized that I can break it down more and I've basically gone from this first class to the new one

#
public class TestSelectionManager : MonoBehaviour
{
    // Whether an object is currently selected.
    private bool _selectionActive;

    // Transforms currently and previously under the mouse.
    private Transform _currentSelectable;
    private ISelectable _selection;
    private ISelectable _previousSelection;

    public delegate void Hover();
    public event Hover ObjectHovered;

    void Update()
    {
        if (_selectionActive)
        {
            if (Input.GetMouseButtonDown(0))
            // Initiate deselection behavior.
            {
                _selection.OnDeselection();
                _selectionActive = false;
            }
        }
        else
        {
            // Gets the highest Transform under the mouse according to sorting order.
            _currentSelectable = MyNamespace.Selector.UnderMouse();

            if (_currentSelectable)
            {
                _selection = _currentSelectable.GetComponent<ISelectable>();
                
                if (_previousSelection == null || _previousSelection != _selection)
                // Initiate hovering pre-selection behavior.
                {
                    _selection.OnHover();
                    ObjectHovered?.Invoke();
                    _previousSelection?.OnUnhover();
                }

                if (Input.GetMouseButtonDown(0))
                // Initiate selection behavior.
                {
                    _selectionActive = true;
                    _selection.OnSelection();
                }

                _previousSelection = _selection;
            }
            else
            // "Forget" _previousSelection if the mouse hovers over nothing so
            // the mouse can move away from and return to selectables.
            {
                _previousSelection?.OnUnhover();
                _previousSelection = null;
            }
        }
    }
}```
#

I took that and broke down ISelectable into ISelectable + IHoverable so the behaviors can be separate

#

and I tried breaking down TestSelectionManager into SelectionManager and HoverManager instead of having them both in one class

#
public class SelectionManager : MonoBehaviour
{
    private ISelectable _selection;

    public delegate void Selector();
    public event Selector Selection;

    public delegate void Deselector();
    public event Deselector Deselection;

    private void OnMouseDown()
    {
        if (_selection != null)
        {
            _selection.Deselect();
            Deselection?.Invoke();
        }

        _selection = MyNamespace.Selector.UnderMouse<ISelectable>();

        if (_selection != null)
        {
            _selection.Select();
            Selection?.Invoke();
        }
    }
}
#

I just want to know

Am I doing this correctly? Is this okay? I want to get into good/proper practices as fast as I can, so I want to know if I'm doing too much or still doing too little

remote drift
#

Anyone has any idea how ScriptableObjects work with Domain Reload and without it?
Do they get fully new instances of C# objects or are they reused?
I am particulary interested in InputActionsAsset, since I subscribe to it and I have my domain reload turned off.

novel plinth
#

I mean, you should dirtying the SOs anyway or else it won't get saved

remote drift
novel plinth
#

you're using the SOs to save some state while in edit-mode or nah?

remote drift
#

I use InputActionAsset because it has events for input

#

in runtime

#

and I wonder whether C# objects are reused

#

for SO

#

since without DomainReload I can potentially get same instance with dead event references

novel plinth
remote drift
#

🤔

tender solar
#

Hi. Got an advanced code question for the group. I am making a Command system for a turn-based game, which includes nested commands. Here's an example of one of my hierarchies:

{
    void Execute();
}
// This generates a path and calls...
class Command_MoveAlongSpline
{
    int NumberOfMovesMaximum;
    Command_SingleMove SingleMoveSubCommand;
    void Execute();
}
//... Which iteratively calls...
class Command_SingleMove
{
    bool PreserveFacing;
    void Execute();
}```
#

Problem is that right now if I create a new Command_MoveAlongSpline, I have to also give it a variable for PreserveFacing if I want the Command_SingleMove to reflect that setting.

#

I'm wondering if I can properly embed the subcommands into greater commands so I can do something like "var NewCom = new Command_MoveAlongSpline(); NewCom.SubCommand.PreserveFacing = true").

#

Ideally with the sub commands accessible through Inspector.

#

In addition, I would like to be able to clone the subcommand so I can configure it without it being changed for every other command instance.

untold moth
untold moth
untold moth
tender solar
#

Ah, that works. Now I need to figure out how to clone them.

#

The intent being that I can embed a Command_MoveToHero in another script, and copy it on each turn when running instead of re-using the same one every turn.

snow flint
#

hi guys, can you use the native C# parallel for each loop in unity? i tried it but i get this error Assertion failed on expression: 'gCurrentManagedTempMem != NULL'

flint sage
#

Should work but obviously it might run in different threads so most of Unity's api is off limits

snow flint
#

hmm ok, so only certain things will allow it

#

hi, sorry another question, i know you cant use reference types in a job struct.. but is there an 'easy' way to work around that?
InvalidOperationException: GetEnemyActionJob.action is not a value type. Job structs may not contain any reference types.

public struct GetEnemyActionJob: IJob
{
    public GridPosition gridPosition;
    public BaseAction action;
    
    public void Execute()
    {
        action.GetEnemyAIAction(gridPosition);
    }
}
flint sage
snow flint
#

i haven't i will try ty

regal olive
#

Each layer has a "Blank" animation which can be replaced once the meshes have been assigned. The Avatar masks nicely allow me to filter out the bones which should move in each layer

#

you dont need a avatar assigned to the animator when using avatar masks

velvet rock
#

Does anyone know why this might be throwing a cast exception?
Convert.ChangeType(registryInstance, iRegisterClosed)
So the registryInstance is a type that inherits the IRegister interface. They both are generic, and when I log the variables they match what they should be.
Levels.Universal.Experimental.IRegistery`1[UnityEngine.GameObject]
Levels.Universal.Experimental.RegisteryService`1[UnityEngine.GameObject]

#

But I am getting the error.
InvalidCastException: Object must implement IConvertible.

#

The classes for reference


    public interface IRegistery<T> {
        RegisterKey Key { get; }
        Func<IScope, string, T> Fufiller { get; }
    }

    public struct RegisteryService<T> : IRegistery<T> {
        private readonly RegisterKey _key;
        public RegisterKey Key { get => _key; }

        private readonly Func<IScope, string, T> _fufiller;
        public Func<IScope, string, T> Fufiller { get => _fufiller; }

        public RegisteryService(RegisterKey key, T instance) : this() {
            _key = key;
            _fufiller = new Func<IScope, string, T>((s, t) => { return instance; });
        }
    }
#

And the rest of the code leading up to the error.

            foreach (var service in Services) {
                Type ServiceType = service.Obj.GetType();

                Type exportOpenType = typeof(Exports<>);
                Type exportClosedType = exportOpenType.MakeGenericType(ServiceType);

                Type iRegisterOpen = typeof(IRegistery<>);
                Type iRegisterClosed = iRegisterOpen.MakeGenericType(ServiceType);

                Type registryOpen = typeof(RegisteryService<>);
                Type registeryClosed = registryOpen.MakeGenericType(ServiceType);
                ConstructorInfo registryConstructor = registeryClosed.GetConstructor(new Type[] { typeof(RegisterKey), ServiceType });

                object registryInstance;
                if (service.Obj is not GameObject) {
                    registryInstance = registryConstructor.Invoke(new object[] { new RegisterKey(service.Tag, ((Component)service.Obj).gameObject), service.Obj });
                } else {
                    registryInstance = registryConstructor.Invoke(new object[] { new RegisterKey(service.Tag, ((GameObject)service.Obj)), service.Obj });

                }
                MethodInfo registerMethod = exportClosedType.GetMethod("Register");

                registerMethod.Invoke(null, new object[] { _source, Convert.ChangeType(registryInstance, iRegisterClosed) });
            }
#

Ah my types would need to implement the IConvertible to work,,, would Castle.Core have an alternative way to cast to the interface without that, and without knowing the concrete(or what ever you would call this) type?

#

Or anyone know how to implement IConvertible for the above as the Microsoft document example calls the Convert.ChangeType method which seems like would cause a circle in calls.

mortal gust
#

Do you need to sync it? Does it have any logical effect?

#

You might need to send what your IK target/ targets position is. But if the IK is purely visual it should be able to calculate most from the state of the game?

#

Game state, e.g. positions, jumping, shooting, ammo etc.
Lets say you have an IK for your right hand to grab a mug of beer, that you can later drink to gain some stamina. Your game state will tell that you're grabbing the drink state, this is replicated. The state triggers an animation and sets your IK target to the beer mug locally.

potent shoal
#

I'm running code in a tick based controller, like so:

    public class TickBehavior : MonoBehaviour
    {
        public int currentTick;
        private CustomTime _time = new CustomTime();

        private float _tickTimer;
        private const float SERVER_TICK_RATE = 30f;
        public const float MIN_TIME_BETWEEN_TICKS = 1f / SERVER_TICK_RATE;
        public float tickDelta;

        public void Update()
        {
            _time.UpdateTimer();
            _tickTimer += _time.DeltaTime();

            while (_tickTimer >= MIN_TIME_BETWEEN_TICKS)
            {
                _tickTimer -= MIN_TIME_BETWEEN_TICKS;
                HandleTick(currentTick++);
            }
        }

        public virtual void HandleTick(int currentTick)
        {

        }
    }```
#

Because my player movement happens in HandleTick, the camera is very choppy.

#

I was hoping someone might have a few suggestions on what can be done.

dusty wigeon
#

And, is there a reason why you want a tick base controller ? I just hope you are not doing it to synchronise your Server and Client.

whole juniper
novel plinth
#

hope you get the idea here, I was putting it in italic so you'd aware what unmanaged territory means.. it's not a common api to be used in Unity in general and they're hiding it for a good reason

undone coral
#

you don't have to use unsafe to do this

#

🌈 that's allsunsmile

undone coral
#

what is your goal? there is a lot going on here

#

there are SDKs with this kind of stuff in mind. for example you might want to use Normal instead of photon. all of them have flaws.

whole juniper
#

I have a Python based Assistive Deivice receiving UDP packets and outputting Keyboard presses using Pynput. I was able to find a solution using Input System's Keyboard class

undone coral
#

this is sufficient for a working keyboard

#

and covers all the nuances

#

you will have to author your own Parse method obviously

#

does this make sense to you?

#

you shouldn't be using udp broadcast.

#

it will not work on most networks

#

but i think you are receiving from python, so it's all local

whole juniper
#

I appreciate the advice but I was only looking for a keyboard input method, I don't need this to pickup the UDP packets

undone coral
#

the udp packets from the device?

#

how does your python process communicate with unity?

#

it's
some hardware <--> python --> unity
right? is your idea?

whole juniper
#

The idea is just via keyboard presses via Pynput, and I was already to figure that out using the new Input System I was recommended above

#

Yes.

undone coral
#

so how does python communicate with unity?

#

the snippet i shared shows how to do keyboard-like events, but it's kind of nuanced so it's worth taking a careful look

#

I was already to figure that out
it might be a little premature to say that

#

there's also input remoting, which is harder to use but even more robust.

whole juniper
#

👍 thank you

undone coral
# daring pelican So in Unity, interfaces are not serialized by default, right? However, we can ge...

let's say you had a script

class TooltipController {
 public Tooltippable lookingAt;
 private bool hovering;
 ...
 void Update() {
  if (hovering) {
   Show(lookingAt.description);
  }
 }
}

then you can do

class Tooltippable : MonoBehaviour {
 [SerializedField] private string defaultDescription;
 public virtual string description => defaultDescription;
}
class UnitTooltippable : Tooltippable {
 public Unit unit;
 override string description => $"{unit.name}: {unit.hp}/{unit.baseHp}"
}
class ResourceTooltippable : Tooltippable {
 public Resource resource;
 override string description => $"{resource.name} ({resource.quantity})"
}

void OnHover(GameObject target) {
 tooltipController.tooltippable = target.GetComponent<Tooltippable>();
}

do you see how this makes interfaces redundant, and Just Works in the default inspector? and it doesn't use [SerializedReference] which is radioactive? and you can really easily customize what you want to do, intuitively? by dragging and dropping components onto prefabs, which is the easiest thing in the world?

undone coral
#

poorly?

#

with threads and like a bajillion lines of code?

#

@whole juniper the unity python package only works in editor

#

it doesn't work in a built player

#

so it's worth talking about this, before you find out you have a lot more work left to do

#

it sounds like you're using the unity python package

#

which won't work

whole juniper
#

I'm not using the Unity python package. Python scripts are being run separately as part of a different application.

undone coral
#

it sounds like your python program is writing to a text file the state of the keyboard, and the unity is repeatedly reading this text file

#

or maybe you are trying to start an http server inside of unity, and the python program is calling a URL on it?

undone coral
kindred remnant
mellow plinth
#

Is possible to enable burst on specific methods? Putting BurstCompile in a method doesn't show it in the Burst Inspector?

#

That only seems to show jobs...

#

Also, another partially related question. Is is possible to make methods with BurstCompileAttribute to call managed methods?

sly grove
#

Burst compiler only means anything in jobs, and jobs cannot call managed code

mellow plinth
#

But can I put BurstCompile in methods which aren't from jobs?

#

I read it's possible, but I don't find those methods in the Burst Inspector.

undone coral
sage radish
mellow plinth
#

Ahhhhh, I wasn't adding the attribute to the class

#

I thought that adding to the class was the same as adding the attribute to each method

sage radish
#

It's set up that way so Burst doesn't have to check every method, increasing your compile time.

mellow plinth
#

Make sense

kindred remnant
undone coral
#

that approach has existed for decades, it's basically the delegate field in all the apple objective-c frameworks

#

the annoying thing about interfaces in your example is that you wind up using the methods as a form of type system

#

which is very clunky

#

you would want all that clunk to live in ItemInteractable

#

you wind up needing to put code somewhere that isn't in the method IInteractable declares; or, you have to if (interactable is Character character) to extract the character field somewhere

#

with CharacterInteractable : Interactable { public Character character; ... }, you have all the stuff you need in the script and it stays out of the way

#

and GetComponent<Interactable> Just Works

undone coral
#

👀

#

the prefabs are already "a collection of traits". components are already the business part of interfaces

#

however, if i was a plugin author, i'd do BaseInteractable : IInteractable, and everywhere in my API, i would expect an IInteractable

#

because sometimes people want more power

kindred remnant
#

ahh

#

cool, yeah that makes a lot of sense. thanks!

solar plank
#

hey there fishyfred! :>

#

I thought about pinging you with my progress but didn't know if you were good with pings or not

#

I tried separating my class into 2 classes (and the interface into 2 interfaces) to manage hovering and selecting separately

#

but now I've run into a problem - I can't pause hovering whilst selection is active, but I'd like to do that
the way that I see a remedy whilst keeping the classes separate is making an intermediary class that enables/disables the hover manager class as necessary
but is that bad practice?

kindred remnant
#

disclaimer: im not the best to ask for this

it's hard for me to say without seeing what you mean, but my gut feeling is that you're not seeing when it's appropriate to separate things out into another class. if you need an intermediary class to allow 2 classes to do a relatively straightforward job, you're introducing a lot of coupling for not a lot of benefit

#

so yes, bad practice to introduce more classes for that example, since your hover and/or select classes should be able to expose what they need to to work correctly

potent shoal
dusty wigeon
#

Anyway, you did not answer the original question which is: Is your camera a child of your player ?

thorny whale
dusty wigeon
#

In my experience, the camera is sluggish because there is a disconnect between the movement of the player and the camera which result in a non-constant movement between the rendering of the frame. I've experience such issue with using FixedUpdate for the movement of my character. My solution was to take the camera out of the hierarchy of the player and use a Lerp to smooth the movement.

ancient talon
velvet rock
#

Likewise the body should never have a new position between the end of LateUpdate and the start of Update(atleast rendered).

cerulean scaffold
#

Hi everyone, is there a way to change the formatting of logs in the logging file Player.log?

#

I would also be interested if it's possible to omit this timestamp from the editor logs

#

never mind, I think I'll just use #if UNITY_EDITOR and change the formatting that way

dusty wigeon
# ancient talon Have you try using LateUpdate()?

In my case, my player had to be in the FixedUpdate because it was driven by the physics. Using LateUpdate or Update was potentially causing issue such as inconsistent amount of force applied to the body. This issue can be seen whenever the frame rates are asymmetric.

By example:
If you want to add a force in function of the distance of an object that is physic base.
If you use the Update function you may have 2 Update calls for 1 FixedUpdate calls
Those 2 Update calls will use the same position
Resulting in the same amount of force applied
Instead, the second Update should have used the modified position that result from the first Update
Which could have and probably would have result in a different amount of force

But like I said, the solution was to move the Camera outside of the player and move the camera independently from the player in a smooth manner.

worthy lodge
#

Mesh slicing triangle intersections

drifting hawk
#

I have one externall dll that is not compatible with skip reload domain, anybody has figured out way to force reload of single assembly or is it always all or nothing?

austere summit
#

Hi guys! What is the best way today of culling UI elements. I want to disable UI element gameobject when it outside of scroll view.

undone coral
undone coral
drifting hawk
#

I cannot do that, as said, its external dll which is not to be distributed

undone coral
drifting hawk
#

author will fix it eventually but was looking easy fix meanwhile

dusty wigeon
austere summit
regal olive
#

can i use c# 11 in unity?

north fossil
#

Does anyone have any suggestions on how I gracefully strip a monobehaviour's values in a build but keep it in-tact in the editor? If I strip out values using UNITY_EDITOR then I get in an error in runtime saying
A scripted object (probably xxxxxxxx) has a different serialized layout when loaded. Read (32 bytes) expected (208 bytes). Did you you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?

#

The reason why I want to strip out values in a build, is that I don't want to bring in debug-only data into the build

#

I could have two separate scenes, one for builds and one for use in-editor, but that's a headache

sly grove
crystal parrot
#

Is ecs slower than MB for large amount of static geometry?

#

Hybrid renderer v2

north fossil
sly grove
#

return a List, Array, or IEnumerator, or any other collection

#

I mean your return type is already an array

#

so return an array

#

loops are not objects

#

they are control structures

#

however

#

C# does have iterator methods

#

where you can do:

for (blah blah ) {
  yield return xyz;
}```
#

99% sure you just want return item; in your case though

undone coral
fathom locust
#

I'm in a bit of a tangle here with some async stuff. I haven't had to do much of this so I'm a little rusty.

I'd like to create a task or async operation that allows me to load up a bundle of scenes (one main one and a bundle of additive ones), and check progress on them via this "parental" task/operation. How might I go about doing this?