#archived-code-advanced

1 messages · Page 196 of 1

nimble lynx
#

Well USD is a cached data format, so you can directly render it using USD Hydra Delegates. But you can also render it by converting to any other format one possible format can be a unity asset. So, I am curious if Unity can render USD natively or does it convert it before rendering

#

If it converts it, is there any plan to support USD natively like Maya or Houdini or some proprietary game engines?

undone coral
#

you haven't really expressed your goal. suppose unity could delegate out rendering the layers from maya or houdini. and suppose it could composite the render layers correctly, somehow, with some kind of compositor compatible renders from its own cameras. then what? it wouldn't be real time

#

so if i were you @nimble lynx i wouldn't stress too much about the USD format. you should export whatever it is you want to use in unity to FBX, and set up the materials in unity

nimble lynx
#

The project is confidential, and I can't share much. We can only use Unity if it supports our USD-based pipeline. I got what I needed for now. Thanks for your help!

undone coral
inland prairie
#

Does it matter where I declare my variables in regards a loop and the garbage that could be created?
For example this:

while (true) {
    var x = 1;
    // do something
}

versus:

int x;
while (true) {
    x = 1;
    // do something
}

My intuition tells me the second one would generate less garbage and less memory allocations but Im not sure if Unity is doing some optimization when this is compiled

austere jewel
#

it's happening on the stack, it doesn't matter

inland prairie
#

I was asking this because I tried to optimize it but re-sharper complained

#

so that made me suspect it didnt really matter

#

thanks for confirming

orchid marsh
austere jewel
#

Under extremely tight loops you might get some performance gains by moving stuff like this around, but it's also highly dependent on the system it's running on, how the compiler decided the code ought to be moved around, so it's kinda useless to look at—there's almost always going to be better things to focus on, and memory on the stack doesn't contribute to GC, and is super fast

undone coral
#

is it possible to build unity windows standalone il2cpp with clang instead of msvc?

#

also, is it possible to get the c++ files from a windows build step

#

instead of going straight to compilation?

#

just like with ios builds?

misty glade
#

i've never opened them though, i'm assuming they're obfuscated (unintentionally) .. like hard to read methods and stuff

#

and there's a bajillion of them

#

(that's on "light" code stripping)

boreal yarrow
regal olive
#

Will this ricochet system work with movement of bullet based on velocity?

dusky carbon
#

the code to change its trajectory looks right. I'm not sure whether or not you are preserving its velocity with the physics system or if it is losing it in the collision

regal olive
#

so i need to use trasnform

dusky carbon
#

I literally have no idea, sorry

regal olive
#

ok

regal olive
#

Hello. I am trying to replicate the mechanics of Fez. The catch is that the character is in a randomly generated world. How would I do this? I am thinking of first pulling of the mechanics (Which I am most confused about) and then making the world generation a thing in a voxel enviroment.

regal olive
#

Bump

flint sage
#

The answer to your question is about the length of a book

#

And your question is also not very clear

regal olive
devout hare
#

multiple books, in fact

flint sage
devout hare
#

you need to split the project into smaller parts and then research or ask about specific things

regal olive
buoyant vine
#

just make it 3d

#

easiest approach from what ihave seen

flint sage
#

You don't just "pull" off all the mechanics in the game, first get a character walking and implement things in tiny little steps

dusky carbon
#

and ortho camera?

regal olive
agile grove
#

can someone explain to me what is Accelerometer Frequency? and for what it is used?

dusky carbon
mint sleet
#

Hello folk!

#

I have this api that retrieves the whole information from the db.

#

but I'm won't use all the information in the records, just id and org name would be fine

#

Would it be fine if I omit those fields not necessary for my purpose?

flint sage
#

In what

mint sleet
#

in the response object

#

I have a lot of field coming as a response, which are unnecessary for this API call

flint sage
#

You mean the object you deserialize to?

mint sleet
#

No the JSON is sent by the server

flint sage
#

If you control the server then just send whatever you want

#

As long as your client handles it properly

mint sleet
#

yes but I'm trying to understand the best practicies.

#

in terms of security, I have heard that I must get the data that I need only. But

#

in another scenario, I will need to have those values as well

flint sage
#

If you want best practice advice then you really need to provide more context

mint sleet
#

hmm. Sure.
I have organizations and courses, and I will add a course to multiple organizations at the same time. to do so, I created a OrganizationsCourses table

#

this stores the data of 'courseId', 'orgId' and, 'Id' (incremental)

#

and I have this API above (Get all organizations)

#

and the API for a course that was owned by organizations.

#

so in frontend I call this API to get all the organizations and visualize them.

#

as a result, I put some checkboxes next to the courses and those checkboxes are true if the course is assigned to that organziation.

#

API will delete all records and put the new values into the database when I make the call.

#

The question arises here.

#

Should I remove unnecessary field from my response JSON so it will be clean and properly in terms of security

flint sage
#

So, it's probably not that big of a deal since it's pretty insignificant data either way, if you were including PII data in those requests then you don't want to query the PII data if you don't need it

#

It sounds like, based on your description, that you can just cache the data initially which makes it so that you don't have to make multiple requests

#

There are also some solutions like GraphQL which let you specify which fields you want in your request

mint sleet
#

hmm.

#

have heard about GraphQL but never used it.

#

understood to the point btw,

flint sage
#

It's probably overkill for what you need

mint sleet
#

if it is not a sensible data the we are good to go

#

Thanks Navi!

quartz stratus
#

Is it possible to embed a Unity application inside a second Unity application as a library? Sorry for asking a let me Google that for you question in code-advanced but just wanted to see if anyone knew off the top of their heads.

undone coral
#

it was designed iteratively depending on the puzzle

#

i think he might also be on a foreground layer sometimes

#

it sort of does it all

#

like on a separate layer from the 3d world

#

you can also email the guy and ask

rain wolf
#

👋 Howdy all. I'm new here (so apologies if this is the wrong place). I'm attempting to add a Source Generator to a Unity project that needs access to some Additional Files (which are normally specified in a csprojfile, e.g.: <AdditionalFiles Include="Foo/Bar/*.asset" />). Is this a thing that is possible at all, or is there some other workaround?

undone coral
rain wolf
#

@undone coral so, i've dug through there and didn't see the answer to my question. Am I missing the part about configuring additional files?

#

(or a bit that says "you can't do that, manually use System.IO", or something?)

undone coral
rain wolf
#

oh shoot. this looks great.

#

tyty

#

i think that project is exactly what I need. But: i'd still love to hear if there is a "recommended way" of generating source files from asset files that i've just missed. I'm basically trying to follow this cookbook example with Unity Asset files: https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#additional-file-transformation

GitHub

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs. - roslyn/source-generators.cookbook.md at main · dotnet/roslyn

misty walrus
#

I have this class:

public class PlayerHand<T> : LinkedList<T>{
          private bool IsItemMatching(T component)
        {
            component.Equals(First);
        }
}

Also this extension method i've ripped from the internet:

        public static int IndexOf<T>(this LinkedList<T> list, T item)
        {
            int count = 0;
            for (LinkedListNode<T> node = list.First; node != null; node = node.Next, count++)
            {
                if (item.Equals(node.Value))
                    return count;
            }
            return -1;
        }

And i'm using both of these on a class with this override:

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(obj, null)) return false;
            if (ReferenceEquals(this, null)) return false;
            if (obj.GetType() != GetType()) return false;

            return ((GameTile) obj).tileType == tileType;
        }

Is there a way for me to change that extension method so instead of equality it checks whether they're identical.

sly grove
#

Why?

misty walrus
#

sorry i sent that too soon

sly grove
#

object.ReferenceEquals(a, b) will check for objects being the same object in memory

misty walrus
#

well i'm dumb... and i even had it on my equals override, thank you.

timber flame
#

Do you agree using enum values and implement logic based on these values is not a good approach?
If the values change, logic in somewhere in the code will be totally wrong

// Do not change the values never ever!!!
public enum RotationType : byte
     {
         Rot0 = 0,
         Rot90 = 1,
         Rot180 = 2,
         Rot270 = 3
     }
uvs[(j+(byte)rotationType)%4]
#

My way is to define Enumeration class with explicit field index for example.
What is your opinion?

 public class RotationType : Enumeration
   {
        public static RotationType Rot0 = new RotationType(0, 0, "Rotation 0");
        public static RotationType Rot90 = new RotationType(1, 90, "Rotation 90");
        public static RotationType Rot180 = new RotationType(2, 180, "Rotation 180");
        public static RotationType Rot270 = new RotationType(3, 270, "Rotation 270");
        //...
   }
sly grove
#

Seems a little overkill

sage radish
#

I've made enum classes like this before, but they are limited. Because the values aren't constant, you can't use them in switch, which is pretty bad.

sly grove
#
public enum Rotation {
    Rot0 = 0,
    Rot90 = 1,
    Rot180 = 2,
    Rot270 = 3
}

public static class RotationExtentions{
  public static int Degrees(this Rotation r) {
    return (int)r * 90;
  }
}```
undone coral
twin vector
calm ocean
#

Is the only way to call a constructor from another constructor in curly braces by making an initialize method?

calm ocean
hollow garden
#

show what you mean

calm ocean
#
public DisplayNameBody(string[] inputs)
  {
    if (inputs.Length == 4)
    {
      Initialize(inputs[0], inputs[1], bool.Parse(inputs[2]), float.Parse(inputs[3], CultureInfo.InvariantCulture.NumberFormat));
    }
    else if (inputs.Length == 3)
    {
      // skippable is false
      Initialize(inputs[0], inputs[1], false, float.Parse(inputs[2], CultureInfo.InvariantCulture.NumberFormat));
    }
    else if (inputs.Length == 2)
    {
      // no autoskip and is skippable
      Initialize(inputs[0], inputs[1], true, -1f);
    }
  }

  private void Initialize(string dialogueName, string dialogueBody, bool skippable, float time)
  {
    this.dialogueName = dialogueName;
        this.dialogueBody = dialogueBody;
        this.skippable = skippable;
    this.time = time;
  }
#

I have a class that takes in an array of strings as input

#

Depending on the contents of that array, I would like to call a different constructor

#

Instead of "Initialize", can I use a constructor?

#

Right now all my constructors just the arguments into Initialize

hollow garden
#

there's probably a way to call the constructor again with reflection but you should probably just include the Initialize method, yeah. ```cs
public class MyClass {
public int value;

public MyClass(int value) {
this.value = value;
}

public void Initialize(int value) {
this.value = value;
}
}

calm ocean
#

I see, thanks

twin vector
#

ah, i see what u mean now, yea i'd agree w Tecci just to keep it

#

u can clean up the constructor if u want tho

