#archived-code-advanced

1 messages Β· Page 184 of 1

shadow seal
#

Well, Material

fresh salmon
#

Yeah, but why reply again when answers were already provided

random goblet
#

I'm using png to made texture

rocky mica
fresh salmon
#

Answers must be valid though

rocky mica
#

if the guy is using a material he only need to change the maintex not the entire material, he might actually want to just replace it witha user provided texture, we dont know what they want

fresh salmon
#

That wasn't their question

shadow seal
#

I mean the initial issue is they didn't read the docs

rocky mica
#

^^

#

haha

#

but yeah, if he wants to change a material, then yeah he needs to use a valid resources path

fresh salmon
#

Also where do these ugly casts come from, Brackeys again?

#

as XYZ will return null if conversion can't be made, it's very error prone

#

Hard cast will throw an exception, way better in most cases

random goblet
#

The material is in the prefabs, it loads the database directory (but the material will always exist in the prefabs) and when clicking on a button it will inform the directory and set the texture in a GameObject

rocky mica
#

you gotta put it on the resources folder

random goblet
#

What I'm trying to do is load the material and set it on the GameObject, I'm tried this:
(WorldData.path = "Paints/Floor/Wood")

GameObject Model = GameObject.CreatePrimitive(PrimitiveType.Cube);
Material FloorPaint = Resources.Load("/Prefabs/GameData/" + WorldData.path + "/Texture.mat", typeof(Material)) as Material; 

Model.name = "Floor";
Model.AddComponent<BoxCollider>();
Model.GetComponent<MeshRenderer>().material = FloorPaint;

But don't work:

rocky mica
#

again, it needs to be

#

on

#

the resources path

#

thats what resources.load does

shadow seal
#

You've been sent there three times, take the advice

random goblet
#

I thought beginner would be the difficulty level of a code, and it's not in documentation

rocky mica
#

...

fresh salmon
#

Also please

Material mat = Resources.Load<Material>("path");

Use up to date, latest generic methods for this!

rocky mica
random goblet
#

Also because I don't speak fluent English, I often use a translator, it's difficult for me, if you don't want to help, just don't help

shadow seal
#

You've been told what to do!

rocky mica
#

haha

weary marsh
#

Hello, We are trying to fill our variables with the response from the API of a website. Our back-end programmer with no Unity experience gave us a .dll file and instructed us to make a async task for the call to the api. It sometimes works and we get the response and sometimes the call just times out and fails.

#

Is using a .dll and using Tasks an acceptable way to make a call to an API? We have always used UnityWebRequests before.

#

"ApiLibrary" is the .dll that we are using. Our software is being used on the Meta Quest 2 (So its an android environment)

flat rain
#

what do i need to do if i want to make an virtual "OS"

#

when i search the google i get prebuild real computers

cloud crag
#

Hello. Imagine There are 10 players. all of them must have the same boss. This boss will be randomly chosen from 5 bosses and be there for about 2 minutes, before next randomization. I want all players to have the same boss at the same time. I think time problem is solved using Greenwich's time (UTC) but generation gives me different bosses in different players. I tried to give the same seed every player (Depended on that Time) But it didnt work. can you help? Without using server to do that for me or with server. Thanks

fresh salmon
#

As for why it sometimes times out, you'll have to debug that out

weary marsh
#

I see. Thank you. On the pc environment it works near perfectly but on the Quest 2, we have to keep restarting until it randomly works right now.

fresh salmon
#

Also I think it's possible to simplify the code down to

Product product = await Task.Run(() =>
{
  ApiProvider ap = ...;
  return ap.GetProductDetail(ProductId).Product;
});

Other than that the async code looks good

#

What's pretty weird is that the API doesn't directly provide some async code

#

But you could try querying the API without async first, to eliminate the potential issue of "async not supported on this platform" like on WebGL

weary marsh
#

Thanks a bunch, I will look into these.

undone coral
undone coral
willow aspen
#

So I need to accurately (a few approximations are fine) calculate drag on a mesh. To do this, I need the cross section of the mesh. I saw a post on the internet that suggested

  1. Take pictures of the mesh from different angles
  2. Count the number of effected pixels
  3. Determine area using coloredPixels / totalPixels * someSizeFactor
    /**
     * Drag is always opposite to motion. Since drag is dependent on the area
     * exposed to the fluid (NOT VOLUME), we can do the "belly flop maneuver"
     * (flip sideways to increase drag). TECHNICALLY the drag coefficient will
     * also change based on direction, but let's not go overboard with the maths.
     *
     * Equation: F = 0.5 * fAv^2
     * f = drag coefficient, 0.3 = car, 0.05 = plane foil, 1.0 = horizontal 
     */
    public Vector3 CalculateDrag() {
        Vector3 force = new Vector3(velocity.x * velocity.x, velocity.y * velocity.y, velocity.z * velocity.z);

        Vector3 n = force.normalized;
        float area = crossSectionLookup[Mathf.RoundToInt(n.x), Mathf.RoundToInt(n.y), Mathf.RoundToInt(n.z)];
        force *= 0.5f * dragCoefficient * area;
        
        // Make sure the drag is opposite to motion
        force.x *= velocity.x > 0 ? -1 : 1;
        force.y *= velocity.y > 0 ? -1 : 1;
        force.z *= velocity.z > 0 ? -1 : 1;

        return force;
    }```
#

I have this float[,,] crossSectionLookup that I want to fill in the Start method, but I am unsure on how to approach this. I would normally create a computeshader and simulate each ray, but I don't think ray-mesh intersection is possible on gpu.

        crossSectionLookup = new float[3, 3, 3];
        for (int x = -1; x <= 1; x++) {
            for (int y = -1; y <= 1; y++) {
                for (int z = -1; z <= 1; z++) {
                    Vector3 direction = new Vector3(x, y, z);
                    
                    crossSectionLookup[x, y, z] = 0f;
                }
            }
        }
gray pulsar
willow aspen
#

That's a good idea, I'm currently trying to calculate each direction from a 3x3x3 cube, but Physics.RayCast is being mean to me

#

Currently it is causing a D3D11 device removed error

gentle yew
#

Hello πŸ‘‹
Are there any best practices in regards of injecting values into [SerializeField] private fields of MonoBehaviours for the purpose of unit testing? As far as I can tell, there are 3 options:

  • Option A: Create a new Init() method just for the purpose of Unit testing (I dislike this)
  • Option B: Create a new scene with properly configured monoBehaviour (Also against this)
  • Option C: Use reflection to get private fields and inject proper values inside (Kinda ok? It's somewhat volatile though)
sly grove
gentle yew
#

Hmmm yeah? That seems reasonable. It's a lightweight version of B I guess

#

Ah I still kinda prefer reflection here. B and D do have a flaw of not being able to test what happens if you fail to provide any of those parameters. How would you test that the method throws a certain kind of exception (or does whatever else) if no value was provided for one of those fields? Would you create another prefab?

native beacon
#

@willow aspen couldn't you just use a bunch of raycasts along the direction of travel?

sly grove
#

You'd simply create a prefab for that test case though

#

E.g. one that's missing whatever required value

undone coral
#

it sounds like your computer is having issues

undone coral
willow aspen
#

No

undone coral
willow aspen
#

Most are. Some aren’t.

undone coral
gritty zodiac
#

Hello, I'm trying to use ECS in the script but I get an error that Entities doesn't exist. I already installed ECS in the Package Manager, what else am I missing?

using Unity.Entities;

public class IntroSystem : SystemBase
{
    protected override void OnCreate()
    {
        base.OnCreate();
    }
}//*/
undone coral
#

you can generate concave meshes from convex ones using something like vhacd

gritty zodiac
sly grove
undone coral
#

then, let's say that instead of drag, you're calculating the "aerodynamicness" (1 - drag) of the object

gritty zodiac
sly grove
#

which word specifically haven't you heard of?

gritty zodiac
#

that worked thanks @sly grove

undone coral
#

then the aerodynamicness of your object is
sum of
the direction of motion dot producted with a vertex
times the distance of that vertex to its neighbors

#

@willow aspen this isn't perfect but do you see the idea here

#

observe a sphere will have an aerodynamicness of zero from all directions, which makes sense

willow aspen
#

I am too tired to reason put vector math

undone coral
#

lol

#

okay

#

well think of some objects

willow aspen
#

Do you mean the normals of the vertices?

undone coral
#

no

#

i mean literally from the center of mass of the object

#

treating them as directions

#

we're trying to approximate their contribution to the "mass" of the object in a certain direction

#

it works for a lot of shapes

#

like a pole (a long, narrow cylinder)

#

most of the "vertices" of the pole would be in the same direction of its motion

#

so it will appear highly aerodynamic, i.e., low drag

#

which makes sense

#

i think you would actually treat the origin not as the center of mass but as a point, "infinity" away from the direction of motion behind the object. that is the same as projecting the 3d mesh onto a 2d surface, i.e., a picture of the object from that view

#

which is the inspiration for a simple approach here

#

that's what an orthogonal camera image is

willow aspen
#

You’ve given me some stuff to think about, thanks

undone coral
#

cool

#

you definitely do not want to raycast

#

or voxelize or stuf like that

#

it's obscuring that you already have data about the shape of the object and you need to interpret it correctly

gritty zodiac
#

Hello what does this class "CapsuleTag" belongs to? I don't know what library it came from. Is it using System.Collections;?

novel wing
buoyant vine
gritty zodiac
unkempt nova
#

So I'm new to async coding, using UniTask. I'm making a whirlwind ability. When the mouse is down, it spins. When the mouse is up, it should stop spinning. It has two modes, I'm currently testing the non-duration mode, so you can ignore that bit. It all seems to be working, except that my Cleanup method isn't being called. I was under the impression that I needed to cancel outside of the async method, listen for the cancellation in the task and make sure to dispose of it. The task appears to stop (I stop spinning) but I don't think WhirlwindCleanup is being called. Was my assumption about needing to listen wrong, and it just cancels the task?

Full code: https://www.toptal.com/developers/hastebin/ikipuvimer.csharp

Relevant bits:

private async UniTask WhirlwindSpin(CancellationToken token) {
        float remainingDuration = whirlwindSO.Duration;
        float timeSinceLastDamage = 0;

        while (whirlwindSO.WhirlwindMode != Whirlwind.WhirlwindModes.Duration || remainingDuration > 0) {
            Debug.LogFormat("Spinning");
            if (token.IsCancellationRequested) {
                Debug.LogFormat("Cancellation requested!");
                WhirlwindCleanup();
            }
            remainingDuration -= Time.deltaTime;
            timeSinceLastDamage += Time.deltaTime;
            if (timeSinceLastDamage >= whirlwindSO.DamageInterval) {
                DealDamage();
                timeSinceLastDamage = 0;
            }

            // Spin the character. Temporary, just for testing.
            Quaternion newRotation = _character.transform.localRotation;
            newRotation *= Quaternion.Euler(0, 0, Time.deltaTime * 500);
            _character.transform.rotation = newRotation;

            await Async.YieldWithToken(token);
        }
        WhirlwindCleanup();
    }

private void WhirlwindCleanup() {
        Debug.LogFormat("Ending whirlwind, cleaning up");
        cancellationTokenSource.Dispose();
        _character.transform.localRotation = startingRotation;
    }
#

I've fixed it by just calling WhirlWindcleanup after StopWhirlwind, but I'm confused and would like some explanation. Are UniTasks different from Tasks in this regard? I was following a guide on regular Tasks with listening for the cancellation

tribal pivot
#

Side question, why use async for this instead of coroutines?

unkempt nova
#

Just trying to learn UniTask

#

Also I'm thinking we'll need it later when things get more advanced

#

Senior dev already suggested I switch over, seemed like a good opportunity

tribal pivot
#

What i personally found is that there still are cases for coroutines. This is my general rule of thumb:

  • If i want to wait for a result that will come later, use async
  • If i want to do something over multiple frames, use coroutines
unkempt nova
#

Makes sense

tribal pivot
#

But eh i dont see an issue i think. I'd even say WhirlwindCleanup is called twice

unkempt nova
#

Nope, just once per up/down cycle

#

In the edited code

tribal pivot
#

I dont think you need to call canceltoken.dispose. I think i would personally add the iscancelrequested in your while-condition itself.

unkempt nova
#

I wanted to pop it out so I could have it call cleanup

tribal pivot
#

Dont you want to stop your loop/routine if the cancelation is requested?

unkempt nova
#

Yeah, that's what I'm doing

tribal pivot
#

e.g. if cancel is requested, you still go on. You dont break.

unkempt nova
#

I should break though, forgot that

tribal pivot
#

Where? You call cleanup, but thats it? You then still go on with the loop, no return no break nothing

unkempt nova
#

Yeah, forgot the return/break. Shouldn't be relevant here though, confused about why the method isn't being called

#

Or maybe it is

tribal pivot
#

I would just while(!token.IsCancellationRequested && whirlwindstuff){} WhirlwindCleanup();

unkempt nova
#

Fair enough. Still wondering about my question though

#

Also not sure if I even need to make sure I'm disposing of it like this

tribal pivot
#

I dont think so

unkempt nova
#

Anyone know of any good tutorials or resources for learning UniTask in general? Been coming up dry. Docs are good, but a bit too terse. Not good for best practices, use cases, etc

#

Unless there are more docs than just the github page

gentle yew
# sly grove Which method exactly are you testing? A unity callback? Or something else?

I'm testing a method that Initializes the game scene (spawns stuff, sets values, whatever else is needed).
I've also asked this on the forum https://forum.unity.com/threads/constructor-alternative.1272353/#post-8075603 and someone suggested Zenject. I've been meaning to get into it for a while and will be proceeding with that then

plucky laurel
#

Create an "Init" method for injecting whatever is an inspector reference just for the purpose of testing.
"Yuck." can lead to places, especially with using massive frameworks and heavy reflections just to avoid simple approach

modest bane
#

anyone got any ideas for networking a floating origin via fishnet? my goal is a scene where each player can fly infinitely in any direction. i wasn't surprised when my singleplayer floating origin solution didnt fully work. one client sees the world update correctly and the other sees that player looping infinitely in the same space.

plucky laurel
#

secondary "real" coordinate system

#

on doubles

#

any transforms in scene are local representations of real coordinates

unkempt nova
#

So I've got this switch statement, and want to try the new C# 8.0 syntax to make it less ugly. I'm fading an object out. Trying to determine what happens when it's done fading, for context

switch (FadeOutMode) {
            case FadeOutModes.Destroy:
                Destroy(gameObject);
                break;
            case FadeOutModes.Pool: throw new NotImplementedException();
            case FadeOutModes.Disable:
                gameObject.SetActive(false);
                break;
            default: throw new ArgumentOutOfRangeException();
        }

I'm trying to do something like this:

void _ = FadeOutMode switch {

            FadeOutModes.Destroy => Destroy(gameObject),
            FadeOutModes.Pool => throw new NotImplementedException(),
            FadeOutModes.Disable => gameObject.SetActive(false),
            _ => throw new ArgumentOutOfRangeException()
        };

But I can't use a local variable of type void. I don't want a return value, I just want to do these things. Not finding any examples of how to use it this way, is it possible?

fresh salmon
#

It's not possible

unkempt nova
#

😒

#

ty

novel plinth
#

you can just return a delegate

var something = new Action(()=>
{
    Destroy(gameObject);
);

(FadeOutMode switch
 {
    FadeOutModes.Destroy => (Action)something,
    _ => throw new ArgumentOutOfRangeException()
 })();
modest bane
#

thanks @plucky laurel ill give that a go

random dust
#

That said, you could try this:

var @action = FadeOutMode switch {

    FadeOutModes.Destroy => () => Destroy(gameObject),
    FadeOutModes.Pool => throw new NotImplementedException(),
    FadeOutModes.Disable => () => gameObject.SetActive(false),
    _ => throw new ArgumentOutOfRangeException()
};

@action();
#

Not tested btw

#

I changed your destroy and disable state into a delegate, since your version actually invokes the method, rather than specifying a way to invoke

#

After that, make sure to actually invoke it.

random dust
novel plinth
#

wut!? ... what makes yours different than mine

#

pls elaborate

random dust
#

You miss half the states

novel plinth
#

bruh

fresh salmon
#

Both versions just hack out the use of switch expressions

random dust
random dust
#

I suppose returning a delegate kind of omits the issue though

fresh salmon
#

Yeah, a regular switch statement looks and feels better

random dust
#

Dunno, I suppose inline switch statements like this are fine

#

You return an action to invoke depending on the state, which is fine

fresh salmon
#

Fine, but not pretty for completely different instructions in the lambdas

random dust
#

How is it different?

fresh salmon
#

A destruction, an exception throw, and a disable

sage radish
#

The delegates create garbage

fresh salmon
#

And that too

final steeple
#

x switch is for expressions that have results

#

If your expression has no result, you cannot use expression switch

#

And all of the suggested alternatives have negative performance drawbacks

#

Trust me, just use a normal switch

fresh salmon
#

And hacking it to forcefully make it return a value in some cases it shouldn't, is just bad practice

final steeple
unkempt nova
novel plinth
#

why you want to do this, I've no clue πŸ™‚

unkempt nova
#

Fused's method didn't compile, wasn't able to find correct type for action iirc

unkempt nova
#

It's interesting

novel plinth
#

this is not nicer compared to the regular switch statement

#

delgates allocate, you know

unkempt nova
#

Yeah, fair. I was thinking I was just making a small syntax error originally

novel plinth
#

aight, goodluck πŸ‘

random dust
#

Honestly just do whatever you want. You learn from it and nobody is going to notice the nanosecond it takes longer to process it

random dust
unkempt nova
#

Yeah, just didn't understand what the literal was for I guess

random dust
#

I suppose the apostrophe does not work as action is not an actual keyword even though I thought it was. Was that the error?

unkempt nova
random dust
unkempt nova
#

This is what I was thinking, the new syntax is nice. I would like to use it. Seems strange to me that this needs a workaround

random dust
unkempt nova
#

What apostrophe?

#

The @ ?

random dust
#

change @action to something else without the @

unkempt nova
#

Changing it to action works, without the @

random dust
#

I see, then it's indeed fine to just use action

unkempt nova
#

Yep

#

Thanks, sorry for saying it was wrong. Just didn't understand the @

random dust
#

It's fine. you put an apostrophe before your variable if it's a reserved keyword, like event.

#

so you would do @event

unkempt nova
#

Ah, you keep calling it an apostrophe too

random dust
#

Oh, it's not an apostrophe

unkempt nova
#

But yeah, I see why you were using it now. Just thought action was reserved

sage radish
#

The error isn't related to the @ though

unkempt nova
#

Yeah

random dust
#

Let me check

unkempt nova
#

Needs to know what to return from the switch, and the types are ambiguous so var bails out

#

That's my understanding of it

sage radish
#

Yeah, the compiler doesn't treat Action as anything special, so it doesn't assume you want to use it here.

#

Any void delegate with no parameters would be valid here.

#

() => doesn't create an Action, it creates a delegate instance that can be assigned to any delegate type that matches the signature.

unkempt nova
#

Makes sense

random dust
#

Yup, seems like it

novel plinth
#

thus, you need to cast it as shown in my example

unkempt nova
#

When does the delegate allocation occur? If I were to make action here a class variable, would I just get the one allocation? Or is there one each time it's assigned

#

I'm assuming when it's assigned, and the allocation comes from a boxing operation of some kind?

#

Maybe not even boxing, if they're just the same type. Not sure how that works

novel plinth
sage radish
#

There can also be an additional allocation for display classes. That's when you have lambdas that need to capture an outside variable.

unkempt nova
#

Is it the new keyword triggering it though? In this use case, if I were to use the local variable, I'm not using it (a new keyword)

unkempt nova
#

Not sure what you mean about "display" classes though. Just classes using the delegate, that might capture variables?

unkempt nova
#

Oh, I see. That just sorta happens to also use a delegate though

#

Since it's returning one and creating one in the process

sage radish
unkempt nova
#

Oh right, I didn't think about that

sage radish
#

Action action = SomeMethod is the same as Action action = new Action(SomeMethod)

#

It's implicit

unkempt nova
#

That makes sense. Thanks. So this would create several allocations

sage radish
unkempt nova
#

Ah, was thinking that. I see 2 alloctions here then, maybe more with the throw

quaint flint
#

Hi ! Would you recommend JSON to keep informations such as :

  • user's name
  • path to a picture

those kind of simple informations

onyx cradle
#

id say just use player pref system

#

if the data doesn't need to be secured, then id use them

quaint flint
#

I'd want it to be modifiable by the user when they start the app

onyx cradle
#

yeah you can modify them in script

novel wing
onyx cradle
#

PlayerPrefs.GetString and PlayerPrefs.SetString

quaint flint
#

I see I see

onyx cradle
#

yeah but player name and file path are both strings so I wouldn't say a Json file is needed

quaint flint
#

I think I'll need to keep track of some boleans and stuff in the future too

#

so ill try with JSON
but if it's too complicated i'll use payerpref

onyx cradle
#

oki

#

I think player prefs can store float int and string (ofc you could use 0 and 1 for boolean easily if you want to)

flat rain
#

how can i make a computer "OS" in unity

#

something similar to PC Building simulator lets say

rugged radish
#

hey guys, what's the best approach for checking if a method was called in the main Unity's thread ?
need to implement the same kind of check like the UnityEngine.Random has (it throws an exception if you access it from outside the main)
So far I only found something about using Unity's lifecycle callbacks to capture the main thread and use that reference to check against Thread.CurrentThread

#

but it kinda looks hacky, so thought maybe there's a better way

final steeple
#

There are internal methods on UnityEngine.Object that allow you to check for the main thread, but I prefer not to rely on reflection if I can help it

rugged radish
#

seems like they are not exposed in the API though
I'm not going to rely on this in the builds, need it for development, so that every time a task tries to use an instance it's not supposed to it would crash

final steeple
#

Yeah, they're private methods unfortunately

#

I made a proposal thread to expose them (and a few other APIs) but so far it doesn't seem to have caught on

rugged radish
#

it does look useful for development for sure

final steeple
#

The MainThread class does the job for now though, it's about as close as you can get currently without reflection

rugged radish
#

yeah, ty πŸ‘

undone coral
#

it has a helper, and it also has await UniTask.SwitchToMainThread()

undone coral
#

if your goal is the ceremony of doing such a thing, try embedding BOCHs into unity and render the framebuffer to a texture

flat rain
#

ROI ?

#

im kinda a "student" can you give some of the appoaches ?

rugged radish
#

not even entirely sure about the tasks yet
they did make the game 100% responsive during world generation, but I'm still debating if this is the way to go

undone coral
#

you can't use plain tasks very easily in unity

#

you'll want all the helpers unirx brings

#

especially for dealing with editor mode

undone coral
rugged radish
#

I'll give it a go for the current branch then πŸ‘
was doubting because native tasks have good support like breakpoints and being the native language concepts

#

I guess the library builds on top of that rather than trying to replace it

small badge
#

If you're specifically doing tasks I would personally prefer UniTask over UniRx (they're both by the same developer and can interoperate if needed). UniRx is heavily built with the Reactive Extensions paradigm in mind, which is by no means a bad thing but it builds a lot of extra concepts on top of tasks which you may or may not want.

sly grove
#

I had no idea there was a difference between the two

#

goes to show you how tuned into React I am

rugged radish
#

I thought it was a single library too, granted I did basically zero research yet

small badge
#

I'm not sure of the exact history, but as I understand it UniTask specifically does just the aspects of UniRx that are "make Tasks work nicely and efficiently in Unity", without much or any of the React stuff. But it's not a subset or dependency of UniRx, it's its own independent library.

sly grove
#

makes sense

small badge
#

I think UniTask may have been a later attempt by the developer to hive off just that part of the functionality from UniRx? But I'm not certain.

rugged radish
#

good to know, I'll need to review both then, not sure yet, but I might need reactive part too

final steeple
#

UniRx and UniTask are a bit heavyweight if all you want is to access the main thread

#

They end up customizing the PlayerLoop to install a callback to do things on the main thread, which I'm not personally a fan of

#

(Unity already has a built-in SynchronizationContext implementation for this purpose)

undone coral
#

and has its own glitches

final steeple
#

Such as?

undone coral
final steeple
#

The current UnitySynchronizationContext could be more efficient, but I wouldn't call it bad

undone coral
#

the unitask one avoids a bunch of pitfalls

final steeple
#

What pitfalls?

#

I'm genuinely curious

#

You said it has glitches but never mentioned what they actually are

#

I'm looking through its code now and I don't see any thread safety violations, so it can't be that

undone coral
#

i don't remember the specific bugs i encountered

#

i vaguely remember it had to do with putting in a lot of in-flight tasks

#

i'm sorry... for some stuff it was so long ago

final steeple
#

If it was a while ago it might have been fixed

#

UnitySynchronizationContext did used to have some issues

#

I think back in... Unity 2017? 2018? Or so there was a race condition that could result in one of your callbacks being called more than once

#

It was eventually fixed though

#

So I imagine that might be what you encountered

undone coral
#

only the unitask one has been flawless

fresh basalt
#

is it possible in StateMachineBehaviour class to get what part of the state has been completed?

#

i want to use it with lerp to move collider object

humble onyx
misty glade
#

Need a quick/clean way to get 3 random, distinct elements from a dictionary. Thoughts?

List<T> randomTs = dictOfTs.Values.ToList().OrderBy(x => Guid.NewGuid()).ToList().GetRange(0, 3);

Vomit or nifty? (assume dict always has 3+elements)

spice wave
#

How do I get the InputAction control type class? So Axis would return a float, and so on?

outer juniper
#

Hi, Does anyone here know how to project a 2:1 texture to equirectangular cylindrical projection of the same aspect ratio and resolution? I've been trying several solutions over the last few days and have not had any luck, any help would be appreciated.

hybrid carbon
misty glade
#

I'm picking a computer controlled lineup of 3 enemy characters from the pool of about 50, so if they were consec the player would always get the same players, or at least like 2 of them, if that's what you were thinking

#

{ 1, 2, 3, 4, 5, 6, 7 } might get 123, 234, 345 etc, which might feel stale

fickle mango
#

make a new List with all your enemies, when you select one you also remove him from said list

hybrid carbon
misty glade
#

shouldn't, it'd just be allocating the pointers, not the full objects

#

but i still also would have to randomise that list somehow, which is mostly the crux of what i'm asking πŸ™‚

#

quick/dirty/easy/mostly-random ways to randomize a list

hybrid carbon
#

Random.Range

misty glade
#

(I'm actually ToList()-ing twice in my solution above, which .. maybe not great)

fickle mango
#

you don't need to randomize the list, just the index of the enemy you take

misty glade
hybrid carbon
fickle mango
#

you mean never 3 adjacent or sometimes 3 adjacent if the rng god wills it?

misty glade
#

if there's 50 elements, and I select a random, then get [i] and [i+1] and [i+2] that'll be stale pretty quick

#

3 adjacent is fine, but 3 adjacent every time isn't

hybrid carbon
#

Random.Range 3 times is what you want

fickle mango
#

then just randomize the index 3 times

misty glade
#

i'm not sure i like doing the "get a random int and ensure it hasn't been picked already" because it'll end up sloppy

hybrid carbon
#

It’s not sloppy

#

It’s exactly what you’re asking for

fickle mango
#

you could also make a List<int> of all the indexes and remove the onces you already picked but you might as well make a new List of enemies

misty glade
#
int i0 = Random.Next(50);
int i1;
do
{
  i1 = Random.Next(50);
} while (i1 != i0);
int i2;
do
{
  i2 = Random.Next(50);
} while (i2 != i1 && i2 != i0);

I feel like that's ugly

fickle mango
#

You could also only reset the List once there are only a certain number of enemies left, thus preventing getting the same enemy back to back

misty glade
#
List<MyObject> allObjects = allObjectsDict.Values.ToList();
MyObject one = allObjects[Random.Next(allObjects.Count)]; 
allObjects.Remove(one);
MyObject two = allObjects[Random.Next(allObjects.Count)]; 
allObjects.Remove(two);
MyObject three = allObjects[Random.Next(allObjects.Count)]; 
allObjects.Remove(three);
#

it's not so much a number of enemies left, it's a "battle" mode thing, 3v3

hybrid carbon
#

At the end of the day it’s all syntax sugar

misty glade
misty glade
hybrid carbon
#

I lean towards least buggy

misty glade
#

this is the concept

#

select 3 crew, go to battle, turn based blah blah blah

#

so as long as i have a quick/easy way to select 3 crew from a pool of dozens, that's good enough

#

probably harder fish to fry with the AI part of it

hybrid carbon
misty glade
#

cool - take grabs the first?

#

nice, i like that

hybrid carbon
#

Yeah the first 3 of the randomized list

misty glade
#

slightly different implementation, going from dict to 3 items - myDict.Values.ToList().OrderBy(x => rnd.Next()).Take(3) but still the same .. thanks

undone coral
#

has anyone seen an example of RegisterThread in a native plugin?

#

i'm trying to profile a native thread

undone coral
#

nevermind i figured it out

outer juniper
#

Hi, Does anyone here know how to project a 2:1 Simple Cylindrical texture to equirectangular cylindrical projection of the same aspect ratio and resolution? I've been trying several solutions over the last few days and have not had any luck, any help would be appreciated.

misty glade
#

OK. Funtime.

I have an arbitrary sized grid (let's say 5x5). It has grid elements with an int contents = 1, 2, 3, 4... A "move" is moving any item on the grid to another unoccupied space on the grid.

When there's 3 or more items orthogonally connected, they merge into the next level. This is a good thing.

I need to write an algorithm to attempt to find a move (by the computer). Any ideas how to break this down?

I already have the logic to detect a completed "chain" (recursive "painting" of matching neighbor count) but am struggling to find a way to positively find a move when one exists.

#

"move" on a 4x4 grid shown here

#

I suppose I could iterate over every "drone" on the board and find every possible move and check for chains, but... that's going to be potentially really slow, I think

#

I suppose I could at least do that and prune search trees when obvious fail cases exist (like there are < 3 of one kind of item on the board)

undone coral
# misty glade OK. Funtime. I have an arbitrary sized grid (let's say 5x5). It has grid eleme...

there are lots of ways to prune a destination. but in principle, visiting every element of an NxN grid is not bad.
since there will never be a situation where there are three orthogonally connected pieces, you only need to mark when an item has a orthogonal same type neighbor.

var interestingMovesByType = 
 // for each pre-existing item
 items.SelectMany(item => 
     // examine its orthogonal spots
     GetOrtho(item)
       // are any the same type as me?
       .Any(neighbor => !IsEmpty(neighbor) && neighbor.type == item.type) ?
       // if so, return all the empty ortho spots as me as an interesting move
      GetOrtho(item)
        .Where(neighbor => IsEmpty(neighbor))
        // store a tuple that stores the empty neighboring location and the type it was interesting for
        .Select(neighbor => (loc: neighbor, type: item.type)) :
       // otherwise, skip this (empty)
      new [] {}
   ) // now we have the interesting moves. let's group them by type of tile
   .GroupBy(interestingEmptyNeighbor => {
     var (loc, type) = interestingEmptyNeighbor;
     return type;
   });
misty glade
#

Yeah.. Did something along those lines. A couple of prunes, a little bit of testing, was no problem even under my fake load

undone coral
#

yeah

misty glade
#

I often overestimate the impact of something but.. it's hard to really load test this (since the computing is on the server of a multiplayer game)

#

but it was in the nanoseconds even for a 10x10 grid so.. no worries

#

i closed down the IDEs for now.. 12 hours is enough punishment for one day

undone coral
#

you could achieve O(1/2 grid tile count) if you switch from visiting every existing item to every empty space when the board is about half full

#

but i wouldn't worry about it

#

i don't think you need to do any pruning

#

it won't beat what i wrote

#

i'd keep it simple

misty glade
#

i actually am really low on the actual checks - i prune any checks against drones that can't possibly make a chain (ie, 2 or less of them on the battlefield).. so honestly average case performance for a 4x4 grid, even one that's reasonably full is like... 100 or 200 operations, it's.. nothing

#

i could prune big grids even further by keeping track of how many neighbors are in every square and then only checking ones that have 1+ to see if they'd get a chain, but.. yeah, i'm not going to work on it anymore .. it's fast enough πŸ™‚

#

fun little problem though, compared to doing UI work :p

undone coral
#

is there a way to use clang for windows il2cpp builds?

undone coral
#

and is there a way to make runtime initialize on load work for il2cpp?

flint sage
#

It does..?

undone coral
#

i set the Master compilation option

#

it's the only one i've tried, but it appears to have made my thing not work

#

does it matter if one of my native plugins were built with clang?

tough tulip
undone coral
#

is there anything arcane i have to do

undone coral
#

the only thing i changed between these two builds was il2cpp + master versus mono

#

is it may be related to master?

tough tulip
nimble compass
#

is there a way to set up a process that actively checks to see if there's an object of certain tag within a range of it?

#

surely theres a much more simpler way than I am trying (unsuccessfully) to do

undone coral
#

maybe this is related?

[           0s] Delete 71 artifact files that are no longer in use. (like Library\Bee\artifacts\mvdfrm\UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule.dll_437B411B571BF089.mvfrm)

from the build log

tough tulip
nimble compass
#

so is layering essentially like filing? Like, "you, you, and you all go in here!"

undone coral
#

2021 can't fully idsable stripping

tough tulip
#

and engine stripping? not sure if that's gonna help with this

undone coral
#

i see that runtime initialize on loads.json correctly references my method

nimble compass
#

Ok so for now I'll just focus on getting a smaller part working. I have the character able to automatically move to the enemy. The next step for what i have planned is to have something in play to see if the enemy is within a range of like, 1 for example. How should I go about starting that?

undone coral
#

@tough tulip i give up... it's too late to diagnose this

quaint flint
#

Hi
I don't really understand Serialization, SerializeField in Unity
can someone please explain it to me ? I've read the documentation but i'm lost (I've had classes about object oriented development but that's hard)

tribal pivot
#

(not entirely sure this is code-advanced)
What dont you understand?

quaint flint
#

(dunno, seems pretty advanced to me tho)

I don't understand in what context i'm supposed to use that

tribal pivot
#

You dont have to use it.

But lets say you have a player, and that player can move. It would be nice if you can edit the movement speed without having to change the code

#

So you serialize a float speed, and change that.

#

Thats it

molten zodiac
#

you can use serialzefields to show private variables in the inspector. but they will not be accessible by other scripts

quaint flint
#

ooooh

#

ok

#

because I saw it's necessary to use JSON
and I want to make a Player Class that has basic attributes (name..) that I can call in other scripts
like I have a script that'll modify an image based on a Player's attribute

tribal pivot
#

No

#

You dont use JSON for this

#

This is all magic to you. You just make a [SerializeField] or public, and Unity sets a value for you

#

This is all you need. Then fill it iin in the unity inspector, and there's your value.

quaint flint
#

JSON is necessary for another part dw
it's pretty complex but I need to save a ton of data so I'll put that in a json file I think

#

but thanks ! Now I understand

tribal pivot
#

Ok but thats something different then. I thought you were talking about editor serialization

quaint flint
#

yeah no sry i'm bad at explaining

flint sage
#

Unity's JsonUtility uses the same attributes

quaint flint
#

yeah i'm using that but it's hard as hell since I don't know a thing about databases, json..

undone coral
#

is there any insight into when d3d12 should be used over d3d11 / vice versa?

tribal pivot
undone coral
#

okay, i just tried d3d12 in my situation and it made a bunch of problems go away

maiden turtle
#

Do shaders care what line endings there are? I have some in LF, some in CRLF, and I was wondering if it's safe to convert them all to LF

mint sleet
#

Hello.

#
    public List<OperationClaim> GetClaims(OrgAdminDto organizationAdminUser)
    {
        using (var context = new EfVrCloudContext())
        {
            var result = (from orgAdminUser in context.OrganizationAdminUsers
                join baseUser in context.BaseUsers on orgAdminUser.AdminId equals baseUser.UserId
                join userOperationClaims in context.UserOperationClaims on baseUser.UserId equals userOperationClaims
                    .UserId
                join operationClaims in context.OperationClaims on userOperationClaims.OperationClaimId equals operationClaims.Id
                where baseUser.UserId == organizationAdminUser.AdminId
                select new OperationClaim
                {
                    Id = operationClaims.Id,
                    Name = operationClaims.Name
                });
            return result.ToList();
        }
    }```