public DisplayNameBody(IReadOnlyList<string> inputs)
        {
            switch (inputs.Count)
            {
                case 4:
                    Initialize(inputs[0], inputs[1], bool.Parse(inputs[2]), float.Parse(inputs[3], CultureInfo.InvariantCulture.NumberFormat));
                    break;
                case 3:
                    // skippable is false
                    Initialize(inputs[0], inputs[1], false, float.Parse(inputs[2], CultureInfo.InvariantCulture.NumberFormat));
                    break;
                case 2:
                    // no autoskip and is skippable
                    Initialize(inputs[0], inputs[1], true, -1f);
                    break;
            }
        }
calm ocean
#

Not a big fan of switch statements because of the breaks

twin vector
#

ah

calm ocean
#

There also mnight be instances where the lengths are the same but the types are different

sly grove
calm ocean
sly grove
#
public class Example {
  public Example(int x, int y) {}
  public Example(int x) : this(x, 5) {}
}```
twin vector
#

Hot take here since many disagree w this but when i do if else statements and its only 1 call
I prefer to do

if (something)
  DoSomethingElse();
else 
  DoSomethingEntirelyDifferent();

similar to

if (!something) return;
// or 
if (!something)
  return;
#

constructor overloading is what Praetor is doing

calm ocean
#

Since I would like to do some logic before calling the other consturctor

sly grove
#

it must be the first thing called

calm ocean
#

I see, so it's like Java

sly grove
#

Similar to-- yes exactly

calm ocean
#

Seems like Initialize is the only way

sly grove
#

Just different syntax

torpid sky
#

Does anyone have advice on how to structure code in Unity projects so it doesn't become a huge mess of spaghetti instantly?

sly grove
#

Organize it into folders and namespaces. When it gets big enough you can even break it up into multiple assemblies

somber swift
torpid sky
#

the issue is that standard OOP doesn't seem to map well to Unity scripts

sly grove
#

Unity is a GameObject/Component architecture

#

you should not be relying heavily or primarily on inheritance/polymorphism

#

focus more on composition of components

somber swift
#

Yeah thats true. Things like interfaces can still make huge difference to your code cleanness

torpid sky
#

I mean you often have to deal with lots of components and concerns at once (for example: Input, Physics, AI, all in one function) and it gets messy for me.

#

I'll just give an example I just wrote

#
    private void HandleInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100,
                Physics.AllLayers, QueryTriggerInteraction.Collide))
            {
                var healthComponent = hit.collider.GetComponent<HealthComponent>();
                if (healthComponent != null)
                {
                    // Attackable.
                    SelectTarget(hit.transform, healthComponent);
                    destination = target.position;
                }
                else
                {
                    UnselectTarget();
                    destination = hit.point;
                }
            }
        }
        else if (Input.GetMouseButtonUp(0))
        {
            UnselectTarget();
        }
        else if (!hasTarget && Input.GetMouseButton(0))
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100,
                Physics.AllLayers, QueryTriggerInteraction.Collide))
            {
                destination = hit.point;
            }
        }
    }
#

this is really messy imo but I don't see a way to make it any simpler

#

it's Diablo 2-like click to move/attack

#

or maybe I'm off-base

#

maybe this is not that bad ^^

somber swift
sly grove
#

honestly doesn't look that bad to me

#

you know you don't need to declare RaycastHit hit; in its own line?

#

out RaycastHit hit works inside the parameter list

#

I'd also recommend TryGetComponent instead of GetComponent for a cleaner way to check for that component

#
                var healthComponent = hit.collider.GetComponent<HealthComponent>();
                if (healthComponent != null)```
becaomes
```cs
                if (hit.collider.TryGetComponent(out HealthComponent healthComponent))```
torpid sky
#

ah I didn't know that one thanks

somber swift
torpid sky
#

alright thanks ^^ good to know it's readable for other people

#

I figured it'd be hard to understand what's going on here if I had to look at it again in 2 weeks

#

but I guess you can't always avoid that exactly

#

actually nevermind it's quite simple

#

I don't know why I'm stressing so much

#

when I write code in non-game projects, I often don't need that many branches/indents, and rather early return etc.

#

makes stuff easier to read imo

misty glade
#

i have recently aimed for the "don't use else" thing and I really love it

#

it's obviously just a stylistic thing but i really just like that my code has become, in general, much less indented overall

#

hot take: style

#

if & return on same line 👀

regal olive
#

How can I check if an action is going to happen? Let me explain.
Okay, so, I have this 3D rotation system (like Fez), and I want the player to not be able to rotate if the player is going to fall when rotated. How would I do this?

sly grove
#

it really depends on the details of your system

regal olive
#

Let me record a video (and send the code if wanted)

regal olive
sly grove
#

So it's just 3D physics the whole time?

regal olive
#

Yep

sly grove
#

You could basically copy the scene into a separate physics scene - rotate the level there and do a raycast

#

or boxcast/capsulecast

#

and see if there's anything below the character

regal olive
sly grove
#

Could also just rotate the level - sync transforms - do the raycast/boxcast - then rotate it back - sync transforms again

#

without anyone being the wiser.

#

if that works it's simpler than introducing a separate physics scene

regal olive
sly grove
#

why>?

#

You would do everything within a single frame

#

by the time the frame renders everything is back where it belongs

#

there would be nothing to notice

regal olive
#

Oh alright

#

My current code is ```csharp
IEnumerator TurnLeft()
{
var fromAngle = cubes.rotation;
var toAngle = Quaternion.Euler(cubes.eulerAngles + (Vector3.up * -90));
for (var t = 0f; t <= 1; t += Time.deltaTime / 0.8f)
{
cubes.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
yield return null;
}
cubes.rotation = toAngle;
rotating = false;
}

IEnumerator TurnRight()
{
    var fromAngle = cubes.rotation;
    var toAngle = Quaternion.Euler(cubes.eulerAngles + (Vector3.up * 90));
    for (var t = 0f; t <= 1; t += Time.deltaTime / 0.8f)
    {
        cubes.rotation = Quaternion.Slerp(fromAngle, toAngle, t);
        yield return null;
    }
    cubes.rotation = toAngle;
    rotating = false;
}
sly grove
#

yeah you'll need to make a method that rotates it instantly for this

regal olive
#

alright

sly grove
#

pseudocode:

TurnRightInstantly();
Physics.SyncTransforms();
bool mayRotate = PlayerPositionIsValid(); // do the raycast in here
TurnLefttInstantly();
Physics.SyncTransforms();

if (mayRotate) {
  StartCoroutine(TurnRight());
}```
regal olive
#

Makes sense...

#

What is SyncTransforms though? I've never heard of that

sly grove
#

When you move objects via the Transform, those changes don't get synced to the physics engine instantly

#

it will get synced only during the next physics simulation step (FixedUpdate basically)

#

If you want to do raycasts for example against the new state of the world after moving something without waiting, you need to sync it manually

regal olive
#

Now uh, another question

#

I am kind of not good at raycasting

#

Hm, maybe not

#

I'll figure this one out myself

fluid jetty
#

Yo! Does anyone know of any .net core networking libraries that let you make an async websocket (tcp/ssl) server? I want to make a server for a webgl client game. I want to write it in C# and not nodejs/etc because I want my client and server model to share core classes for communication.

#

I've looked for a couple of days but I can't find what I'm looking for. I might just be really bad at using google, Lol

dusky carbon
#

example code seems to dispatch requests asynchronously

#

SignalR looks like it would be good for game communication.

regal olive
#

I want my player to be able to jump up to the top platform from the bottom platform

#

Here's how it looks in 3D space

#

Oh, btw, I've change the 3D Rotation code so that only the camera is rotated, and not the whole level

#

Bump

misty glade
#

(i'm also using MessagePack for C# to serialize the messages into tiny little byte streams)

fluid jetty
#

so unfortunately no it would not be viable

misty glade
#

Ah, didn't know that

#

A quick google on it gave me a little bit of a finger-wagging too:

Short answer No. I would simply close this as a duplicate of the many times this has been asked here before, but the answers elsewhere are surprisingly poor. The security problems are rather over-stated - it would be trivial to prevent amplification attacks that have proved troublesome with DNS and NTP. The reasons I am aware of are that 1) its not needed for most of what a browser does currently 2) its very difficult to implement across the internet due to NAT.

#

it'd be nice if there were an analogue to rUDP for TCPIP, there's some nice features in it. The guy who wrote it actually was hired by Unity to work on their networking stack MLAPI, so maybe you'll have some luck checking that out, I haven't seen their progress in the last few months. I know they have a discord going, if you're not already in it

fluid jetty
#

i'll check out the MLAPI library

#

though it'd be nice if i could find a framework that gives me control over lower level protocols while not forcing me to reinvent the wheel for everything

misty glade
#

right? there's a lot of sweet features in rUDP.. hashcash challenges, connection pooling, fully managed so building isn't a pain in the ass, MTU for large datagrams, etc

#

If I knew more about networking and .. had a month to spare, it'd probably be a fun(?) exercise to write a TCP library similar to rUDP

fluid jetty
#

haha we had to write a rUDP implementation in uni recently

#

for our final assignment in networking

misty glade
#

that sounds like a serious project

fluid jetty
#

with error handling for shit like corruption, lost packets, etc

#

everyone had to do it Looll

#

it wasn't super huge

misty glade
#

i suppose i wish i had that knowledge but also, not. 🙂 It's nice to be able to just say NetworkManager.SendData() and not worry too much about implementation details

fluid jetty
#

just a 'make a reliable transport protocol on top of udp that handles lost packets, corrupt packets and has timeout functionality'

fluid jetty
#

we were doing this in c too so its not as annoying like in .net where u have all these high level abstractions for low level protocol access

misty glade
#

call me a grumpy old man, I did the C thing in highschool, have no desire to ever go back. Dot net for life throws up gang signs

#