#

I got sick. Where am I missing do you think?

#

I want to get the user claims but returns null.

#

Could you please somebody take a look into this? Thank you in advance.

small badge
# outer juniper Hi, Does anyone here know how to project a 2:1 texture to equirectangular cylind...

Well, like any projection you need to run a shader that converts pixel positions in the target projection to pixel positions in the source projection.
For cylindrical->equirect that's fairly simple: x coordinates are of course the same between both. For y coordinates, assuming -1 < y < 1, if you draw a diagram you should see that the conversion from the angles that are equirect y coordinates (ey) to the distances that are cylindrical y coordinates (cy) is just given by cy = h * tan(ey * halfpi), where h is a constant dependent on the height of the cylinder. You'll need to decide for yourself what to do at the cylinder caps where this gives out-of-range results (probably clamp, or return black).

flint sage
#

What's the attribute that lets you ignore methods in log stacktraces?

#

I know there's StackTraceHidden in C# but I thought htere was also an equivalent for Unity

shy violet
#

does unity seralization work like java serlaization
it creates a file with your Data

tribal pivot
#

How does java serialization work?

#

What serialization are you talking about?

#

@shy violet

shy violet
#

it makes a file

#

Pretty much

#

with your binary data

tribal pivot
#

So you are asking if Unity makes a file with your binary data?