(this was 1994, i'm old now)

fluid jetty
#

Lool cool

#

im 96

#

i think C is simpler because it doesn't have a crap load of abstractions on top of abstractions

misty glade
#

fair enough

fluid jetty
#

but i think c# is comfier to use in most cases

#

after youve learnt what the api ur using does

#

kek

misty glade
#

It's nice to be able to get at the guts of the matter, but .. I suppose I rarely need to ever do so.. Sometimes I poke at https://referencesource.microsoft.com/ but usually only out of curiosity

#

a year ago I didn't even use LINQ expressions/extensions and now I'm like.. totally on the LINQ train

#

I was like, fuck that, gimme a for loop any day of the week.. now I'm all like Select().where().This().Is().Awesome().ToList() ya baby

fluid jetty
#

Loool i haven't done that ever yet

#

it looks cool though

ivory salmon
#

Does anyone have a contact at Unity for problems with the new Bug Reporting system (it's broken, I believe I know how/why - it's a known bug in Atlassian, which I thought they'd fixed by now)?

(after carefully looking through all the channels this one seemd most likely to have someone who might know!)

misty glade
#
        [Key(0)] public HashSet<UpgradeType> TemporaryUpgrades { get; set; } = new HashSet<UpgradeType>();
        [Key(1)] public HashSet<UpgradeType> PermanentUpgrades { get; set; } = new HashSet<UpgradeType>();

A year ago, doing a union of these structures would like 10 lines of code, two loops, with a temporary hash set.. now it's just

        [IgnoreMember, JsonIgnore] public HashSet<UpgradeType> OwnedUpgrades => TemporaryUpgrades.Union(PermanentUpgrades).ToHashSet();
misty glade
hollow garden
misty glade
#

i don't want to modify a though

hollow garden
#

oh right

misty glade
#

i mean, nbd, declare a new tmp hashset, add all of a, add all of b, no problem, it's not hard

#

just saying it's a lot shorter with linq 🙂

hollow garden
#

yeah

misty glade
#

i'm also really into the whole Max() type things

hollow garden
#

yeah the max and min things are cool

#

sad that you gotta make your own MinBy and MaxBy methods tho

#

since unity doesn't seem to have them for whatever reason

misty glade
#

wait, there's no key selector predicate for max() and min()?

hollow garden
#

nah

misty glade
#

🤯 i feel like I should know that but i haven't experienced it

hollow garden
#

lol

misty glade
#

👀 OrderBy().FirstOrDefault()

#

lol i looked through my codebase for where i thought i'd be doing a maxby or whatever and.... that's exactly what i'm doing

hollow garden
#

🤔

misty glade
hollow garden
#

it returns an int instead of the object you want

dusky carbon
#

I have a hard time wrapping my head around the Linq stuff, a little different from the fluent API I use in java at work (which feels more intuitive to me)

misty glade
#

i don't use the old school LINQ stuff for expressions, i just meant the extension methods

#

just the .. things that turn 4 lines of code into 1

#

Max() OrderBy() Sum() etc

dusky carbon
# misty glade wait, there's no key selector predicate for max() and min()?

just for practice I tried writing an extension for this, never wrote an EnumerablExtension before:

public static class EnumerableExtension
{
    public static T MaxByKey<T, S>(this IEnumerable<T> source, Func<T, S> keyFn) where S : IComparable<S>
    {
        if (source == null || !source.Any())
            return default(T);
        return source.Aggregate(source.First(), (max, next) => keyFn(max).CompareTo(keyFn(next)) <= 0 ? max : next);
    }
}
#

pretty cool that it just works as long as the namespace it is in is used

misty glade
#

yeah.. I have pretty much all my unity projects with a unityutilities class

fluid jetty
#

i wonder, could i use asp.net core signalR to make an mmo websocket server

#

and then send and receive data through websocket from a unity webgl client

urban warren
#

Is there a nice way to get every element in a grid in a float radius of a point?
I want to get the elements based on their nearest corner to the point.

#

I can think of ways to do it but they all seem kind of ugly.

hollow garden
urban warren
#

I also haven't seen the x * x + y * y < r * r before, interesting. I will have to think about it more to understand what it is doing.

hollow garden
#

its the equation for a circle

#

well technically the equation for a circle has =

#

but with < its just every point inside the circle

#

i.e every point within the radius

urban warren
#

Yeah, that tracks. I am not great with math and generally just don't learn much until I have a need for something. (Clearly that backfires sometimes...)

hazy hearth
#

Good morning everyone. I'm trying to figure out how to implement my skin swapper.
As of right now I have a skin library asset that holds my skins and I managed to develop the swapper properly while I keep the changes in game as well.
The thing is that now I need to have some skins that are available and some that need to be purchased first.
There are two approaches that come in mind for now.

  1. One that i hold all the skins in a huge sprite library holding all the resolvers and in parallel with a Dictionary that signals which are bought and wich are not I allow or not hte usage of the skin.
    Orrrr
  2. The second Idea is to hold several skin libraries and then whenever the user buys a skin, then somehow merge the main library with the skin's one. Or somehow add the new resolvers labels etc to the main library. What is your suggestion? 🙂
torpid sky
#

Hey, how do you implement something like variable attack speed?

#

It seems pretty much impossible to access the current state in the animator and change its speed, so apparently you have to change the entire Animator's speed, and then revert it back at the end of attack animation?

#

nevermind I didn't see there is a speed multiplier I can override per state

unkempt socket
#

I made a visual effect and am wondering, how to turn it on/off in script

#

any ideas?

#

not a particle system

urban warren
urban warren
hollow garden
#

ah right right this is for any point

#

it should be (x - h)^2 + (y - k)^2 < r^2 with h and k being the coordinates of the point then i think

urban warren
#

Ohh, well I guess I could just get the cell index and then offset it

#

Alrighty, thanks I will mess around with it 🙂

regal olive
#

According to person on the internet, apparently its much faster to do:

return new Vector3(
     f0*p0.x + f1*p1.x + f2*p2.x + f3*p3.x,
     f0*p0.y + f1*p1.y + f2*p2.y + f3*p3.y,
     f0*p0.z + f1*p1.z + f2*p2.z + f3*p3.z
 );```
than doing:
```cs
return f0*p0 + f1*p1 + f2*p2 + f3*p3;```
Anyone know why?
pX are Vector3
fX are floats
urban warren
#

However idk about 'much faster'. That kind of depends how many times you are calling it I guess.

regal olive
#

Ah yeah I can see that I think

hollow garden
#

i think there's like 7 in the second one

regal olive
#

4 multiplication and 3 addition?

hollow garden
#

ye something like that

regal olive
#

Compared to 12 addition

#

of floats

hollow garden
#

well

#

the 4 multiplication and 3 addition

#

are actually 4 * 3 multiplication and 3 * 3 addition

#

so 12 + 9

#

21

regal olive
#

Ah

urban warren
#

All the vector operations are just this

return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z);
hollow garden
#

it's purely faster because of the new Vector3s every operation

#

otherwise the amount of float operations are the same

regal olive
#

Anyone familiar with bezier curves?

#

Not sure whether to use a quadratic or cubic

hollow garden
#

i've dabbled in them a little

regal olive
#

I want a 2D arc from one point to another

#

Should I have 1 or 2 control points?

hollow garden
#

i guess cubic would do

regal olive
#

Alright now do you know how to find P1 and P2?

urban warren
#

If you are on 2022.1+ you can use Unity's new Spline package btw

hollow garden
hollow garden
regal olive
#

I have P0 and P3

#

Start and end

#

Not sure how to find the two in the middle

hollow garden
#

hmm

urban warren
regal olive
urban warren
regal olive
#

Ill take a look

#

If t=0 at P0
Would t=0.25 at P1?

#

So:
if P = (1-t)P1 + tP2
Then :
P0 = 0.75P1 + 0.25P2
P3 = 0.25P1 + 0.75P2
P1 = P0/0.75 - P2/3
P3 = 0.25(P0/0.75 - P2/3) + 0.75P2
P2 = 2P3/3 - 2P0/9

And from there I can get P1

hollow garden
#

i don't bother with that whole math thing i just use Vector3.Lerp a bunch

#

like ```cs
public static Vector3 Quadratic(Vector3 a, Vector3 b, Vector3 c, float t) {
return Vector3.Lerp(Vector3.Lerp(a, b, t), Vector3.Lerp(b, c, t), t);
}

public static Vector3 Cubic(Vector3 a, Vector3 b, Vector3 c, Vector3 d, float t) {
return Vector3.Lerp(Quadratic(a, b, c, t), Quadratic(b, c, d, t), t);
}

#

haven't done it in a long time

regal olive
#

Does that do the same thing?

#

Well anyways I got this working pretty much perfectly, just need to add some randomness now:

   IEnumerator C_BezierMove()
    {
        float elapsed = 0;
        float dur = 1;
        Vector2 startPos = transform.position;

        while(elapsed < dur)
        {
            Vector2 p0 = startPos;
            Vector2 p3 = Player.Instance.transform.position;
            Vector2 p2 = (2f * p3 / 3f) - (2f * p0 / 9f);
            Vector2 p1 = (p0 / 0.75f) - (p2 / 3f);
            transform.position = Extensions.BezierCube(p0, p1, p2, p3, elapsed / dur);
            elapsed += Time.deltaTime;
            yield return null;
        }
        Player.Instance.GoldCount++;
    }```
hollow garden
regal olive
#

lol

#

Is there a better way to get a random sign? This is kind of chaotic:

int RandomSign = Random.Range(0, 1) < 0.5f ? -1 : 1;```
#

Wait

hollow garden
#

well Random.Range(0, 1) is always gonna return 0

#

you want Random.value instead

regal olive
#

Got it

float RandomSign = Mathf.Sign(Random.Range(-1f, 1f));```
hollow garden
#

and to answer the question, probably not

regal olive
#

What does Mathf.Sign(0) return?

hollow garden
#

0

#

oh wait nvm

#

1

regal olive
#

Oh good

#

Looks like RandomSign * P2 & P3 completely breaks it

#

Oh wait duh of course it does

#

How do I get the a point symmetrically flipped across another point

#

Guess its time to reverse engineer the midpoint formula again

latent vine
#

guys

#

just a question

#

should i recycle one commandbuffer for all instances

#

or i can make multiple ones?

#

(performance based)

twin tartan
#

Does anyone know why my visual studios says miscellaneos files instead of assmebly csharp

nova slate
twin tartan
nova slate
#

ya same thing was happening to me and i found a youtube video on it

twin tartan
nova slate
#

ya there were also other solutions

nova slate
#

how do i add art to a game object if it already has been coded?

honest hull
#

why doesnt this work and how do I make it work? If I run it, unity yells at me that I cant set randomwrite enabled to an already created texure, but if I try to feed it to a compute shader to write to it, suddenly its not randomwrite enabled?
Im about ready to start making like 20 rendertextures per frame for temporary textures isntead of using temporary textures...

        for(int i = 0; i < 5; i++) {
            RenderTexture Intermediate = RenderTexture.GetTemporary(TargetWidth, TargetHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
            Intermediate.enableRandomWrite = true;
            Intermediate.ReleaseTemporary();
        }
#

If I use .Release it doesnt yell at me, but then after awhile I believe it causes the asset ID to go out of range so thats not an option

undone coral
#

pool them yourself?

#

should be easy enough right?

#

instead of temporaries

honest hull
#

trying that but im running into an issue with not evenly dividing by 2(tryng to do bloom so I need to downsample and upsample

#

oh the reason why I cant really recycle them is cuz each time its a different size
and the size is different every time basically(due to int divisiono)

keen cloud
#

this is disgusting is there a better way to get value of toggle group on change?

hollow garden
#

i suppose you could do a for loop

keen cloud
#

but the forloop would work once

hollow garden
#

and cache toggleGroup.GetComponentsInChildren<Toggle>()

hollow garden
keen cloud
#

they dont click a button to confirm which one is active, it is used to actively change search results

#

i'd need an on value changed for each one?

#

like that would work if this was possible, then i'd just call something to check

#

but you need to check each individual element for on value changed to get anything

keen cloud
# hollow garden ?

unless theres some other syntax i dont know about or im not understanding what youre saying

hollow garden
#

i was talking about doing a for loop and caching to make it look cleaner, which is what i assumed you wanted. ```cs
var toggles = togglegroup.GetComponentsInChildren<Toggle>();

for (int i = 0; i < toggles.Length; i++) {
//capturing
var _i = i;

toggles[i].onValueChanged.AddListener((bool on) => NarrowSearchLanguage(_i));
}

keen cloud
#

that makes sense. I wonder why they dont just have something like this

#

i appreciate it though

hollow garden
#

yeah i'm looking at ToggleGroup rn and i don't see any reason they wouldn't have a function to add a listener to every toggle

keen cloud
#

lmao yeah idek

#

literally one of the reasons you'd use it

#

frustrating

hollow garden
#

seems pretty easy to make as well ```cs
public static void AddListeners(this ToggleGroup toggleGroup, Func<bool, int, void> f) {
//this part seems like something that could be optimized but idk
var toggles = togglegroup.GetComponentsInChildren<Toggle>();

for (int i = 0; i < toggles.Length; i++) {
var _i = i;

//not sure about this part
toggles[i].onValueChanged.AddListener((bool on) => f(on, _i));

}
}

keen cloud
#

i'd guess just few enough people use it they havent done something like this

#

or they forgot? idk

#

lmao

hollow garden
#

probably the first one

#

lol

keen cloud
#

but yea thank you

#

the only thing is now, it calls it twice

#

lmao

hollow garden
#

lol

keen cloud
#

toggleGroup.GetComponentsInChildren<Toggle>().ElementAt(langaugeIndex).ToString().Split(' ').First()

#

to get the value of the one actually selected lmao

#

after it goes into NarrowSearchLanguage

undone coral
#

are there textmesh pro extrusion features?

#

or a good asset / library to do so?

unkempt nova
#

For what? 3D text based on TMPro? Feel like I've seen one around that does that

urban warren
#

Okay, how do you convert a world position to a grid position?
I thought it was this. But it only gives even grid positions.

x = (int)(Mathf.Round(position.x / _cellSize) * _cellSize)
#

You just don't multiple it after... I got too deep in to it...

dusky carbon
undone coral
#

how about a good input system virtual joysticks asset?

honest hull
#

How do you force the size of a created atlas texture? I need to pack them into a texture2darray but for that they need to be the same size

#

WAIT TEXTURE2D's ONLY SUPPORT UP TO 2 GIGS??

unkempt nova
somber swift
honest hull
#

yeah thats fair but I am gonna have to end up upscaling all my textures to like 4k just to make sure I dont lose detail on the high detail ones while still being able to send them all to the GPU compute shader at once

somber swift
honest hull
#

which is a problem if I also have hundreds of small textures
simply atlas'ing them all is now too slow with the amount that I need to be able to handle

#

if I could just have the atlas create a fixed size that would be nice

wooden cedar
#

You are the one writing the math for the texture atlas. Set it to anything you like, no? If it overfills, split it to another texture. I'm not sure where the question is in that statement though.

#

Hard to give you more advice though as it depends on how you are bringing textures into the array at the onset

meager kite
#

Unity cannot bake dynamic GameObjects into the occlusion culling data. A dynamic GameObject can be an occludee at runtime, but it cannot be an occluder.

#

whats the difference between occludee and occluder?

unkempt geyser
#

my guess is that an occludee is something that can be culled while an occluder helps unity determine what should be culled

#

just going off of how english works

rain sand
#

my character controller is not working it has the capsule collider and the camera is a child object of the player which right now is a cyllinder

unkempt nova
twin tartan
#

hello i am workling on a code via a yt video and i came across this character and dont know how to type it

#

its the character next to the void player movement()

zenith ginkgo
#

nothing ?

twin tartan
zenith ginkgo
#

oh

#

|

#

are you on a qwerty keyboard?

twin tartan
zenith ginkgo
#

keyboard layout

twin tartan
hollow garden
#

😐

twin tartan
twin tartan
hollow garden
#

oh boy i wonder if this is a qwerty keyboard

shadow seal
twin tartan
hollow garden
#

also if you mean this

#

it's nothing

#

it's just an IDE thing

twin tartan
shadow seal
#

Yes the magical character in the code is just a collapsed method

twin tartan
#

thank you for your help

humble leaf
stray plinth
#

Hey 👋
Is there any way to get dispose called on a class once you exit playmode?
Calling GC.Collect manually once playmode changes doesn't seem to cause it to get called? I've tried both with a destructor and with IDisposable

unkempt geyser
#

are you wanting it to be disposed automatically?

#

unity doesnt call those functions normally so youll have to write an editor script to do that

stray plinth
#

I've done that by subscribing to playmodestate change, calling forced Collect on all generations

unkempt geyser
#

GC.Collect from what i know doesnt call dispose on an object

#

it should call the deconstructor if its considered garbage

stray plinth
#

Shouldn't it be considered garbage if playmode is done?

unkempt geyser
#

unfortunately unity doesnt mark everything as garbage when switching between playmodes

#

it just destroys scene objects and components

#

so you would need to call dispose in the hook function in order to properly destroy it

stray plinth
#

Any way to dispose of runtime instances manually?

unkempt geyser
#

unless you can call dispose (or destroy if inheriting UnityEngine.Object) theres not much you can do unless you can remove their references (which will mark them as garbage)

unkempt socket
#

am i not allowed to change the shader anymore?

#

turns into this

fresh salmon
unkempt socket
#

true

lavish sleet
twin tartan
undone coral
#

what's the best way to project a wide stroked line onto terrain / other colliders?

#

drawing onto surfaces, but also with mitered/proper caps (unlike line renderer)

undone coral
#

my goal is to make a character moving around a terrain that leaves a graphic trail on the ground

regal olive
#
    {
        Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
        Plane plane = new Plane(Vector3.up, Vector3.zero);
        float hit;

        if(plane.Raycast(ray, out hit))
        {
            Vector3 pointToLook = ray.GetPoint(hit);
            Debug.DrawLine(ray.origin, pointToLook, Color.red);

            transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
            transform.eulerAngles = new Vector3(-90, transform.eulerAngles.y - 90, 0);
        }
    }```
#

and to move my tank im using rigidbody.MovePosition

#

should i use transform movement?

tough tulip
tough tulip
regal olive
keen cloud
#

are scrollbars supposed to be unfixable

#

i dont think ive been able to fix a single broken scrollbar

#

i just restart

honest hull
#

If I have an asset thats a model and not in the hierarchy yet, is there a way for me to auto-remap the materials from script?

worn flower
#

using a webgl build, why does unity not respond when the player hits escape to get cursor control back? i have an update loop checking for ESC and it doesnt fire when the cursor is locked on a webgl build

alpine adder
#

does anyone have ideas for better rotation in regards to AR or even positioning

#

like how would I got about having an object spawn at an object then add an offset position to it

undone coral
#

is there something special i have to do to set values on a script from a ContextMenu?

#

also the PositionConstraint editor is so insanely glitchy

#

i feel like i'm taking crazy pills. if the weight is 0, the position constraint should not move the transform even if it is active. why does it evaluate otherwise

pale pier
#

This might slowdown your project considerably tho, it'd probably be faster to just hook into the play mode change event and clean up only what you need

hushed fable
tough tulip
mint sleet
#

Hello. I have a list of 10 elements.
Another list has some of the same items in it.
I want to compare these two lists and change the isExisted property of the first list if the second list item matches

#

Is it possible to make it in Linq

flint sage
#

Sure but it's likely less inefficient than raw code

devout hare
#

If they're the exact same items and reference types:

foreach(var elem in list1.Intersect(list2)) elem.isExisting = true;
regal olive
#

but i already fixed it using transform based movement

mighty latch
#

Hi, I'm using an API through a wrapper which handles requests through async methods. I'm having an issue where, when making a request: I call the wrapper method and it returns a Task<TResult> object. However, when trying to access its result through MyTask.Result, the debugger returns a 403 error. Any idea how to fix it?

#

And yes, I'm using a valid API key

pale zinc
#

if it's returning 403 seems like something is wrong with authentication

weak agate
#

403 = forbidden

mighty latch
#
                var api = RiotApi.GetDevelopmentInstance("Valid API Key here");
                var summoner = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Euw, "Valid Summoner Name").Result;
                var matchlist = api.Match.GetMatchListAsync(RiotSharp.Misc.Region.Euw, summoner.AccountId);
#

The first request is validated, meaning the key is indeed valid, however, the second will return a 403error if I try to access its content, for example :

                var api = RiotApi.GetDevelopmentInstance("Valid API Key here");
                var summoner = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Euw, "Valid Summoner Name").Result;
                var matchlist = api.Match.GetMatchListAsync(RiotSharp.Misc.Region.Euw, summoner.AccountId);

                var test = matchlist.Result; // This returns a 403 error
#

I'm a newbie when it comes to API requests and async methods, but shouldn't the matchList variable be local? Why would I get a 403 error trying to access its contents?

pale zinc
#

shouldn't you be await-ing in there

#

it looks like you're trying to get the result without first waiting for the auth call to complete

#

try var api = await RiotAPI.GetDevelopmentInstance()

#

no wait, that one's not async

#

but use that for the Async calls

devout hare
#

How do you know the first request doesn't return a 403 response if you don't access the results?

mighty latch
#

Well, it doesn't return a 403 BECAUSE I don't access the results lol

#

@pale zinc Thanks, I think that's simply the issue, although the provided examples didn't seem to bother using async/await, so I'm a bit confused

devout hare
#

That doesn't make much sense. If a tree falls in the forest, it still falls, even if there's no-one to see it.

fresh salmon
#

By accessing .Result in the last line, the thread is blocked until the Task completes

#

It's one way to not await the task, and do the request synchronously

pale zinc
#

yeah you should probably check if summoner doesn't also have a 403

mighty latch
#

Well, it would halt execution if it did, but no, I wrote some Debug statement and all of the information matches, names, ids,...

fresh salmon
#

Ah I think I see why

#

You don't await or get the result of your summoner Task before feeding it to GetMatchListAsync, in this case I'm not sure what would happen if the task hasn't finished

#

Ah no I'm just blind

#

Ignore me

pale zinc
#

is it possible you're not allowed to call that method with that account id?

mighty latch
#

Shouldn't be the case. I retrieved the id from summoner and used it on the API's official website to make a direct request, using the same API key, and got a valid response

pale zinc
#

sounds like a question for whoever wrote the API library

mighty latch
#

Yes, I submitted a request, I should have the latest version but you never know

#

Thanks for thelp!