#

When?

#

I mean, yes, Unity makes a file with binary data.

shy violet
#

Ok

tough tulip
flint sage
#

Definitely not what I'm looking for

tough tulip
#

i had a similar issue maybe last year with a custom logger. i ended up going with inline functions to prevent the internal assembly codes from being shown on stack trace.
idr if it worked in editor, but it does work in debug builds. the function name also is changed in release/master build (if the hiding method is the last method) although you dont get the full stack trace there obv

sage radish
flint sage
sage radish
flint sage
#

Yes

undone coral
tribal pivot
#

Yes.

#

And?

#

The latter not so much, most is abstracted away

old hollow
#

Hello! How can I calculate velocity change while taking into the account other things that could change player's velocity? For example jumping forward?

This is my current movement code:

Vector3 _direction = input * walkSpeed;

Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;

Vector3 acceleration = _direction - currentVelocity;

rigidbody.velocity += acceleration;

It works okay but there is one problem... If I would try and add force in the forward direction:

rigidbody.AddForce(this.transform.forward *   jumpPower, ForceMode.Impulse);

The object would just stop because the velocity change in the script above isn't taking this force into the account... Any help?

sly grove
old hollow
#

hmmmm

#

I didnt think about that

sly grove
#

The entire point of forces is to effect a change in velocity

#

aka the exact same thing you're doing

#

rigidbody.AddForce(acceleration, ForceMode.VelocityChange); would be equivalent to your += line

old hollow
#

Yup I'm aware of that I just didn't think about doing it for the forward jump too-

#

Thank you!

#

I'll give it a try

#

@sly grove hmm it did not help. I think the main problem is because the movement function is called in the fixedupdate function so it runs every phyics frame. It overrides any other velocity change im trying to do

#

that's why would I need to take jump force into the account in the line

Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;
tribal pivot
old hollow
#

Yup I am, but the problem is then if the player starts moving and the movement function is called again it will cancel out the forward jump force

#

even to I'm adding to the velocity not setting it directly

#

+=

#
Vector3 _direction = input * walkSpeed;

Vector3 currentVelocity = rigidbody.velocity;
currentVelocity.y = 0f;

Vector3 acceleration = _direction - currentVelocity;

rigidbody.velocity += acceleration;
tribal pivot
#

But its telling you to do movement via addforce

old hollow
#

you mean

rigidbody.AddForce(acceleration, ForceMode.VelocityChange);
```?
tribal pivot
#

Yes, thats how Unity wants you to interact with rigibodies

old hollow
#

yup but thats same thing as if I were to do
rigidbody.velocity += acceleration;

tribal pivot
#

Not really no. Unity really wants you to do it this way

sly grove
#

none of them will override anything

#

you've got some other code probably that's overriding it

old hollow
#

hmm but when I comment out this line

rigidbody.velocity += acceleration;

it works

#

i think the problem is because, if for example

sly grove
#

oh it's because

#

look at your code

#

you're literally adding the exact amount of velocity you will need to exactly set your velocity to a certain amount

old hollow
#

yup i know where's the problem I just dont know how to fix it

sly grove
#

you're doing rb.velocity = _direction in a roundabout way

#

what are you actually trying to do with this code?

old hollow
#

I'm just trying to move a character so it doesn't affect other forces

#

so the other forces aren't affected by it*

sly grove
#

you just want this then:

Vector3 _direction = input * walkSpeed;
rigidbody.AddForce(_direction);```
#

and tweak the numbers to your liking

#

and potentially add a clamping to the velocity

#

or drag forces

old hollow
#

hmm but what should I do then about the slow acceleration at the beginning of the movement?

tribal pivot
#

Are you sure you want to use the physics engine for your movement?

old hollow
#

Yes ._.

sly grove
#

That's how physics works

#

there's also nothing stopping you from doing more complicated things. Think about real life. You can quite explosively start running from a standstill but once you're going fast your legs can't move much faster so you can't accelerate well when you're already moving. You can write code to simulate that kind of thing - vary the amount of force you can apply based on your current velocity and the direction you want to apply the force in etc...

#

getting "good" feeling movement is not going to be as simple as a few clean lines of code in FixedUpdate. It's a very complex subject