#

@pale zinc @fresh salmon Okay, turns out the issue was that you needed to use an alpha release to get access to the current API, so there wasn't anything wrong with the code itself, just an obsolete API

fresh salmon
#

Thanks for the update!

timber flame
# sage radish I've made enum classes like this before, but they are limited. Because the value...

I do not want to use switch/case for that!
See, it is just used instead of indices 0,1,2,3.
I mean instead of passing meaningless values 0,1,2,3, you pass RotationType.
Now, why I say enum is bad here because a developer can change the values easily while changing values causes bugs in logic.
Values are used as index uvs[(j+(byte)rotationType)%4] rotationType=0,1,2,3
but if I use Enumeration class, I can add a field with specific name index.
Generally, I think using enums when somewhere a logic is based on the values of that enum is buggy

split blaze
#

It is searchable, nvm. I can search with that string. My code ran at zeroth frame which is not recorded. Was able to search that name in the profiler window on the next calls.

worn flower
#

Hello. In a WebGL build, I have an update loop checking for when the player hits the ESC key. If the unity player has locked and hidden the cursor, hitting escape will NOT trigger the code to execute in the update loop, even though it does in the editor and desktop.

What is the best way to handle this? I simply want to achieve a situation where if the player is in first-person-mode with a locked and hidden cursor and they hit ESC, they will get their cursor back and stop causing player rotation. This seems like it should be easy, but I think some under-the-hood stuff with webgl is making it more difficult.

ALSO, i try detecting ESC with javascript, and if the cursor is locked, it doesnt detect it either....

What is the best, cleanest way to accomplish this?

hot willow
#

I am trying to make a simple game where basically I need two textures to be compared and output a matching percentage of the first one to the second one. I experimented with for loops that do GetPixel in every pixel (Texture2D) but with no result. Also the textures are black shapes with white background, so if both pixels in x, y (first texture) and x, y (second texture) are black or both are white, int correctPixels++;

formal lichen
#

no need to cross post

undone coral
#

if so you should probably file a bug

swift widget
#

Hey, I am trying to call a JS function from a c# class for my WebGL project, the only isssue is, that it does not build for some reason. Any idea how i can call the JS functions from within C#

formal lichen
#