old hollow
#

Yup I understand. And I'm not trying to do anything really complex right now it's a simple little stylized game but I was just stuck on this, I think I got it!

#

So thank you!

shadow seal
#

Does that even compile...

nimble compass
#

i didnt try yet LOL

shadow seal
nimble compass
#

cause i didnt know if it was an advanced question or not

shadow seal
#

It really is not, that code can't even compile for many reasons

nimble compass
#

I think I figured it out 😎 gimme 2 mins

fickle mango
#

that's silly code. You don't need to use GetComponent, you can just use .transform. And no point in the logic of this since instead of getting the transform you have to get this class, you are not really saving anything

shadow seal
#

Not to mention that you can't have a member with the same name as the class, and you're using a variable that doesn't exist

nimble compass
#

Ive just been trying to google but havent been able to find anything to help me get my code do what i want it to so i've been trying to stretch

nimble compass
small latch
nimble compass
#

When i ask questions there, no one answers me. I figured it meant no one knew the answer

shadow seal
#

This code is beyond wrong

#

I'm sure you can find help on Google for this too...

harsh grotto
#

dunning kruger in full force

sturdy comet
#

watch some beginner tutorials on gamedev in unity with c#....thats not good to say it nicely

fathom locust
#

Is there any way to define a constraint on an interface so that it can only be used with a class?

I'm trying to search through a generic list of an interface for elements of a specified type, typecast the element and return it. But it appears I can only do this for lists of elements with a class constraint.

outer juniper
#

Texture without the projection applied

#

texture with it applied

#
private Texture2D RegularToEquirectangular(Texture2D tex)
    {
        if (!_UseEquirectangularProjection)
            return tex;
        Texture2D output = new Texture2D(TexSize.x, TexSize.y);
        InitializeTextureSettings(ref output);

        float maxLon = TexSize.y / 2;
        float minLon = -TexSize.y / 2;
        float pi2 = Mathf.PI * 2;
        float halfPi = Mathf.PI * 0.5f;
        float height = TexSize.y;
        for (int x = 0; x < TexSize.x; x++)
        {
            for (int y = 0; y < TexSize.y; y++)
            { 
                float latitude = x;
                float longitude = Mathf.Clamp(height * Mathf.Tan(y * halfPi), minLon, maxLon);

                output.SetPixel(x, y, tex.GetPixel(Mathf.RoundToInt(latitude + _Offset.x), Mathf.RoundToInt(longitude + _Offset.y + maxLon)));
            }
        }

        return output;
    }
#

This is the script I'm currently using for this

outer juniper
#

Something like this where the poles get more distorted to resemble that of longitude of a sphere

undone coral
undone coral
#

okay

#

are you asking how to convert between cartographic projections?

outer juniper
#

yes

undone coral
#

did you try googling "cartographic projections library github"

outer juniper
#

the starting projection would be mappable to that of a cylinder

undone coral
#

because that's the answer

outer juniper
#

I have

#

I've been doing that for 3 days lmao and came up short each time, most require me to use shaders and I'm not interested in using that for my project

undone coral
#

okay

#

do you know what the term is for what you want to do?

fathom locust
# undone coral ?
public T GetState<T>() where T : IState
{
     return states.Find(o => o is T) as T;
}

This doesn't work because IState doesn't have a class constraint and therefore can't be typecast as a generic class.

outer juniper
#

equirectangular cylindrical projection

undone coral
#

i mean the process of turning one cartographic projection into another

outer juniper
#

oh, not quite?

undone coral
#

based on what i'm seeing online, the term is "reprojection"

outer juniper
#

yes, thats it

#

my memory is not so good

undone coral
#

you can research the implementation here maybe

outer juniper
#

Thank you, I'll have a look and let you know what I find

undone coral
#

okay

#

maybe this one will be best

undone coral
#

that's probably why it doesn't work

#

what are you trying to do?

fathom locust
#

Trying to find a state of a given type and return it, typecasted to that type.

undone coral
#

okay, then just use OfType

#

there aren't sealed interfaces in csharp

#

that's the feature you'd need to implement what you want

#

however, if you use an abstract base class instead, and mark the subclasses as sealed, it will work

#

@fathom locust how about this?

#

this correctly errors for me

#

then you can FirstOrDefault

fathom locust
#

I just thought of an alternative. Instead of relying on interfaces in the first place, I can get around the typing discrepancy by using a wrapper class for everything else I need.

regal olive
#

is it posable to build a custom editor that when typing in a string field it will try to auto complete from a list of words you have ?
want to enter item name and have it try and predict what im typing so i dont have to enter so many items manually or well less manually

unkempt nova
#

Sure

#

I've seen assets do it. Know of a free one that does it if you wanna see how they do it

regal olive
#

yea

#

please

unkempt nova
#

It uses a custom editor window though, but I imagine the process is similar

#

This bit here:

regal olive
#

ty

unkempt nova
#

Also a cool tool. np

novel plinth
#

I don't recall there's any public function similar to onValueChanged for uielements textfield, but yeah, registering a callback is the way to go

novel plinth
novel plinth
#

You proly don't need to make registercallback on your own, there is this event you can subscribe to

tight cypress
#

hi i need some help with a rotation problem, (quite new to unity) Please dm me if you have any idea!!! ill show you the script

frozen imp
#

@tight cypress Don't cross-post

reef wren
#

is GetComponentsInChildren order guaranteed? it is mentioned in docs that it internally uses recursion+dfs to search, but I'm really not sure if the order should be consistent

novel plinth
#

you can just sort it

#

oh wait, I thought you mean the plural version

#

yeah, use the plural version then sort it

reef wren
#

yes sorry. i mean the plural only

unkempt nova
#

I'd be safe and say it can't be, because the hierarchy can easily change

reef wren
novel plinth
#

based on what you want? how am i supposed to know XD

reef wren
novel plinth
#

if you're only looking for specific component, lets say just one, then just filter it

reef wren
novel plinth
#

there you go, then yeah, thats very possible

unkempt nova
#

Can use transform.getchild() to get their position in hierarchy, but you kinda lost me on why

reef wren
#

comp1
comp1-1
comp1-2
comp2
comp2-1
comp2-2

i want them in order like comp1, comp1-1, comp1-2, comp2, comp2-1, comp2-2 and so on

unkempt nova
#

Sounds like you're trying to basically use the hierachy as a list for multiplayer. Sounds like a bad time

unkempt nova
#

Because it can change and it wasn't designed to hold data like this

unkempt nova
#

So order can be wonky maybe, etc

reef wren
#

no the hierarchy isnt changing at all

#

its fixed in the prefab

#

not changing ever. order is same throughout the lifecycle of the scene and also the application

unkempt nova
# novel plinth huh?

It sounds like he's trying to use the hierarchy as a form of data storage, by pulling values from the hierarchy instead of some data class

#

Just sounds like a bad time, as I've noticed how vastly hierarchies differ in multiplayer

reef wren
#

as in the position of the components transform

unkempt nova
#

Yep. You're using the stored hierarchy position. That's using it to store data.

#

Or maybe I'm just confused. I'm bowing out

reef wren
# unkempt nova Yep. You're using the stored hierarchy position. That's using it to store data.

let me explain fully what i'm doing in here. i have multiple objects in scene, whose main work is to denote their world position and rotation in the scene.
i send the number of objects to the server for initializing. basically the server just stores the total number of the component instances.

then to spawn some objects at the said points, the server will send a random index ranging from [0, componentInstances.Length-1]. basically just a number to client instead of vector3 positions and quaternion rotations (to save bandwidth)

then when the client receives the index, it will lookup for the index, and then get a world position and world rotation and spawn the object there.

the problem here is that, the index lookup is not same for all clients. because i'm doing GetComponentsInChildren whose order is not same across all clients.
array[10] for client1 and array[10] for client 2 are not the same when the list is initialized with GetComponentsInChildren<T>(true)

the fix im looking for:

  • sort the collection based on something, preferrably by hierarchy order, or anything. but i just want to guarantee the order across all clients with that sort.

what i'm not sure of here is:

  • if GetComponentsInChildren is supposed to return in order or not. If it should return in order, i dont know what then. But if it doesn;t return in order (which my case clearly shows) I will obviously go with sorting
unkempt nova
#

the problem here is that, the index lookup is not same for all clients. because i'm doing GetComponentsInChildren whose order is not same across all clients.
array[10] for client1 and array[10] for client 2 are not the same when the list is initialized with GetComponentsInChildren<T>(true)
This is what I mean by using the scene to store data. I'm not sure why the order is different. Maybe GetComponents order can't be relied on. Maybe one of them was moved or reparented or simply disabled. I know inactive objects will not be searched, and some netcode will disable objects until their client is connected, or under other circumstances. This is why I say using it to store data is bad.

With that said, as an alternative, I could suggest storing these "position" game objects in a list instead. Put this list on whatever object needs these positions, probably the spawner. This way, this order is found at EDIT time instead of runtime and you should be all good

#

List<GameObject> positions
Then use positions instead of where you're using the results of the GetComponents call

scenic marlin
#

idk why but this gives me wrong count or something else is happening so any idea how to fix this or what is wrong ?
i have multiple append buffers in compute shader

        VerticesBuffer = new ComputeBuffer((Voxels.Count / 4)*8, ComputeHelper.GetStride<Vector3>(), ComputeBufferType.Append);
        ...
        VerticesBuffer.SetCounterValue(0);
        VoxelMeshGen.SetBuffer(kernel, "vertices", VerticesBuffer);
        ...
        VoxelMeshGen.Dispatch(kernel, Size.x/4, Size.y / 4, Size.z / 4);
        VerticesCountBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
        // Copy the count.
        ComputeBuffer.CopyCount(VerticesBuffer, VerticesCountBuffer, 0);
        // Retrieve it into array.
        int[] counter = new int[1] { 0 };
        VerticesCountBuffer.GetData(counter);
        // Actual count in append buffer.
        int count = counter[0];
        Debug.Log(count);
        // Get the append buffer data.
        verts = new Vector3[count];
        VerticesBuffer.GetData(verts);
        VerticesCountBuffer.Release();
        ...
tough tulip
cedar ledge
#

What's the relationship between UniRx and UniTask?

cedar ledge
# reef wren let me explain fully what i'm doing in here. i have multiple objects in scene, w...

I wouldn't trust the hierarchy order, just like how I don't trust GetChild(0) to refer to the same thing. In this example, ask yourself, do I really want the first child, or am I looking for something in particular, and I'm just assuming it's the first element? Maybe in the future I rearrange it, which would break the code. Coding it in a certain way resists constantly breaking due to things like that. In your example, you don't want the hierarchy order, you want to get a position/rotation using the index given by the server to grab on gameobject from an ordered set. The gameobjects can be put in a proper, synchronized order by giving them each a network ID of sorts. Basing in on anything else gives a possibility for desynchronization.

remote drift
#

Is there any way to see source of Render Objects feature from SRP?

uneven fossil
#

Hello there. I find myself working with Unity 2020.3.30f1 building for WebGL. I have created a file named JSBridge.jslib, which content is as follows:

mergeInto(LibraryManager.library, {
  FireJSEvent: function (jsonstring) {
    const obj = JSON.parse(jsonstring);
    window.dispatchEvent(obj.eventKey, { detail: obj });
  }
});```

I have placed this file onto the Assets/Plugins folder. Then, I have created a MonoBehaviour script named JSBridge.cs, which has the following lines within it:

```cs
//...
[DllImport("__Internal")]
private static extern void FireJSEvent(string jsonstring);
private void Start()
{
  #if UNITY_WEBGL
  FireJSEvent("{eventKey:start}");
  #endif
}
//...

And the following error pops out on console:

EntryPointNotFoundException: FireJSEvent
JSBridge.Start () (at Assets/JSBridge.cs:32)
#

Any ideas on how I can remove the error? Will the code work if I compile it to a WebGL build?

subtle river
#

When you add an anonymous method as an event callback, when is it removed? I'm having a hard time finding any concrete info on how this works behind the scenes

myClass.someEvent += () => print("some event");

I'm especially curious about adding an anonymous method to an event within the scope of an async task so the task can know when the event was invoked

var complete = false;
myClass.someEvent += () => complete = true;
await Task.When(() => complete);
// some event has now been invoked
// will the anonymous callback ever get cleaned up?

Is that okay πŸ‘†
Or do I need to manually remove the listener like so

var complete = false;
var completeAction = delegate() { complete = true; };
myClass.someEvent += completeAction;
await Task.When(() => complete);
myClass.someEvent -= completeAction;
// some event has now been invoked
#

I know it probably doesn't matter but it would bother me if these anonymous callbacks pile up over the app's lifetime

sage radish
subtle river
#

Gotcha, so it will get garbage collected along with the owner. If you were to add an anonymous listener to a static event would that mean the owner never gets garbage collected? πŸ€”

austere jewel
#

Yes, and it will hold onto everything contained in that event for the lifetime of the program

subtle river
#

Roger that πŸ™
And to be clear, is the "owner" the class which holds the event, or the class which holds the callback?

austere jewel
#

If everything stops referencing the instance that has the event then it will be freed

subtle river
#

I see. Then it seems like as annoying as it is, you really should manually unsubscribe your callbacks right? Is that how you handle event listeners?

austere jewel
#

Generally yes, unless you're in total control of your references you should find a way to unsubscribe

tribal pivot
subtle river
#

Well RIP anonymous methods then πŸ˜”
thanks for the clarification @austere jewel @tribal pivot @sage radish
Just wanted to make sure I wasn't off-base before mentioning this to coworkers πŸ˜›

tribal pivot
#

You could set it to null entirely

subtle river
#

Yea I guess sometimes. But the nature of events makes me think I *shouldnt make assumptions about other listeners not being important in most scenarios

austere jewel
#

The garbage collector doesn't arbitrarily hold onto things with events. If the instance containing the event is going to be collected because it is no longer referenced, then it will be freed.

tribal pivot
sage radish
#

But you're right that the listener can't be garbage collected if it's being referenced by an event.

tribal pivot
#

You can even invoke the event, and the now null subscriber will get called, eventhough half of it is garbage collected. this will be null

sage radish
#

We weren't necessarily talking about Unity objects

#

this can't be null. this == null can return true if this is a destroyed Unity Object.

tribal pivot
#

You're right, garbage collected is the wrong term. Still, ive had event callbacks where this is null

#

Yes it can

sage radish
#

You can't destroy objects in C#. That would be unsafe. Unity fakes it by overriding the == null check to return true if the underlying native object has been destroyed.

tribal pivot
sage radish
#

Unity objects also override ToString to return "null" if the underlying native object is destroyed.

austere jewel
#

It's a Unity Object. It's evaluating to null

sage radish
#

You can confirm this by logging Object.ReferenceEquals(this, null)

tribal pivot
#

Eh ok. Ok you guys are right.

#

Whats the difference though, practically speaking?

#

You should unsubscribe your events.

sage radish
#

The question wasn't whether you should unsubscribe or not. The question was this:

When you add an anonymous method as an event callback, when is it removed?

tribal pivot
#

Alright, you're right

austere jewel
#

Simple profiled example that self-references in an event and is released

undone coral
#

it's not javascript, they're not anonymous callback function objects... it's something else that's going on

#

@subtle river memory/the code looks something like
some function D that is the delegate's source code, which takes an argument "address of a boolean variable" (i.e., the specification of its closure)

completeAction "1" is an instance of a "complete action binding class"
a pointer to the function D
a pointer to the address of a boolean variable

completeAction "2" is an instance of a "complete action binding class"
a pointer to the same function D
a pointer to a different address of a boolean variable

#

it's not like you create a big object that is a function

#

that stuff doesn't matter

#

the thing that matters is "pointer to the address of a boolean variable"

#

i.e., things in the closure

#

it becomes way more clear why the event references don't matter once you refine what the real question is - what are the lifetime of objects referenced in a closure? the simple answer is it is the min ( lifetime of declaring scope, lifetime of the function referencing it )

#

pretty simple.

#

the function with the closure (i.e., your delegate) has a lifetime too - it will die at the end of its declaring scope if it's not referenced anywhere else, for example in an event, which is just a fancy array

shy violet
#

memory. everyones favorite bug :')

subtle shell
#

Hello guys!
i wanted to know whats the best way to draw the LineRenderer through code. since if the weapon is so close to the wall it wont be straight from the weapon barrel.

regal olive
#

Anyone knows how to use read swift functions in objC? I created a unity project (2019.4.23) but i need native swift code to run in a custom UnityAppController

undone coral
undone coral
undone coral
#

i don't think the hierarchy order will be the same

#

sort on the names of the objects

subtle river
#

Beans5715 memorythe code looks something

half path
#

what is the best way to establish communication between 2 unrelated objects in a scene? Drag&drop attaching references suck, .Find() is better but falls apart whenever you try to rename or change hierarchy, Find() with tags is kinda manageable, but there should be some message or event system that is easy to use, right?

asked in #archived-code-general and someone mentioned a static dictionary that would hold references to every object, and it seems like an interesting idea, but don't tags kinda accomplish the same thing? I've read up on Unity Atoms but it seems needlessly complicated for something so basic. I guess I'm asking about experiences, what worked for you guys in the past and if there are some must-have assets i'm overlooking

fickle mango
undone coral
#

like give an example

#

Drag&drop attaching references suck
how do you figure? like how could it get any simpler than this

#

somewhere, somehow, you have to declare the names / identities of the things that should communicate with each other

#

you can either have two fields, which seems the absolute bone dry simplest to me

#

or you can build a big cathedral that... still, eventually, has to declare the names or identities of things that should communicate with each other

#

there IS a message system that is easy to use, BroadcastMessage

half path
undone coral
#

this stuff exists in unity

#

but a message bus... like you have to register on the message bus, which is "declare the name or identity of things that should communicate with each other"

#

except instead of just declaring fields, now you also declared a message bus

#

do you see what i mean?

#

declaring the name or identity of things that should communicate iwht each other is unavoidable

half path
#

my main issue here is having to rebuild half a scene (or more) whenever I want to test an object or a script, a middle-man object/script would work nicely here

fresh salmon
#

That is doable yes, you can have a class that declares an event you can subscribe to, and invoke

tropic pulsar
#

Hey there, I'm using a Bluetooth library for my win64 exclusive Unity project and I'm running into an issue regarding the System.Runtime version of the project:

Assets\Scripts\Managers\BluetoothManager.cs(122,9): error CS1705: Assembly 'InTheHand.Net.Bluetooth' with identity 'InTheHand.Net.Bluetooth, Version=4.0.0.0, Culture=neutral, PublicKeyToken=ea38caa273134499' uses 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

I've attempted to upgrade this package in visual studio using NuGet and adding the new version to the Asset folder, but it does not seem to solve the problem. Am I missing something?

half path
undone coral
#

the net amount of code they write, in a big-O sense, doesn't change

#

and i'm trying to give you the insight as to why that's the case

rocky mica
#

its a PITA to debug tho due to the way you subscribe

#

but if correctly documented, it's a good approach

undone coral
#

for testing purposes, find all objects of type is your event bus

rocky mica
#

just gotta support it with a well thought architecture

undone coral
#

i wouldn't overthink it

#

personally i would declare fields lol

#

because they are a superior way to declare a relationship between two components in Unity

#

and if you want to discover objects to add to your fields, use find all objects of type

#

and when you need to cross the bridge to make that exact method call fast, which is a short bridge but very far on your journey

rocky mica
#

imo if you have 2 unrelated objects that need to communicate

undone coral
#

then you can deal with that

rocky mica
#

they arent unrelated anymore

undone coral
#

the opportunity here is to deconstruct what you are asking for

rocky mica
#

You can use tags and find objects but the sane approach would be to make them depend on a manager that sets up the relationship

undone coral
#

"how do i write names for things?"

modest lintel
undone coral
#

fields. fields are a simple way to write names for things

rocky mica
#

yep

#

sometimes you gotta refactor

#

because sure you are working on alpha and build an entire system that depends on that relationship and down the road you find up its messing stuff up, now you gotta refactor an inmense amount of work

undone coral
#

well, with fields

#

it's like, okay... it's either null, or it's the wrong type, or it's the wrong name, or it's pointing at the wrong thing

#

4 possible bugs

#

extremely finite

modest lintel
#

and soon you have 100 extremely fixed and defined things

undone coral
#

for normal people they should avoid ceremony

#

"message buses" have way more things that can go wrong, for little value

rocky mica
undone coral
#

because you still wind up having to declare the identity of something somewhere!

#

it's unavoidable

#

eventually, you have to have

rocky mica
#

Message busses are also a valid approach, there is a reason why there are so many design patterns

#

just gotta use whatever works best for your wanted solution

undone coral
#
field = some object // could be in the inspector

or

event bus . register (some object)
#

the big O of the amount of stuff you've written is the same

modest lintel
rocky mica
#

... no?

#

Dude

#

design patterns

#

they exist for a reason lol

modest lintel
#