that c# extern will point to a jslib file running within the same project that points to the function ```js
WebSocketConnect: function(instanceId) {

#

the naming of the method is important as it uses that to find the method in the jslib

hallow elk
#

Looking for a way to render an object under everything else, always, without using an extra camera.

#

I have tried setting a Sorting Group on the object with the MeshRenderer, but this isn't working

dusky carbon
hallow elk
#

Yes, exactly.

dusky carbon
#

This is my dumb advice because I know next to nothing about tricky rendering stuff, but I would try adding a shader to the obj with the "Queue" subshader tag set to "Background". I figure posting a probably wrong answer might at least provoke others to provide better advice

hallow elk
#

DIdn't work... 😦

regal olive
#

Hello! I'm trying to make a login system so I have a singleton that contains the authentication session data and i'm assigning it values if the request goes well (login or register). I'm having an issue when trying to assign a teacher to it and it says something is null. I've debuged everything and the teacher i'm trying to insert is not null actually but maybe something's wrong with my singleton class, and btw Teacher class isn't a monobehaviour. Can you help me figure out what's wrong?

sly grove
regal olive
#

Thanks and sorry

dusky carbon
# hallow elk DIdn't work... 😦

so I got this... (same objection positions, just a different angle proving white box is actually behind) it doesn't quite work if I leave the camera's skybox enabled in game though

hallow elk
#

I am going to try messing with it a bit

dusky carbon
hallow elk
#

Aha! ok

#

It works! YESSSSSSS

dusky carbon
#

nice!

#

I think it will lead to some pretty confusing perspective while moving the camera around lol

hallow elk
#

Basically I have an "outside" of a building, that is visible from certain places in the game, but when it intersects with the internal parts I want it to not render

dusky carbon
#

makes sense

hallow elk
#

So while it looks super weird from the outside...

#

From inside it's perfect

small basin
#

Hello! I have read some articles on switching between 1st and 3rd person cameras so I understand basics. However, I do not understand how to make functional in multiplayer. Take a game like CoD, you play in first person animations but see others in third person animations. How is this achieved? Please direct me to some resources. Thanks!

somber tendon
#

you simply render others as 3rd person, ignoring their 1st/3rd person state

tough tulip
stray sleet
#

Quick question: ScriptableObject data does not persist after a restart of the application right?

dark cedar
#

Are you referenccing a scriptable object and editing the values at runtime via code?

tough tulip
stray sleet
dense echo
#

anyone know anything about unity & spine?

flint sage
#

Depends what you need to know

dense echo
#

so we use spine & unity for the game were making and im trying to implement a backpedal but when i try to backpedal it interrupts the attack if you do it too early then you get stuck

#

in a backpedal state

flint sage
#

That doesn't sound like an animation problem but rather a implementation problem on your code side

tough tulip
dense echo
#

this is my first time using spine ive used unity in the past but not in something as complicated as this

flint sage
#

That's a lot of code, you should really isolate the problematic parts

somber tendon
#

Exactly, not everyone here have the time to read all those 800+ lines 😮‍💨

dense echo
#
private void Move()
    {
        movementX = Input.GetAxisRaw("Horizontal");
        movementZ = Input.GetAxisRaw("Vertical");
  
        if (movementX != 0)
        {
            this.rb.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionY;
            //Start Moving
            if (isWalking == false && isbackpedaling == false)
            {
                SetCharacterState("Running");
            } 
            else if (isbackpedaling == false)
            {
                SetCharacterState("Walking");
            }
            else
            {
                SetCharacterState("Backpedal");
            }
            //Decide Direction
            if (movementX > 0)
            {
                if (UnitForward == false && isWalking && isRecovering == false && attacking == false)
                {
                    isbackpedaling = true;
                }
                else
                {
                    UnitForward = true;
                }
                
            }
            else if (movementX < 0)
            {
                if (UnitForward == true && isWalking && isRecovering == false && attacking == false)
                {
                    isbackpedaling = true;
                }
                else
                {
                    UnitForward = false;
                }
            }
        }
        else if (movementZ > 0)
        {
            //Start Moving Z
            SetCharacterState("AwayStep");
        }
        else if (movementZ < 0)
        {
            //Start Moving Z
            SetCharacterState("TowardsStep");
        }
        else
        {
            //Idle
            SetCharacterState("Idle");
            movementX = 0;
            movementZ = 0;

        }
    }
#

thats movement code

#

thanks

#

the only problem is attacking is really long as well

dusky carbon
#

is this code generated out of curiosity?

dense echo
#

generated no its typed out

#

thats all primary action code

#

and finnaly ```cs
private IEnumerator WalkWait()
{
yield return new WaitForSeconds(1.75f);
if (movementX != 0 || movementZ != 0)
{
speed = normalSpeed;
walkTrack = skeletonAnimation.AnimationState.SetAnimation(0, run, true);
canAttack = true;
isbackpedaling = false;
attack1Fired = false;
attack2Fired = false;
attack3Fired = false;
}
else
{
speed = normalSpeed;
canAttack = true;
isbackpedaling = false;
attack1Fired = false;
attack2Fired = false;
attack3Fired = false;
attacking = false;
}
}

dusky carbon
#

I need to wrap my mind around this, can you walk me through the animations you see, starting with attacking and then early backpedaling?

dense echo
#

the main problem is just getting stuck if i swing my sword and during that time i attempt to move before the attack recovery has completed i either get stuck walking forever or i get stuck backpadaling forever its like if the attack is interuppted variable i have set in walk wait dont trigger

somber tendon
#

your code looks like they could use some refactoring, but lets put that aside...
if your walk wait doesnt get triggered, then most likely the attack animation is interrupted (the animation is changed before it's completed)
maybe you should disable moving while attacking animation is not completed

dense echo
#

the problem with that is you need to be able to attack and walk at the same time

somber tendon
#

I'm not sure if spine animation support animation blending... or do you have attack while moving animation?

dense echo
#

we have 2 different attacks 1 while idle and one while moving called attack1blend and so on

somber tendon
#

do you have attack while backpedalling?

#

if not maybe you can just disable attack while backpedalling

dense echo
#

would it help if i just redid everything?

#

im sure theres a better way to dop what im doing

hallow elk
#

OK, I cannot seem to find an answer here, but I think this is the source of an issue I'm having: When you get transform.GetSiblingIndex are inactive objects counted in that index?

bold mountain
#

Hi! i'm using UnityEvents for a few things, and i might not be understanding a few things:

public class CustomSCOLEvents : UnityEngine.Events.UnityEvent<CallEventAction> {
}
[CreateAssetMenu(fileName = "New Custom Action",menuName = "SCOL/Actions/Custom Action")]
public class CallEventAction : ActionBase {
    public CustomSCOLEvents EventsToTrigger;
    public async override Task Execute() {
        EventsToTrigger.Invoke(this);
        await Task.Delay(0);
    }[...]```
Here, i'm passing my CallEventAction as argument, but how can i retrieve it in the called function in the event? IE: i'm putting this function inside the unity field:
#

which is basically ```cs
public void PrepareNikkyImpDialog() {[...]}

What can i do to retrieve my callEventAction in this? Do i need to add it as a parameter?
tough tulip
#

where are you passing the parameter?

bold mountain
#

if you pay close attention, the parameter in my generic type is actually the class just below

tough tulip
#

what i meant to ask is, the object is being passed to UnityEvent<T>. but UnityEvent<T> is calling a UnityEvent.
the parameter is being discarded

#

there's no direct approach for something like this.
a custom inspector might work im not very sure.

but what you could do is, store the generic T instance somewhere publicly accessible.
store the object when you call the Invoke. Then consume it within the function

bold mountain
#

i don't think i've been clear of what i'm doing lol
Let me do a quick paint drawing

tough tulip
#

my assumption is that you want to access CallEventAction which you're passing via Invoke(this) in the function PrepareNikkyImpDialog()
am i right?

bold mountain
#

so i don't need to actually see anything in the inspector

#

anything get passed down in the code (theorically)

bold mountain
#

So you're saying that maybe i need to pass it down another way..?
I clearly can't do that, cuz the soul purpose if this CallEventAction scriptable is to being able to call it anywhere. I'll do what i need another way if it's not possible

austere jewel
#

public void PrepareNikkyImpDialog(CallEventAction action)

#

Then properly select it from the Dynamic section of the functions list

bold mountain
#

so i can't pass down two bc of how unity events work

austere jewel
#

You cannot get the value unless you use a function that can receive it.

bold mountain
#

okok! got it
I really do not get what is the purpose of using a unityEvent with this generic type polymorphism thing

tough tulip
austere jewel
#

What's the purpose? To be able to serialize a simple function in the inspector. A perfect example is an InputField having a Submit(string)

#

I would love if they could support some more complex stuff, but it doesn't have that capacity

tough tulip
#

there are other simple options too.
passing true/false to GameObject.SetActive

bold mountain
#

well, if i bind a function that is defined as "SetActive(bool active)" in my script, i can do it with a UnityEvent without having it to be a generic type i created, right?

tough tulip
#

it will only need to serialize the boolean value. so yes no generics needed

bold mountain
#

okok! might be a 90° degree turn, but i basically wanted to do this so that if my event called an async Task, i could wait for it to be over with a workaround, and setting a boolean to my callEventAction saying it's over, yaddah yaddah... Anyways, i can't call a function that's not a coroutine by name, can i?

#

(unless i do like "switch(functionName)...." and hardcode all the names ofc)

#

i like to live on the edge sunglasso

winged mirage
#

So, I'm trying to lerp my slider to the target value when pressing the space key
https://paste.ofcode.org/4MWPwGQMZhe99Qda6LKdvV
But, it's showing
Assets\LerpSlider.cs(27,25): error CS0161: 'LerpSlider.LerpHealth()': not all code paths return a value

somber tendon
somber tendon
winged mirage
#

still aint workin, i've set the default slider value to 0, but it aint reaching the targetvalue 10, aand i ain't seeing any error like before

random dust
#

Your code is valid, but it will execute your while loop immediatley because it is not yielding based on some condition in there. I assume your program will lock up based on what the loop waits on

hasty elm
#

Hello, does anyone know how is it possible to trim mp4 files with unity?

bold mountain
#

oh this is such a bad idea

pale zinc
bold mountain
# pale zinc what are you trying to achieve?

Basically, ideally, i'd want my event invocation to have a workaround for asynchronous behavior. So basically imagine this:

public class CallEventAction : ActionBase {
    public CustomSCOLEvents EventsToTrigger;
    [HideInInspector] public bool finished;
    public async override Task Execute() {
       
        EventsToTrigger.Invoke(this);
        await TaskUtils.WaitUntil(() => finished);
    }
}```
And maybe what i could do is in each of my functions (that are all gouped in one scriptable object), i could have a custom implementation like so:
```cs
    public async void Fun() {
        CallEventAction action;
        await Task.Delay(2000); //Do async stuff
        action.finished = true;
    }```
So i attempted having a UnityEvent with generic type (which does not help at all and actually does something that has nothing to do with what i want),
bold mountain
pale zinc
#

what is the purpose of the await after the event invoke?

sly grove
bold mountain
#

oh, yeah my bad. Let me track the stack call for you, but we might unzoom too much:

pale zinc
#

Do you want to fire an event synchronously, and then start some async logic elsewhere based on that event? Or do you want to call an event from an asynchronous functoin and.. do what exactly?

bold mountain
#

Basically: my state machine is made of Trees. These trees, of leaves, and those leaves of actions. Polymorphic actions that can basically have anything inside them:

public async Task PlayLeaf() {
            foreach (ActionBase action in actions) {
                await action.Execute();
            }
            if (CharacterSystem.Instance.ClearCharactersOnEndLeaf) await CharacterSystem.Instance.CharactersAllGoAway();
        }```
So the Execute is awaited here, and the PlayLeaf itself is awaited in the Tree.ResumeTree, etc etc.
pale zinc
#

you want to await the result of events?

#

don't do that, that's a bad idea

#

events are meant to be fire and forget

#

you're better off keeping a list of listeners then

bold mountain
#

oh
And triggering them by index or something? hmm

misty walrus
#

I'm trying to extend the Button class. I'll need very little functionality but I'm failing to figure out how I can run a method at the start of a scene. As it's not mono I don't have any access to start/awake. Is this not possible?

#
    public class ToolButton : Button
    {
        private void Awake()
        {

        }
    }

this is basically what I need tbh

sly grove
#

Button is a MonoBehaviour BTW, so Awake, Start etc will work fine

misty walrus
#

I did follow its inheritance but didn't see monobehaviour on any layer.

#

I'll have a few tools around and I don't wish to connect their identical onclick events. It was either this or a companion component to a regular button.

pale zinc
#

I'd go with companion and [RequireComponent]

misty walrus
#

oh i'm extending the wrong button...

sly grove
#

But there's no reason to extend Button usually

misty walrus
#

May I ask what's the benefit of a companion over an extended class?

pale zinc
#

generally if you can choose between composition and inheritance, pick composition

misty walrus
#

mkay, tyvm

pale zinc
#

If you end up having some other piece of logic that would also need to be attached to a button, with composition you can just add two extra components. With inheritance, you're stuck

misty walrus
#

that makes sense

undone coral
#

you want to use a separate script for your animations. this script should make measurements / observe the rigidbody and other state and write those to an animation controller.

#

you also want to use Input System instead of Input

#

@dense echo so in my opinion you should rewrite what you have from scratch. authoring a state machine in an update loop ("updateloopese") isn't viable

undone coral
#

you will need to do compositing of some kind in general, so it's unavoidable

#

i am looking at this online and it's just the cost of doing the effect.

undone coral
tough tulip
# hallow elk I have tried setting a Sorting Group on the object with the MeshRenderer, but th...

you have some options you can try to explore.

i) use an extra camera with culling layer setup. this is the worst option because having multiple camera will just multiply the cpu overhead that many times. even more in HDRP which does not support camera stacking at all.(you can still get it to work, or use compositor, but you'll face unwanted issues later)
ii) use a custom shader to draw the object at the right spot. you can also use the render queue to control things in a similar pass.
iii) if you're using urp/hdrp youre in luck. you can use render objects (urp) and custom pass (hdrp) to do layer based sorting and draw objects in a specific layer in a different way.

In simpler words:

  • writing a custom shader is the best option since thats per object. No need to waste a layer for this solution.
  • render object and custom pass work on layer basis and only on urp and hdrp respectively.
  • camera also works on layer basis but has extra cpu overhead and wont even work in hdrp.
floral flower
#

hey guys, SO saves between scenes right? it only reset when u turn on/off game?

#

built version ofc

sly grove
floral flower
#

yup, thank you 🙂

uneven nova
#

can anyone tell me why calling LobbyService.Instance.QuickJoinAsync is causing me to get an error when i pass it in as a parameter in the second line, but works just fine if i await it using the method in the first line?

#

it throws this error

#

and from what i've seen before, its usually because i've called a unity-function that's only meant to be called on the main thread. but these are async functions so it should be fine

hazy hearth
#

Hey yall,
Any idea why OnDeselect() is not showing results? I'm using the IDeselectHandler properly with the using UnityEngine.EventSystems;
as well. The gameobject that holds teh script is a button which I want to be disabled when deselected.

#
using UnityEngine;
using UnityEngine.EventSystems;

public class EquipButton : MonoBehaviour,IDeselectHandler
{
    // On equip button click event
    public void OnClick()
    {
      // blah blah blah 
      ...
      // Disappear when tapped as well
      gameObject.SetActive(false);
    }

    public void OnDeselect(BaseEventData eventData)
    {
        gameObject.SetActive(false);
    }
}

#

[Solved]

undone coral
#

is there an asset for extruding shapes / graphics? for example an svg, especially one that came in via unity's vector graphics package

keen holly
#

New to C#
Trying to make this language more bearable. I see that it has support for destructuring.

No idea why a lot of the Unity structs don't support it out the box. Can anyone explain why?

I also found this extension: https://github.com/baba-s/UniDeconstruction

I tried to install it via the package manager but it doesn't seem to do much. Anyone have any ideas here?

undone coral
undone coral
undone coral
#

don't try to do that stuff yourself, you did it wrong

uneven nova
#

AsyncTask is mine, but even Unity's own code doesnt work

#

@undone coral

compact ingot
uneven nova
#

i just did a test to make sure that the player is in fact sign in before quick joining and im not getting a 404 code instead of 401 @compact ingot
seems like i can just ignore the 404 code though

compact ingot
#

Are you sure you are passing the required auth. info in your request? Bearer token etc.

uneven nova
#

@compact ingot im not sure where that would be shown. im initializing the unity services and authentication services within Start and then using their way of setting up the rest of the identification

compact ingot
uneven nova
#

mmk one sec

#

@compact ingot

compact ingot
uneven nova
#

just trying to get unity lobby+relay+utp stuff working but every step of the way im getting problems

compact ingot
#

step 1 would be to get UniTask and ditch your DIY solution to make sure there aren't any bugs created by a buggy async implementation/wrapper/utility-thingmajig
step 2 would be to understand how the remote API works to avoid the permissions/auth issues
step 3 would be to build a utility framework around what you learned

#

the errors you have shown so far can only be solved by understanding how the lobby API works, if you post an exception that says "Failed to find any open lobbies" what kind of help do you expect to get here?

uneven nova
#

the errors you have shown so far can only be solved by understanding how the lobby API works
yea. the thing is that theres so much sample code to sift through and half of it is irrelevant. its hard to create framework when i dont know whats important.

#

ive been dealing with looking through Unity game lobby example project since friday, trying to pick through it and create my own code based on what they do

main gull
#

Hi guys I need your advice. I am self taught developer. I finished MIT CS106a and a couple of C# courses. I can do a lot of things in Unity. But it seems I have little knowledge about data storage and data structures ,graphs , lists , dictionaries, their pros and cons . Could you please recommend a book or online course for the subject. Thank you

uneven nova
#

@compact ingot also i dont really have time to sift through whatever UniTask is to figure out how that works too

safe gazelle
#

Database stuff is a bit separate and more in depth depending on what you already know, or don't know.

main gull
undone coral
#

create a networked multiplayer game? what kind of game is it?

uneven nova
#

its a golf game

#

@undone coral the object syncage should be super simple so i dont really need the Networked Game Objects package, i can handle syncing that stuff on my own, hopefully

#

making code for sticking people into a lobby was simple enough. coding the relay part is where i had to mostly rely on unity's RelayUtpSetup to get that all working because there's so much behind-the-scenes code that would take me forever to research

misty glade
# main gull Hi guys I need your advice. I am self taught developer. I finished MIT CS106a an...

If you're intending to be a computer scientist then you really need to take a data structures course (and probably also algorithms) so you understand how they work under the hood and how to design and build your own. If you're intending to be a programmer, then you likely can get by just fine by continuously learning how to use new data structures that exist in .NET generic collections - dictionary, queue, stack, list, hashset: they'll do it better than you can, and they're far easier to implement.

When I say "computer scientist" and "programmer", by the way, I consider a programmer to be someone who generally consumes the API of other people, and computer scientist someone who has spent many years (either in school or not) studying "pure" computer science and math topics. 90%+ of programmers are "programmers" and not "computer scientists", I think.

In general, it's hard to study generic concepts without a background/degree in computer science, so your best bet for learning is to try to implement something yourself, and read as much as you can to learn the concepts for that task. Databases, networking, serialization, etc.

You'll probably also want to add "patterns" to your list of things to learn - which are also a little bit hard to study in the abstract, but still critically important to get good at if you want your codebases to be manageable.

uneven nova
#

I consider a programmer to be someone who generally consumes the API of other people
i think Unity's Gaming Service API gave me API poisoning, i dont feel so good
Edit: I do think I'm making some progress though

wary zephyr
#

How can i Change the Alpha Channel from a Gradient variable.
I am using Slider component to fill the image with different values I am creating a healthbar but I want to decrease the alpha channel at some point and I can't seem to solving this :/ I saw like GradientAlphaKey something like that but didn't work and I wanna access it from other script

main gull
uneven nova
wary zephyr
#

But the color was changing

#

I assume I had a mistake on GradientColorKey but don't know how to get this done with the slider

uneven nova
#

i havent fiddled with those so im not too sure

wary zephyr
#

To be honest I didn't try to use them both :/ don't know if that would have worked

#

What do you mean? You never used both gradient and slider? Plus alpha channel?

#

Yeah okay no problem thanks for trying ❤️

uneven nova
#

like for line renderers

wary zephyr
#

Ohh it's okay :/ thank you very much 😊

compact ingot
# main gull Hi guys I need your advice. I am self taught developer. I finished MIT CS106a an...
rocky mica
#

Hey! I am trying to do a small little editor script that gets a prefab in the assets folder, creates a new variant out of it, and then duplicates the material inside if it has a mesh renderer, then finally assign them those materials. Sadly I cant get that last part to work, if I use .material the editor will error out saying I should use sharedMaterials, but using sharedMaterials doesnt assign the material, so i am a bit stuck

#

public void Duplicate() {


        var targetPath = path.Replace(split, addedText + split);
        //Instantiate Copy in Scene
        var newObj = (GameObject)PrefabUtility.InstantiatePrefab(obj);
        var meshRenderer = newObj.GetComponent<Renderer>();
        List<Material> mats = new List<Material>();
        if (meshRenderer != null) {
            int index = 0;
            foreach (var material in meshRenderer.sharedMaterials) {
                string matPath = AssetDatabase.GetAssetPath(material);
                string matSplit = Path.GetExtension(matPath);
                string matTargetPath = matPath.Replace(matSplit, addedText + matSplit);

                Debug.Log(matPath);
                Debug.Log(matSplit);
                Debug.Log(matTargetPath);
                AssetDatabase.CopyAsset(matPath, matTargetPath);
                
                mats.Add((Material)AssetDatabase.LoadAssetAtPath(matTargetPath, typeof(Material)) );
                index += 1;
            }
            //replace mats in prefab
            index = 0;
            foreach (var material in mats)
            {
                newObj.GetComponent<MeshRenderer>().sharedMaterials[index] = material;
                Debug.Log(newObj.GetComponent<MeshRenderer>().sharedMaterials[index].name);
                index += 1;
                
            }
        }
        //Save!
        var variantRoot = PrefabUtility.SaveAsPrefabAsset(newObj, targetPath);
        //DestroyImmediate(newObj);
    }

#

this is the code

#

it gets the prefab (works), instantiates it on the scene (works), gets all the materials inside the mesh renderer(works), creates copies of these materials (works), then reassigns these copies to the scene instance (DOESNT work), and then saves the newly edited prefab (works!)

#

this is my issue and I cant find a solution

#

//replace mats in prefab
            index = 0;
            foreach (var material in mats)
            {
                newObj.GetComponent<MeshRenderer>().sharedMaterials[index] = material; //<- this doesnt nothing
                //newObj.GetComponent<MeshRenderer>().materials[index] = material; //<- this errors out in editor
                Debug.Log(newObj.GetComponent<MeshRenderer>().sharedMaterials[index].name);
                index += 1;
                
            }

#

any help would be appreciated

#

that would explain a lot

#

gimme a sec to try

#

Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.

#

this is a really backwards way to explain what you just said lol

#

works perfectly

#

thankssss

#

I was stuck here for half an hour haha

undone coral
#

i've engineered a golf game, and also directed a different golf game

#

one async multiplayer and one realtime

#

this is going to sound stupid, but why are you writing so much of this stuff from scratch

#

why aren't you using photon?

uneven nova
#

im not a fan of writing all this stuff from scratch

#

im used to using UNet where most of this stuff was handled automatically

uneven nova
#

oh it looks like they do. maybe i can convince them to use that instead

#

@undone coral lmao one of the guys on the team saw this and said "Nice ad, it's telling us something"

undone coral
#

golf is the perfect game for photon's networking model

#

as long as you don't need the balls to collide with each other, which none of these games do

uneven nova
#

that was potentially going to be one of the things that they do 😬

#

i'd rather they not, though

#

the chance of players having their balls collide when launching them at the same time is gonna be rare im sure

#

balls colliding when they're rolling on the ground would be more likely to happen

sly grove
#

Many golf games allow ball collisions but they're relatively rare and they're expected to be chaotic anyway so it works fine.

uneven nova
#

😄

uneven nova
#

switching over to Photon immediately to try it out 😄

sly grove
#

although "Photon" doesn't mean much - they have at least 3 networking products:

  • Pun
  • Bolt
  • Fusion
regal olive
#

Pun is very good

#

And free

arctic finch
#

Which kind of network model or package is best? Thinking of multiplayer, did some research but showed up with many options

shadow seal
#

The best is the one you like that suits the needs of your game

calm ocean
#

I have a class whose majority of its methods take in a string, and converts it to its class counterpart. More specifically, I am working on a visual novel characters script, and the methods take in a character name in string, and gets the actual character class from a dictionary. Many of these methods accesses the dictionary for the character class. Is there a way to abstract the accessing of the dictionary? Sort of like decorators in python

humble loom
#

an enum is basically a finite set of distinct values. you can access the dictionary using the enum values as a key, which means you basically make it impossible to supply an incorrect argument

calm ocean
#

As in, replace the string in the parameter of the methods with an enum?

humble loom
#
public class Character : Monobehaviour
{
  public enum Name
  {  
    Rick,
    Stan,
    Beth
  }
  private Dictionary<Name, Character> _prefabMap;
  protected Name _name;
  public Name Name => _name;
  public static Character Generate(Name characterName)
  {
    var result = Instantiate(_prefabMap[characterName]);
    return result;
  }
}
#

something like that

#

you have a public factory method that takes in a "name" argument, instantiates the prefab, and returns the reference to the calling code

calm ocean
#

Oh I see. So in the methods that take in that enum, I call the Generate method to get back to Character class?

#

Or do I call the factory method before passing into the method?

humble loom
#

yeah so the calling code would look like

#
public void GimmeRick()
{
  var rickInstance = Character.Generate(Character.Name.Rick);
  rickInstance.DoRickThings();
}
calm ocean
#

Oh I see

#

On a side note, why is the method named Generate?

humble loom
#

it's just a standard factory pattern naming

calm ocean
#

Ah, that's what I thought, interesting, I didn't know that, thanks for the help

humble loom
#

you could do Create, Spawn, whatever you want

#

np! I hope that's along the lines of what you're looking for

#

a tag-along pattern that might be useful is to create a "palette" of prefabs as a scriptable object, so you can build the dictionary automatically

calm ocean
#

What is a tag-along pattern?

humble loom
#

like you could make a script that extends from character like this:

public class Rick : Character
{
  // Rick comes packed with his own name so we can build the dictionary with no extra data
  _name = Name.Rick;
}
[CreateAssetMenu(menuName = "CharacterPalette")]
public class CharacterPalette : ScriptableObject
{
  [SerializeField] private Character[] _prefabs;
  public Dictionary<Character.Name, Character> CreatePrefabMap()
  {
    Dictionary<Character.Name, Character> result = new();
    foreach (Character prefab in _prefabs)
    {
      result[prefab.Name] = prefab;
    }
    return  result;
  }
}
#

assuming the parent class has a protected _name variable and a public property Name to access it

#

yadda yadda

calm ocean
#

That's super cool, thanks for the insight

wicked cape
#

I have been trying to fix my weapon script. Currently it holds everything that any type of weapon needs but I have some weapons where a lot of the variables are redundant (Ranged/melee or requires ammo/Doesn't require ammo). How would I go about fixing this for different weapons?

humble loom
#

don't have one script that does everything

#

have an abstract weapon script that has all the attributes and definitions all weapons will need, then make other scripts that extend from them and specialize

uneven nova
#

@undone coral can Photon Fusion handle lobbies by itself or do i have to use PUN 2 also?

somber tendon
humble loom
#

that's fair. it i wanted to do it compositionally, i would probably have like socketed sub-components, if that makes sense. like have interfaces defining how a component can interact with a base weapon

#

like IOnBulletHit, IAmmoConstraint, IFireRate

#

and then i can predefine a suite of subcomponents and build weapons compositionally, like the base weapon knows how to consume all the subcomponent interfaces and ALL the weapon does is apply them

#

and then you can build weapon configurations as scriptable objects, so you can literally slap them in completely modularly

#

(though interfaces don't work for that, which sucks, so i'll probably use abstract base classes as a pseudo interface even though it's gross

#

I SO WANT to be able to serialize interfaces in unity

#
[CreateAssetMenu(menuName = "WeaponConfiguration")]
public class WeaponConfiguration : ScriptableObject
{
  [field: SerializeField] public IOnBulletHit OnBulletHit {get; set;}
  [field: SerializeField] public IAmmoConstraint AmmoConstraint {get; set;}
  [field: SerializeField] public IFireRate FireRate {get; set;}
  [field: SerializeField] public IBurstRate BurstRate {get; set;}
}
#

that would be SO SEXY

#

but abstract classes are just as good, just a little more constricted

stray sleet
humble loom
#

your name it nutpile

somber tendon
#

I dont like abstract classes, feels like I'm writing something that I will never use

humble loom
#

you're writing a contract

flint sage
#

Then you're using them wrong

somber tendon
#

not particularly abstraction, but maybe the whole oop concept I don't like...
dont get me wrong, I was using c++ with irrlicht, and flash/as3 before, and I have no problem with oop, but comparing to how unity implemented component based it feels like it's more effective (although it's most likely biased/not apple to apple since unity is a complete game engine).

humble loom
#

if you don't like OOP then you might want to rethink games lol

#

the few forays into like pure functional programming are exclusively meme passion projects

#

oh i see what you're saying, like entity/component models are still OOP though

somber tendon
#

🤔 maybe I should say inheritance...

humble loom
#

well using inheritance in this sense is just to group the types of compositional pieces

#

like "these are things you can cram into the ammo slot"

#

"these are the ways you can manipulate fire rate"

#

it's like how a motherboard has sockets for ram and graphics cards and cpu's

#

you have a collection of compatible cpu's, a collection of compatible RAM, a colletion of compatible GPU's

somber tendon
#

you know like
creatures -> biped->humanoid->elf
most likely I ended up with 'useless' classes like creatures and biped

#

which contains nothing but abstractions

humble loom
#

they're only useless if
-> you don't define abstract behavior
-> you don't utilize the abstraction as a contract

#

like

flint sage
#

Also no one is saying that you should start that low level

humble loom
#

sec i'll show you something interesting

#
public abstract class Mammal<T> : MonoBehaviour where T : Mammal<T>
{
    public abstract void HaveSex(T other);
}

public class Breeder<T> : MonoBehaviour where T : Mammal<T>
{
    [SerializeField] private List<Tuple<T, T>> _animals = new();

    public void AttemptBreeding()
    {
        foreach (Tuple<T, T> pair in _animals)
        {
            pair.Item1.HaveSex(pair.Item2);
        }
    }
}
#

i think this is called a fix-up pattern, but basically this is a structure where a type is templated to pair while child types of the same type

#

so a kangaroo which derives from mammal will only be able to HaveSex with another kangaroo

#

but that functionality is abstacted

#

which allows you to have a generic breeder class that can store collections of mammals, but the contract of the Mammal<T> class can store ANY mammal, but only one kind of mammal per instance

#

calling code could be

public class Farm : Monobehaviour
{
  [SerializeField] private Breeder<Cow> _cowBreeder;
  [SerializeField] private Breeder<Sheep> _sheepBreeder;
  
  private void UpdateBreeders()
  {
    _cowBreeder.AttemptBreeding();
    _sheepBreeder.AttemptBreeding();
  }
}
#

that's something incredibly powerful that you can't get strictly from compositional design

#

i only did the list of tuples to demonstrate that the generic type can also use type enforcement which is poggers as hell that you can do in the base class

somber tendon
#

🤔 interesting indeed...
using compositional, I can see that it cant be written that short... need to divide/define the breeding components first, then, well... it could be a long story

humble loom
#

using composition you'd have to define the same method uniquely for every component, and then have some other heuristic for determining how components can interact or where they belong

#

also the fixup pattern has this little weird syntax, because you have to template the child classes to themselves

#
public class Cow : Mammal<Cow>
{
    public override void HaveSex(Cow other)
    {
        //yoink the udders or something idk
    }
}

public class Sheep : Mammal<Sheep>
{
    public override void HaveSex(Sheep other)
    {
        // baaaaaaaah
    }
}
#

but that's how you enforce the type interaction

#

OH

#

i learned a thing

#

this is called CRTP (curiously recurring template pattern)

sour loom
main gull
astral python
#

Hi guys, can someone help me porting this JS code to C# ?

var XYIterator = function(width, height) {
    this.width = width;
    this.height = height;
    this.x = -1;
    this.y = 0;
}

XYIterator.prototype.next = function() {
    if (this.y == this.height) {
        return {
            x: this.width - 1,
            y: this.width - 1,
            done: 1
        };
    }
    this.x++;
    if (this.x == this.width) {
        this.x = 0;
        this.y++;
    }
    if (this.y == this.height) {
        return {
            x: this.width - 1,
            y: this.width - 1,
            done: 1
        };
    }
    return {
        x: this.x,
        y: this.y,
        done: (this.y * this.width + this.x) / (this.width * this.height)
    };
}```
flint sage
#

No?

astral python
# astral python Hi guys, can someone help me porting this JS code to C# ? ```js var XYIterator =...

Replying to myself, probably something like this :

public class IteratorResults {
    public int x;
    public int y;
    public int done;
}

public class XYIterator {
    int width;
    int height;
    int x = -1;
    int y = 0;

    public void Init(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public IteratorResults Next() {
        IteratorResults result = new IteratorResults();
        if (this.y == this.height) {
            result.x =  this.width - 1;
            result.y =  this.width - 1;
            result.done = 1;
            return result;
        }
        this.x++;
        if (this.x == this.width) {
            this.x = 0;
            this.y++;
        }
        if (this.y == this.height) {
            result.x = this.width - 1;
            result.y = this.width - 1;
            result.done = 1;
            return result;
        }
        result.x = this.x;
        result.y = this.y;
        result.done = (this.y * this.width + this.x) / (this.width * this.height);
        return result;
    }
}```
compact ingot
astral python
#

Oh, thanks 🙂

misty walrus
#
        public void SelectTool(int index)
        {
            _selectedTool = index switch
            {
                0 => new LinkTool(),
                1 => new UnlinkTool(),
                _ => null
            };
            ToolChanged?.Invoke(index);
        }

I'm trying to make a sort of in-game editor with multiple tools. This is my manager's method for changing the currently active tool. I was hoping to somehow serialize a type on my tool buttons, and pass that along the click event to my manager. Since if this goes on like this, I doubt it will be scalable.

crimson ruin
#

How do people generally handle serializing of spawned objects? Taking care of persistent objects in the scene is fairly easy since they're already instantiated at load time, but spawned objects aren't as easily restored. Since all spawned objects come from prefabs in our case I'm thinking of putting the prefabs in the Resource folder & then serialize the prefab path, I can then instantiate these at load time & feed them the serialization data, but perhaps there's a different way to do it? Resource folder seems frowned upon overall by the documentation.

astral python
#

You can even create this scriptableobject at runtime and serialize the spawner array to update it and store its content.

glacial copper
#

Hey, I am using HDRP and I am trying to blit my targetTexture (of my Camera) to the backbuffer (to the view), I tried using Graphics.Blit but it seems to not do anything, and I tried using CommandBuffer which I don't find a way to render to the backbuffer,, any idea what I should do?

#

Basically the BuiltinRenderTextureType doesn't contain anything related to the backbuffer except the GBuffers, but I want one end buffer to write to

drifting galleon
glacial copper
#

@drifting galleon I'll check it out thanks

mighty latch
#

I don't think I understand async / await. I have a method that takes a long time that is currently running on the main thread, I want to make it so that it runs on another thread, and when it has finished running, returns its result on the main thread so it can be used. How do I do that?

drifting galleon
#

with async / await
post your code

round blade
#

Hey guys I am having an issue with building once I added 'Amplitude' an analytics plugin for Unity
When I try to build from XCode
I get this

#

Anyone who is able to point me in the right direction I would be eternally grateful

pallid reef
#

True

#

Oh, you know how to backpropagate it?

astral python
#

Guys, is it the right way to mix two Color32[] ?

    Color32[] CombineColors(Color32[] source, Color32[] colors) {
        int numColors = source.Length;
        if (numColors != colors.Length) return null;
        Color32[] combinedColors = new Color32[numColors];

        for (int i = 0; i < numColors; i++) {
            Color sColor = source[i];
            Color cColor = colors[i];
            combinedColors[i] = sColor * cColor;
        }

        return combinedColors;
    }```
novel plinth
#

You can use Color.Lerp instead.. Color.Lerp(somCol, otherCol, 0.5)...

#

But it still not the proper way of doing it, im on my phone, so cant really type that comfortably

astral python
#

Color final_color = Color.Lerp(someColor, otherColor, otherColor.a / 1.0f); better ?

novel plinth
#

Still incorrect, this what we called linear averaging... You'll get wrong color

astral python
#

Can be simplified but this is the idea

mighty latch
#

Am I using await correctly here? I want the main thread to keep running while waiting for a response from GetMatchListAsync

novel plinth
astral python
hollow garden
#

i don't think there's any color blending algorithm that perfectly mixes colors like they would irl

#

but ig you can get pretty close

novel plinth
#

There's a proper way, dividing by 2 just straight up wrong

astral python
undone coral
undone coral
mighty latch
undone coral
undone coral
#

it's all documented online

#

you should see in your snippet you're not using the await keyword

#

you can also look into UniTask to avoid common pitfalls

#

with using async/await in unity

astral python
undone coral
undone coral
#

i'm not 100% sure why you need to mix colors for that though

#

in code i mean

#

why aren't your nebulae textures? can't you put them on quads and have them blend with alpha?

nocturne tusk
#

If your colors are sRGB then you have to do an inverse gamma correction to convert it into linear mode and blend it there

astral python
nocturne tusk
calm ocean
astral python
calm ocean
#

And we use Twine for the writing

nocturne tusk
humble loom
calm ocean
#

It's a fairly new feature

astral python
humble loom
# calm ocean Yeah, it's in the Unity docs
public interface IFireRate
{
    public float RoundsPerSecond { get; set; }
}
public class Gun : MonoBehaviour
{
    [SerializeReference] private IFireRate _fireRate;
}

well this is a thing. I can serialize the NAME of the interface lol

calm ocean
humble loom
#

which unity version

calm ocean
humble loom
#

maybe a concrete implementation needs to exist?

calm ocean
#

So in your case, Add [Serializable] to IFireRate

#

Wait a second

#

Yeah, you need a concrete class

austere jewel
#

There is no drawer for serialized references without a value

#

if it's null, you will not get a drawer unless you use a custom package

calm ocean
#

I mean, if you think about it, there is nothing to serialize if there is no information

austere jewel
humble loom
#

@calm ocean you said you were able to serialize the type of IClass

calm ocean
humble loom
#

well that's just serializing lul

austere jewel
#

You can serialize instances in a field declared with an interface just fine with serializereference.

humble loom
#

yeah just not without a custom drawer. that's fine i spoze

#

literally all i want to do is just like
[SerializeReference] IFireRate _fireRate; and drag in a reference to a script that implements it

#

i feel like that should be out of the box

austere jewel
#

You cannot use UnityEngine.Object types with SerializeReference

humble loom
#

i'm aware. that was my original complaint, and someone was just telling me otherwise so i got my hopes up lol

#

wait why tf is this example working but mine wasn't. from the unity docs

austere jewel
#

Because they initialised it with values

#

It just draws nothing but the label when null

humble loom
#

oh that's interesting lol. so all i have to do is just, ok ic ic

#
public class Gun : MonoBehaviour
{
    [SerializeReference] private IFireRate _fireRate = new DefaultFireRate();
}

public interface IFireRate
{
    public float RoundsPerSecond { get; set; }
}

public class DefaultFireRate : IFireRate
{
    [field: SerializeField] public float RoundsPerSecond { get; set; } = 1.0f;
}

so something like this then should work

#

ohhhhhhhh i see why you used the custom drawer. so you can select from the concrete types via some enum

rocky mica
#

seeing all of this makes me glad I bought odin

astral python
rocky mica
#

unity drawer code has way too much boilerplate

astral python
#

small stars are rendered well but not the other stuff

humble loom
#

serialize an enum, construct a different concrete implementation based on the selection and expose the property as the interface

humble loom
#

i actually bought it but it's got so many features i haven't actually used it yet cause i wanna read up about it

#

oh it does, that's amazing. okay definitely using odin in everything now