well, the latter part is a design pattern

rocky mica
#

maybe for that specific case use it sucks

#

sometimes you want generic behavior sometimes MUST define extremely specific and defined behaviors, it depends

#

you cant just say "fields suck" or "message busses suck"

#

it depends

#

I wish programming was that easy

#

blanket statements like that mean nothing

modest lintel
#

Who said that

undone coral
#

the expanding brain meme version of this is

 1. I will use BroadcastMessage or FindAllObjectsOfType...
 2. Those are slow, let's directly reference these things
 3. I will use an event bus, dependency injection, and other discovery mechanisms instead
 4. I wound up recreating something Unity ships with that was simpler / I recreated C# methods and variables, so I'll go back to using that but with caching
 5. These things should not have been decoupled in the first place
#

i think a ton of people get stuck at 3

#

so they never get the wisdom at 5

undone coral
#

it shouldn't be decoupled

#

it's unavoidable

#

the big O of the code is the same in ALL SCENARIOS

#

let's say the event log "discovers" what can write to it

#

now you have IHasEventLogEvents on all of your monobehaviours

#

O(number of identities)

#

let's say each thing just writes to the event log instead

#

O(number of identities)

#

let's say you have an event bus. every way you cut the event bus

#

you will have to add O(number of identities) code to do this!

#

no matter what your pattern is

rocky mica
#

I personally reserve singletons for managers that will survive the entire game loop but its a valid approach, yeah

undone coral
#

either there are O(number of identities) registrations or there are O(number of identities) type checks of an event type

#

and then your event type has IHasEventLogTrait or whatever

#

do you see what i mean?

#

O(number of identities). O(number of identities). O(number of identities).

#

it's unavoidable

#

you will not be able to get better than O(number of identities)

#

don't try!

half path
#

this is how i see it, I have a combat log that i'd like to test and work with, and I would like to do that without having to rebuild everything else in a scene. So my options here are

  1. rebuild a full scene with units/grid/abilities/etc and do hard references between objects
  2. have combat log listen for events of type A, where other objects can broadcast/dispatch events of type A, and ideally where I can just artificially send an event of type A with a single click
hot tendon
#

hey ive been trying to get a working mesh terrain system however I got weird behavior with the new mesh API where the first 4 triangles are always missing in my meshes

undone coral
rocky mica
#

your combat log deff should be a singleton

#

IMHO

undone coral
#

i mean, how could it be any other way

rocky mica
#

CombatLog.instance.LogEvent()

undone coral
#

the universe would be topsy turvy if you could do that with no work

#

"i would like code that writes itself"

#

tough cookie!

#

have combat log listen for events of type A, where other objects can broadcast/dispatch events of type A, and ideally where I can just artificially send an event of type A with a single click
this is still O(number of identities).

#

anyway @half path take some time to digest what i've been saying here and then it should help you make the choice that's right for you

half path
undone coral
#

if you are interpreting "things" as "number of game objects" you ar emisundertanding me

#

i'm trying to get you to ascend here but maybe it's too early

cursive horizon
#

ascension is only possible after 2pm

undone coral
#

lol

#

"but what if i had a base class" well extending a base class is O(number of identities)

#

honestly i think this is a waste of time optimization. your game might have 50-100 identities, which as long as it's like 1-2 lines each will take you 3 minutes to do

#

also a common pitfall

rocky mica
#

Dont optimize until you need it

half path
#

number of identities is irrelevant here, do you not agree that it is better to assign all those identities in a singular place than having a web of interconnected stuff that is hell to setup and debug

undone coral
#

expanding brain meme:

 1. Ugh, how do I automate this task! I guess I won't do it. Too many clicks.
 2. I have written a cathedral (event busses, base classes, editor script) to automate this task.
 3. Clicking on 100 objects takes like 3 minutes to do.
rocky mica
#

of course have common sense and dont raycast 200 times in an update loop but you get what I mean

undone coral
#

you could forget to assign one of those identities in a single place

#

just like you could forget to touch something somewhere in some class

#

etc. etc.

half path
#

and I immediately know where to look, instead of searching the entire hierarchy of references

undone coral
#

it's up to you, i have shared the most wisdom i have

#

on this matter

#

the number of identities you're interacting with is the most essential part of this problem, because it will give you insight that the simpler way to enumerate these identities the better

#

you can build a cathedral to specify those identities (e.g., event bus, dependency injection) but it will burden you unnecessarily

#

my personal suggestion is CombatLog.instance.WriteToLog(...) in all the scripts that should write to it

#

that's O(number of scripts that interact with the combat log) ~ O(number of identities)

#

you could "forget" to "write to the log" when you define a new script, but you could also forget to register it on the event bus, add the interface, etc.

#

the big O of the number of mistakes you could make is the same

#

there will be like 10 attacks in your game so it will NEVER matter

#

and maybe you have an attack base class that you inherit from (still O(identities) but less janky for sure) that calls CombatLog.instance.WriteToLog(...)

#

an event bus just does not help here

half path
#

I see what you're saying and it makes sense, but you're looking at this from a purely programming perspective... what if I, for example have a designer who doesn't do code or doesn't know enough game logic to interconnect stuff by themselves? Isn't it easier to tell someone to "drag here and connect to these 2 things" than teaching them how to setup an entire scene from scratch?

undone coral
#

if you value it, i'll tell you that having a designer do this stuff is a waste of time

snow grotto
#

How would I do CircleCast but in 3d? And with 3d colliders?

tribal pivot
#

..spherecast?

snow grotto
#

The shere cast would also pickup on everything above and under, I basically want an flat box cast were the distance is checked so it's round πŸ˜…

half path
#

sorry if I pinged you, it was accidental

tribal pivot
snow grotto
rocky mica
#

a 3d circle cast would be the equivalent of projecting a cilinder

snow grotto
rocky mica
#

a sphere cast is a capsule

regal olive
#

a bat is a chicken of the cave

rocky mica
#

which for 99.9% of purposes would be identical

snow grotto
#

I'm just looking for a flat overlapsphere

rocky mica
#

doesnt exist, should use the suggestion above

#

really confused about the use case for that haha

regal olive
half path
snow grotto
rocky mica
#

We just have managers that declare an Action, then components that needed to be invoked on said actions would subscribe to it

#

for example, the input system just calls a single function call for when an input was detected, and every component that would need to receive those inputs would subscribe to it

and if it needed to stop receiving them, it would unsubscribe, p useful

olive lion
#

Hi, anyone knows how I can custom sort an array of objects based on a Color property?

rocky mica
#

with Linq you can sort by anything

olive lion
tropic pulsar
olive lion
#

Is there another way of custom sorting?

#

Because Color has no CompareTo and I can't just implement one because I got no access to that class

tropic pulsar
olive lion
#

Thanks

pallid kelp
#

you know how when you export webgl's and if you dont do build and run it doesnt work because build makes it so its just local
Is there a way to reverse engineer a local webgl one because i lost everything on it but i have the one thats just build on google drive

tribal pivot
#

Extension methods are not useful for you here

#

Its not like if you make a compareto it will be used.

#

Use the sort method with a custom comparer

olive lion
#

Alright I'll check it out, thanks

tribal pivot
#

Array has the same

olive lion
#

I've got another question, regarding inheritance.
I have a gameObject that is a Player Board, and has a script of Player.
Now I have a class Computer that is derived from Player and I wish to use it as an AI.

#

However, it seems I am unable to have polymorphism in that way where:
Player p = new Computer()

tribal pivot
#

Why not?

olive lion
#

Because the Computer class isn't a script by itself

#

It's derived from Player

olive lion
#

I basically have a game object that is linked to the Player class.
I intend to have a Player variable that can either be a human player or a computer player.

#

If he were a human player, I'd just get the script component from the object without a problem.

If he were a computer player, I'd assign him a new instance of a Computer class, as that class has extended functions specific to the AI.
But still have them use the object from the game, just like the player.

compact ingot
#

in unity you are supposed to define what a gameobject is by adding components. A human player gets a HumanPlayer component, Ai gets AiPlayer, both derived from Player, which in turn is derived from MonoBehaviour.

tribal pivot
#

I dont get it, youre confusing object and component.

compact ingot
#

Or just skip inheritance

tribal pivot
#

Player = GetComponent<Computer>()

compact ingot
#

you don’t new components, you add/remove or enable/disable them

olive lion
#

Ok.

#

Thank you

compact ingot
#

The pattern is called composition

undone coral
undone coral
#

are you saying you lost your project?

olive lion
#

Anyone knows why I have this exception?
Here's the code:

public void FirstAlignment()
    {
        List<Tile> tiles = new List<Tile>(hand);
        tiles.Sort((Tile t1, Tile t2) = t1.GetValue().CompareTo(t2.GetValue())); line 25

        for (int i = 0; i < tiles.Count; i++)
            Debug.Log(tiles[i].GetValue());
    }
sly grove
#

which means hand has one or more null entries in it

olive lion
#

Oh I see

sly grove
#

that means that null gets passed into your comparison function, causing that error

olive lion
#

I am aware there are null values in the hand at first, which is why I wanted to pass only the non-null elements to the list

#

I assume there's no short way of doing it?

sly grove
#

why would you assume that

olive lion
#

Because I'm pretty sure I can't do it in one line

sly grove
#

although - why do you have null in hand in the first place?

#

ist that intended?

#

It can definitely be done on one line, not that that is the best way to do things always πŸ˜›

olive lion
#

Yes. The hand has 22 tiles but starts with 14 only

olive lion
#

And what would that way be?

sly grove
#

List<Tile> tiles = hand.Where(t => t != null).ToList();

#

with using System.Linq; at the top

olive lion
#

Ahh Linq

#

I think I'll pass with Linq tbh, I just don't want any random errors that I can't understand to pop up

sly grove
#

you could also just let your comparison function handle null entries, if you want tiles to contain the nulls too

sly grove
olive lion
#

Yeah might go with it thanks
(and I meant that I didn't learn about Linq so yeah)

rocky mica
undone coral
#

no idea what GetValue() returns

#

but you can deal with nulls just fine

olive lion
olive lion
mortal marten
#

Today I installed new version of unity(2021.3.1f1) after upgrading my project I'm getting this error

Assets\Backend\Scripts\JsonUtilities.cs(34,39): error CS0433: The type 'JsonValue' exists in both 'System.Json.Microsoft, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'System.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

#

How can I solve it

final plinth
#

hey

#

can i get some help

#

iam programming a RTS game and trying to set a Local Avoidnace while using the Nev mesh.
does anyone have a soultion for that?

#

bec my Units stack on eachother tho

foggy vigil
#

hello, i don't really know a whole lot about straight c#, but does anyone have any idea how I could get Apache kafka working with unity? I've found this library (https://www.nuget.org/packages/Confluent.Kafka/) and these examples (https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/examples/Producer/Program.cs#L45) and in stack overflow I found some people saying that I only need to install the package and then copy some .dlls into the unity project, but I have 0 clue on how to do that. stack overflow for reference (https://stackoverflow.com/questions/54898608/unity-confluents-apache-kafka-net-client)

regal olive
#
void Update()
    {
        if (hasHit) 
        {
            if (!firstHit)
            {
                colliders = Physics.OverlapSphere(landingSpot, 4f, monsterLayer);
                Debug.Log("gonna hit for init damage");
                foreach (Collider col in colliders)
                {
                    //Debug.Log(col);
                    if (col.gameObject.transform.CompareTag(enemyTag))
                    {
                        col.GetComponent<MonsterHealth>().TakeDamage(initialDamage);
                        nextShot += hitsPerSecond;
                        firstHit = true;
                    }
                }
            }
            if (Time.time >= nextShot && hitsLeft > 0) 
            {
                Collider[] activeColliders = Physics.OverlapSphere(landingSpot, 4f, monsterLayer);
                Debug.Log("gonna hit for normal damage");
                foreach (Collider col in activeColliders)
                {
                    if (col.gameObject.transform.CompareTag(enemyTag))
                    {
                        col.GetComponent<MonsterHealth>().TakeDamage(damage);
                    }
                }
                Debug.Log("just hit for cling damage");
                foreach (Collider col in colliders)
                {
                    //Debug.Log(col);
                    if (col.gameObject.transform.CompareTag(enemyTag))
                    {
                        col.GetComponent<MonsterHealth>().TakeDamage(clingDamage);
                    }
                }
                nextShot += 1/hitsPerSecond;
                hitsLeft -= 1;
                Debug.Log("I have " + hitsLeft + " hits left");
            }
            if (hitsLeft <= 0) 
            {
                hasHit = false;
                firstHit = false;
                Destroy(gameObject);
            }
        }
    }

This code is supposed to hit once, then wait, and do that 10 times, however, it hits all 9 times in basically a second.

The same " nextShot = 1/hitsPerSecond" and "if time.time > nextShot" works just fine on another script which is why im surprised why it doesnt work

#

ignore the 1 error and warnings, the error is to do with the spectator which is completely unrelated and has been like that before the error appeared, the warnings are debug.logwarning

amber shuttle
#

Hey hey people, I've in a little pinch understanding the whole ECS gig.
Googling yields either too abstract or too hardcore stuff.
I'm no coder, I'm a generalist so I may misuse terms to a varied degree of misuse.
Say in our game, we have a horse which the player could mount.
In poor oop that'd be, in pseudo,

      some stats
      mount():
            ...
      dismount():
            ...```
So, whatever stuff you can do w/it is written under their single class.
In more functional, "better OOP" as I tend to think it, that'd be
```class horse
      ...
mount(target):
      ...
dismount():
      ...```
Here, a horse is a stat bunch w/maybe some behaviour & mount/dismount functions outside their class.
How would this same functionality look in ECS?
Basically, all I saw out there so far were examples of doing the *same* thing to every X component there is, such as moving every movement component in a certain direction. What if we wanted every actor on a scene to move where their AI system tells them to?
Any input highly appreciated, a book even or whatnot.
#

Perhaps the example listed poorly illustrates that little bit of puzzle I'm struggling with, if it does I'll try conjure up another one.
Cheers 🍻

shell jasper
# amber shuttle Hey hey people, I've in a little pinch understanding the whole ECS gig. Googling...

in any ECS system you separate data and functionality. You don't get to have mount method in horse. Separate it into two different things: HorseComponent and HorseMountSystem. Assign horse component to an entity, then run a system that handles your mounting logic. The horse component would probably contain bool isMounted which would allow you to handle mount-specific logic. It's tough to picture your example in ECS terms because it depends on the mount functionality. If it's about setting something on PlayerComponent, then your system should gather information from InputComponent (on the player entity as well) and change state of PlayerComponent and MountComponent.

"Basically, all I saw out there so far were examples of doing the same thing to every X component there is" - this is what ECS is about. You need to stop thinking in terms of OOP, it takes a while to get used to it.

"What if we wanted every actor on a scene to move where their AI system tells them to?" - their AI system would set the necessary values in each component, then a separate system should handle their movement, according to different state of the components involved. It all depends on the exact functionality that you want to implement.

#

Also sorry for not being able to provide code examples, I never used ECS in Unity but in my day job I'm developing and maintaining similar system to this under UE4

amber shuttle
# shell jasper in any ECS system you separate data and functionality. You don't get to have `mo...

Neither I am using ECS in unity, nor plan to. Just a learn-how.
So, if I'm following you, for

every actor on a scene to move where their AI system tells them to
We'd have actor entity with MoveComponent, MoveSystem and AiSystem.
MoveComponent would (roughly) have stored pos and targetpos.
AiSystem would iterate over all entities that have MoveComp. and set it's targetpos to a certain value.
MoveSystem would then iterate over all entities with MoveComp and actually change their pos?

shell jasper
#

Yes, although in certain situations you might want it the other way around; the MoveComponent would query a different component to take different action - in this example it doesn't make much sense, but in some scenarios that could improve cache coherency. For this situation (although still broad), I'd do just what you described

amber shuttle
#

Yeah seems so.
Still, while it does make sense for tons of stuff happening, can't figure out how this blends into the horse example.

You need to stop thinking in terms of OOP
If I didn't, I wouldn't ask. : )

#

If we throw in a system for this and a system for that, iterating over our couple dozen components all around the game, I imagine an update cycle looking sth like:

sys2.update
movesys.update
aisys.update
...```
wouldn't that cause weird racing?
shell jasper
# amber shuttle Yeah seems so. Still, while it does make sense for tons of stuff happening, can'...

What exactly do you want the horse to do though? We use "tags" to easily filter the components during iteration - if I wanted to change movement behaviour of a player, say, entering a vehicle, I'd set a tag on the player that prevents movement system from iterating over that entity and let the HorseMovementProcessor take over. The mounting/dismounting would be handled by a separate system - getting nearby mounts and filtering for players with a certain input state. Then change the state of the components to represent mounted state

shell jasper
amber shuttle
#

Yeah, they had JobSystem along with the ECS package. A while back that is, frankly I've little idea on the state of unity ECS/DOTS at this moment.

shell jasper
amber shuttle
amber shuttle
#

It's more of a conceptual mental block that I can't seem to break out of rather than understanding the principle itself... Case closed for now
🍻

shell jasper
#

I guess it would become more clear if you try implementing something with it. Practice ftw : ) Good luck!

shell jasper
undone coral
undone coral
undone coral
sturdy comet
#

is there a big difference between writing a normal if-statement with brackets and writing those one liner with the ? and : (Condition?True:False)

I mean does it save performance or anything or is it just for look and different workflows?

livid kraken
#

Just for looks. Using the ternary operator is a shorthand for doing if else statements

whole badge
#

well the ternary operator can evaluate to something

#

i don't think you can do x = if(statement);

tough tulip
#

string x;
if(statement) x = "True";
else x = "False";

ternary would generate the same equivalent IL code as above

austere jewel
#

Ternaries can cause the compiler to be capable of doing more optimisation (removing a local variable sometimes) under specific circumstances, but this is generally true

tough tulip
# sturdy comet is there a big difference between writing a normal if-statement with brackets an...

you shouldn't care about performance in here. its a very very beginner thought for many programmers. even if there was a difference it would be very very negligible.
you should focus more on bigger things.

one FindObjectOfType will have much much more search time that more than thousands of such negligible optimizations.
unless the profiler complains about it, or unless unity doc mentions performance costs, youre good

sturdy comet
#

thanks guys

fringe burrow
#

Hi! I'm trying to run automated tests using parameters that are defined in my scene.

In my case, I'm trying to have a few test cases to test if different types of enemies are successfully navigating certain obstacles.
I managed to do it as a single test, which loads my scene, finds the script with test definitions and execute all combinations. This works ok, but the test stops once an assertion fails, and which one of the cases failed is not very visible after the testing is ended. It would be a lot better if I could have each combination visible in the test runner (Like parametrized tests), but the test's data is defined in the test scene. Any good ways to deal with this?

final plinth
#

tthe Local avo doesnot work

#

sadly

regal olive
coral perch
#

Hello people, I would like to know which is the best way to manage source contorl with unity! I've always been using SourceTree + Git, but I wonder if it could be better to use perforce or plastic.
Which option could be better for a big project?
I heard some companies do

sly grove
#

Git is good. Plastic is decent

kindred tusk
#

I would def use git 100% of the time

#

The only reason you might not use it is if your team is somehow incapable of learning git IMO

#

Because the others are apparently a lot easier to use

#

But if you're just starting out I'd recommend toughing it out

coral perch
kindred tusk
coral perch
kindred tusk
coral perch
kindred tusk
#

That library sucks

#

Maybe useful if you have a large team

coral perch
#

4 people?

kindred tusk
#

Nah, not worth it

#

IMO

#

Honestly I just hate that thing.

#

Also if you are to use it, make sure you use the fork

coral perch
#

I am also looking to autogenerate UML, do you know any tool to do it?

kindred tusk
#

The original creator had the IP stolen from him by an employer

kindred tusk
coral perch
#

thanks for the advice

#

What is useful for big projects?

kindred tusk
#

UML is just out of date

#

I think

#

I have never heard of a programmer using it

#

I think ti's a 90s thing?

coral perch
#

The trainer in unity certified professional program used it XD (2017)

kindred tusk
#

lol weird

#

I mean I dunno, I learned it in uni

#

But like... does it even make sense for unity?

#

Inheritance relationships are not that interesting

coral perch
#

I was wondering it. It may have sense at the beginning in order to plan the code well and fasten the development

dusk plaza
#

What does this even mean? I have been building Standalone windows builds since forever. I am attempting to use this build settings thing so I can use subscenes, but it's already broken out of the box

snow grotto
#

Are you sure you have windows build platform installed on your editor?

full pike
#

Hi, was wondering if anybody could point me in the right direction for this problem: I'm trying to deform a 2d mesh(square, circle, etc) so that it fits and lays flat on a given section of irregularly shaped terrain.

snow grotto
#

In a 2D game? or 3D?

#

You could get the bottom vertices and from those points raycast down, when the distance is < your minimum distance you could place them on the ground

#

I'm not sure how you would change an already existing mesh tho