#archived-code-advanced

1 messages · Page 185 of 1

full pike
#

3D game, and that makes sense. I've been making things that change the mesh at runtime, gonna try your solution really quick. Thanks!

snow grotto
#

np, you cold also create a margin where if the distance is further then the minimum but still close to the ground, you can lerp between the ground point and the original point

#

but this all depents on what you use it for

undone coral
#

yeah then you should use the aron granberg asset

snow grotto
#

and when using the raycast be carful when using it every frame

undone coral
#

it's the only one with an RVO demo that works well that i'm aware of

final plinth
#

Ok thx ^^

undone coral
#

i like the asset it's worth it. i rarely make that kind of game though

#

subscenes?

full pike
regal olive
#

didnt work

snow grotto
#

Raycasts are not as bad as most people think, but I would keep it under 50 - 100 per frame. For placing things one it's perfect and you can get away with lots

regal olive
#

runs once then doesnt yield again

#

more than a minute goes by and nothing happens

#

delay is set to 0.1f as you can see in the Debug.Log

undone coral
# regal olive didnt work

if (hits <= maxHits) sounds like Updateloopese. you should write a coroutine to describe the entire DOT effect, including each individual hit.

regal olive
undone coral
#

yes, but where's the while

#

it should be inside the coroutine

regal olive
#

its a coroutine that "yields itself" isnt that functionally the same?

#

i never StopCoroutine

undone coral
#

i haven't seen the code, and you're telling me it doesn't work... so i guess you have to share the code 🙂

regal olive
#
IEnumerator DOT(Vector3 landingPosition, float AoE,LayerMask monsterLayer, float damage, float clingDamage, float delay, float maxHits, bool doesCling, Collider[] clingColliders) 
    {
        
        float hits = 0f;
        Debug.Log("I have " + (maxHits - hits) + " left");
        if (hits <= maxHits)
        {
            if (doesCling)
            {
                foreach (Collider col in clingColliders)
                {
                    if (col.CompareTag(enemyTag))
                    {
                        Debug.Log("dealing "+ clingDamage+ " cling damage");
                        col.GetComponent<MonsterHealth>().TakeDamage(clingDamage);
                    }
                }
            }
            Collider[] activeColliders = Physics.OverlapSphere(landingPosition, AoE, monsterLayer);
            foreach (Collider col in activeColliders)
            {
                if (col.CompareTag(enemyTag))
                {
                    Debug.Log("dealing " + damage + " active damage");
                    col.GetComponent<MonsterHealth>().TakeDamage(damage);
                }
            }
            hits += 1;
            Debug.Log("ending this cycle, yielding new one in " + delay);
            yield return new WaitForSecondsRealtime(delay);
        }
        else 
        {
            Debug.Log("breaking coro");
            yield break;
        }
        
    }
undone coral
#

i'm saying i need to see the while loop

#

i mean

#

that's your bug

regal olive
#

there is no while loop

undone coral
#

you wrote if

#

well!

#

think about it

#

clearly that's what you want

regal olive
#

when i used while loops it would freezew

#

because of infinite looping

undone coral
#

because it wasn't a coroutine

regal olive
#

so i need to do a loop in a coroutine??

#

isnt a coroutine already that?

undone coral
#

the code is doing exactly hwat you asked it to do

#

no.

regal olive
#

bruh

#

so that if should be a while

#

interesting

undone coral
regal olive
#

the else{} is now just after the while

undone coral
regal olive
#

lets see if it freezes

undone coral
#

you will need to master some C# concepts to really get this going 🙂

regal olive
#

now it works

#

great

regal olive
undone coral
#

dependency injection in Unity is very low ROI

regal olive
#

i jsut used For and foreach instead of whiles until now

undone coral
#

as far as i know, maya has a way to project a polygonal mesh onto the surface of another. that means blender probably has it too. you can try finding out what that tool is called, then look at the source for blender's version. i imagine it's pretty finnicky.

#

you should use git

#

you will need to set up git lfs

#

github's can be very expensive. there are ones that are one-click installable in an AWS account, so you only pay for usage

#

if all of this sounds too complicated, plastic is as good as not using source control - you might as well use Google Drive

dusk plaza
#

Yes, I have been building Standalone windows builds for a while now. Or the windows platform on Unity Hub is different from this one? I couldn't find any windows playform on the Package Manager

dusk plaza
austere summit
#

Hi, is there a way to check if scene is a prefab's scene? I see that only name of the scene is equal to prefab's name.

austere summit
#

When you open your prefab unity creates a virtual scene to edit this prefab. I try figure out when gameobject is in real scene and when it in virtual one

gray pulsar
snow grotto
snow grotto
#

let me quickly open unity and show where it is

gray pulsar
snow grotto
#

You can change the context here

#

You can also see it when looking at this

#

And navigate to the scene

austere summit
#

Yeah, within a context all goes well, but my script logic doesn't work well with prefab opened through project separately from any scene

#

I mean like this

snow grotto
#

Oh, so you wanna test your code within the prefab preview?

austere summit
#

yep

snow grotto
#

For that scenario I would make a separate scene just for testing prefabs

austere summit
#

i have custom sprite rendering system which works on DOTS and i'm trying to write in-editor rendering. When gameobject is in the scene or opened within a context all renders just fine, but there is a problem with prefab preview scene

snow grotto
#

mm, I would not know how to fix that. Maybe changing the settings in the preview scene helps, like enabling lighting etc.

#

Like enabling always refresh. skybox those things

soft hawk
#

Are scriptable objects instances, or templates?

gray pulsar
soft hawk
#

Ok, so if 2 gameobjects have a reference to the same SO asset, they're referencing the same instance?

#

"one copy of the data in memory" ok that answers my question

hallow cove
#

where do I start with learning on-the-fly building generation?

#

like, I have 4 points and I can stretch them in the editor and have a building update itself

#

how do I start with learning how to code geometry like that

granite viper
#

check out dynamic mesh generation

#

good place to start

hallow cove
#

ok

strange cradle
#

Having searched everywhere on Google all day on this one question, I thought I'd check in here in case someone can help me figure this out.
Ok... Using Unity 2020.3.24f1, I'm trying to implement IAP. My project is Android but will maybe go iOS later if app is popular.
I have my "Subscription Product" set up on Google Play, and my app is able to successfully purchase that product, it appears to be renewing itself every 5 mins, since the app is in internal testing.
So....
How do I check if the subscription is active, every time I open my app?
I tried to implement some code in "OnInitialized()" within my IAPManager class, but that method is never called (It is attached to a GameObject).

fresh salmon
#

Don't cross-post, see #854851968446365696 for code posting guidelines (a screenshot that zoomed out is unreadable)

strange cradle
fresh salmon
#

Yep you can do that

shadow seal
granite viper
#

@strange cradle your class isn't implementing anything

#

should probably be implementing IStoreListener

fickle mango
# strange cradle

Start() is called when you Start the scene, so maybe put the code in there?

fresh salmon
#

In the meantime I looked at your screenshot and your method doesn't execute because it isn't referenced by anything, if that was supposed to handle an event

strange cradle
granite viper
#

interfaces tend to require methods, yes

strange cradle
fresh salmon
#

If there are some methods you don't want to provide implementations of, just make a stub, or keep the one VS auto-generates when you use the "Implement Interface" quick action:

public void InterfaceMethod() => throw new NotImplementedException();
strange cradle
fresh salmon
#

Throwing an exception will remove the requirement to return a value

strange cradle
fresh salmon
#

Ah, if you do want to implement that method then yeah, you have to return something

#

I was still on the "I don't need that one" part

strange cradle
#

It wants to return a "PurchaseProcessingResult" but I'm not sure how to get that

fresh salmon
#

What type is PurchaseProcessingResult? Class, enum? The light theme has different colors compared to the dark one, so I can't determine the type by looking at the color of the type

strange cradle
#

enum

fresh salmon
#

Yep, so you can just do return PurchaseProcessingResult.SomethingHere;

#

Where you replace SomethingHere by one of the supported enum values

strange cradle
#

return PurchaseProcessingResult.Complete;
vs
return PurchaseProcessingResult.Pending;

...I'm certain it's complete at this stage. Curious why it gives me the option for Pending

granite viper
#

PurchaseProcessingResult Applications should only return PurchaseProcessingResult.Complete when a permanent record of the purchase has been made. If PurchaseProcessingResult.Pending is returned Unity IAP will continue to notify the app of the purchase on startup, also via ProcessPurchase.

fresh salmon
#

Looking at the Docs for it it's to use when you make the purchase request asynchronously

strange cradle
#

Interesting... But, I'm thinking this stuff is handled for me?

fresh salmon
#

Yeah, so it does indeed check periodically for purchases that are pending, for you to check whether it has completed

#

It just runs the method again and again for you to get an update from the server

strange cradle
#

Ok...
So I have added "IStoreListener" to my class.
I have implemented "PurchaseProcessingResult" and "OnInitializeFailed", as per requirement of the "IStoreListner".
However, My OnInitialized is still not being called.

#

Yes, my Start() is being called, but not OnInitialized.

#

It was suggested earlier that I should manually call it from my Start(), but I was unable to supply the controller and extensions parameters to it

fresh salmon
#

Yeah I've never used that package, but seeing how most packages are made you may have to somehow register your class to something, so it knows that's the one to call methods on

#

Not sure though, check the documentation on how to do that, if you have to do that

strange cradle
#

Honestly.... All I need is the ability to buy a subscription, which I've got. and then to check if the current user has that subscription.
Other than that, I dont care how it's done, or what package I use for it.... Completely open minded....
How would you implement this check

strange cradle
fresh salmon
#

I'm looking through it now, seems like you have to register the products, then call UnityPurchasing.Initialize()

strange cradle
#

I'd really like a method...
bool IsThisSubActive(String subComName)

fresh salmon
#

Aha, or you scroll down and you have an option to check inside Unity directly

strange cradle
fresh salmon
#

Yeah that should not be attached to a GameObject

strange cradle
#

Oh? I should remove it from my GameObject?
...just leave the Cs in my Scripts Unity Folder?

fresh salmon
#

Yep exactly

strange cradle
#

ok cool ty

fresh salmon
#

Still looking through the docs to see if you have to create the class yourself or IAP discovers it automatically

strange cradle
#

After removing the cs from the gameobject, I see that my Start() isnt running, nor is the OnInitialized

#

"public class IAPManager : IStoreListener"

fresh salmon
#

Yep that's normal, since that was MonoBehaviour the trigger for any Unity message to run, you'll need to put the code that initializes it all into a constructor

#

We're back into plain old classes

strange cradle
#

Forgive me... I'm not familiar with 'constructors'

fresh salmon
#

It's special methods that are run when you create new instance of classes. They have no return type, and their name match the class name

class Sample {
  public Sample() {
    // a constructor
  }
}
#

The code inside of it will run when you'll do new Sample()

#

It doesn't mention whether the fricking constructor is called automatically or if you have to do that yourself

strange cradle
fresh salmon
#

Yeah you could try that, basically in your IAPManager class you declare a constructor that will register products and initialize the IAP, like in the example

#

Then from another script, this time attached to a GameObject, in Awake or start you do new IAPManager() and see if any of the initialization methods get called

strange cradle
#

Running this, does not run my Start() or OnInitialized() (Inside the IAPManager) 😢

fresh salmon
#

Post the contents of your constructor. Start on IAPManager won't run because it's a Unity method only available on MonoBehaviour. Track the execution of the constructor instead.

regal olive
#

how would i make a ui prompt show up and the user be able to execute a script when showing that prompt

#

im guessing using raycasts?

fresh salmon
#

What have you tried?

regal olive
#

nothing i dont know hwo i would do it

#

lol

fresh salmon
#

Did you post here because it was active?

#

Pretty sure that's a yes

regal olive
#

what?

fresh salmon
#

Did you post in this channel because it was active

regal olive
#

ig?

#

why?

fresh salmon
regal olive
#

um k?

fresh salmon
#

I don't see a constructor here

#

Again, as this class does not derive from MonoBehaviour Start won't be called

strange cradle
fresh salmon
#

The link I gave earlier on has that constructor

#

Take inspiration from it

strange cradle
#

I've seen my error! got it... right brb!!!

#

ty

strange cradle
# fresh salmon Take inspiration from it

I was able to successfully get those methods to run, after doing the constructor correctly.
However, now my purchase button is no longer bringing up the Google Play's confirmation dialog, when running on the device.
In the Unity IDE, I do see the fake store confirmation dialog though 😢

#

Also, on the device, my text4 output is showing that my 1 product is listed, but with no receipt.
My next step was to click purchase, and I expected to see the google pop up, but nothing happens when pressing the button on the device 😢

undone coral
#

or are you an android power user

strange cradle
undone coral
#

okay

#

it looks like you've been at it for a while

strange cradle
#

I have....

#

However, I think I just managed to bypass the problem by 'not' using the IAP Button Component on my button

#

Calling Controller.InitiatePurchase manually, seems to work... But I'm not sure if that will translate over to the iOS (But thats not too important right now) just worried I'm doing it all wrong....
I feel like I've made a mess of my code to achieve this

undone coral
#

I feel like I've made a mess of my code to achieve this
it does seem that way yeah

#

the workflow for IAP is

user taps buy button
-> completes purchase
on platform
-> platform gives you receipt,
which you interpret
cryptographically and
award user item

#

everything else is a failure case and you do nothing. you don't attempt to recover

#

i have a feeling you are trying to recover from failures

rocky mica
#

Yeah you cant recover from failures with those kind of atomic operations

#

it either goes through or it doesnt, there is no recovery process, you just reattempt the transaction again

undone coral
#

it looks like part of it is you're using the platform to manage your inventory

#

i wouldn't do that. you just have the inventory in game. in the platform, you create corresponding price objects and you verify the user bought something of the right price, not a particular item

#

does that make sense?

#

finally, you have restore purchases

strange cradle
#

😬

#

I'm not sure lol

I only have 1 item, it is a subscription for 1gbp a month.
I just want to check if the subscription is active, and then I'll disable the ads

strange cradle
#

I wana thank everyone who's helped me... I think I'm at a good point now...

midnight violet
#

Hey everyone, so I got an EAN code scanner which starts a thread, but the problem is, I want to start a safe code part form this unsafe void. I get of course the error "StopAllCoroutines can only be called from the main thread." So how can I ensure, I call it on the mainthread or something?

sly grove
#

My favorite technique is to use a ConcurrentQueue

midnight violet
#

So enqeue in the mainthread?

sly grove
#

enqueue in the background thread

#

TryDequeue in the main thread

midnight violet
#

Hm okay, I guess I gotta google around a bit 🙂 Thanks for pointing

undone coral
#

whaddya think?

sly grove
#

too cute for my blood doc

undone coral
#

lol

undone coral
#

something stirred in your hardened heart

sly grove
#

It made me think of doge

undone coral
#

lol

#

"wow" "such elegant"

sly grove
#

yes

undone coral
#

"no queue" "wow" "is async" "so short"

compact ingot
undone coral
# midnight violet Hey everyone, so I got an EAN code scanner which starts a thread, but the proble...

you might have something of this form

sealed class EANScanner {
  static void Scan(Action<Image> callback);
}

and callback is invoked on the EAN scanner thread. in which case:

async UniTaskVoid Scan() {
  var scanResult = new UniTaskCompletionSource();
  EANScanner.Scan((image) => scanResult.TrySetResult(image));
  await UniTask.SwitchToMainThread();
  var image = await scanResult;
  GetComponent<Image>.sprite = new Texture2D(image);
}
midnight violet
# undone coral you might have something of this form ```cs sealed class EANScanner { static v...

I actually just found this 🙂 https://github.com/PimDeWitte/UnityMainThreadDispatcher Thanks a lot for your async idea too. Will think about that too 🙂

GitHub

A simple, thread-safe way of executing actions (Such as UI manipulations) on the Unity Main Thread - GitHub - PimDeWitte/UnityMainThreadDispatcher: A simple, thread-safe way of executing actions (S...

undone coral
#

use unitask

undone coral
#

yes

#

just use UniTask

#

lol

#

okay i'm done

#

i don't have any more bits

shadow seal
#

Or just one queue, because it's just one queue

sly grove
#

curiously thogh

#

does uniTask let you enter the main thread at specific parts of the event loop

undone coral
#

it takes a player loop argument

sly grove
#

like I can jump in during FixedUpdate?

undone coral
#

yeah

compact ingot
#

you can jump at any time

undone coral
#

it has PreFixedUpdate, PostFixedUpdate, etc. etc.

sly grove
#

I see

undone coral
#

// wow

compact ingot
#

if there's a script you drop into all your projects to do that main thread scheduling via a concurrent queue, you can also just drop in UniTask with the same amount of effort

undone coral
#

for my platform i force people to install unitask

#

that's how much i love it

#

i'm a unitask stan

compact ingot
#

has it changed your life in some way?

undone coral
#

it helps me run heaven up here, where people ascend to

#

helps me schedule everything in one giant async task

shadow seal
#

Sounds more like hell

undone coral
#

lol

#

it went well, 1 gameloop task

#

lemme pull it up

#

for a sneak peak

#

literally a game loop

while (Application.isPlaying)
        {
          // click a play button
          await
            (m_PlayNowButton.OnPointerClickAsObservable() ?? Observable.Empty(default(PointerEventData)))
            .Take(1)
            .ToUniTask(cancellationToken: token);
          m_ScoreCurrentControl.Reset();
          m_ScreenView.Transition(m_PlayingScreen.screenIndex);
          // game loop began
          // wait a beat
          await UniTask.WaitForEndOfFrame();

          m_ThrowControl.enableNextThrow = true;
          m_ThrowControl.StartThrowingGame();

          // wait until the next throw to start the timer
          await m_ThrowsSubject
            .Take(1)
            .ToUniTask(cancellationToken: token);

          // start the clock
          var timeElapsed = new CancellationTokenSource();
          var anyCancellation = CancellationTokenSource.CreateLinkedTokenSource(timeElapsed.Token, token);
          var clock = UniTask.Create(async () =>
          {
            var startTime = Time.unscaledTime;
            var didLowTime = false;
            while (Time.unscaledTime < startTime + m_ShotsDurationSeconds)
            {
              var timeLeft = TimeSpan.FromSeconds(m_ShotsDurationSeconds - (Time.unscaledTime - startTime));
              m_TimerText.text = $"{((int)timeLeft.TotalMinutes):00}:{timeLeft.Seconds:00}";
          ...
#

this is a basketball minigame. the whole thing is in 100 lines

#

it's pretty good

#

i tried to eat my own dogfood here to its greatest extreme

#

what if you did the whole gameloop as a single task? it's not bad

compact ingot
#

Dedication!

undone coral
#

"there are so many cancellation tokens" - well, those are real. it forced me to deal with everything

compact ingot
#

I like it

undone coral
#

await clock;

#

if you can read asynchese, you know exactly what happens in this game, in one file

compact ingot
undone coral
#

i think this is a crazy way to write a substantive game. but if your whole experience is 2 minutes long, it's perfect

compact ingot
#

Also fun

undone coral
#

you can wrap your head around exactly what happens, and the bugs surface 90% in compile errors, 10% in using cancellation tokens correctly

#

it forces you to deal with things at compile time

#

which is really attractive

compact ingot
#

I once made a game in one huge coroutine, that was less fun

undone coral
#

coroutines are missing cancellation

#

they have StopCoroutine

compact ingot
#

they miss a lot of things

undone coral
#

yeah

#

you can't "await foreach"

#

you're going to see that and it's crazy

#

but it is expressive and correct

#

oh youv'e seen this demo

#

you can open it on your phone

wary roost
#

given a rect of yMin -512 yMax 512 xMin -640 xMax 640, and latitude goes from 0(Npole) to 180(Spole), and longitude goes from 0 to 360 (Greenwich). Take a lat/lon coord and place it inside the rect

small latch
#

go do your homework Smonk

shadow seal
#

Could it be more obviously homework? Who else uses "given"

compact ingot
#

People who went through trial by math

grim oxide
#

How often are GameObjects serialized/deserialized? Pretty rarely, right? 🤔

#

Doing some custom serialization via OnBefore/OnAfter De/Serialize, trying to gauge how 'hot' those methods are

compact ingot
grim oxide
#

Oh yeah sorry I mean during gameplay

#

But that means only once then

#

Or whenver it needs to be loaded/unloaded

#

So I can use Linq in these methods without fearing performance 😛

compact ingot
#

pretty much

compact ingot
grim oxide
#

Right, the stuff I'm doing would only be very slow if it was happening like multiple times per frame or something

compact ingot
#

usually linq is fine during level/scene init while you show a loading screen, bad if you use it while spawning bullets

grim oxide
#

lol yeah that makes sense

compact ingot
#

but generally linq is way less bad that it’s reputation

compact ingot
orchid marsh
#

Which can slow your application if you're creating excessive amounts and freeing excessive amounts per frame. But it itself isn't too expensive or slow at all.

daring pelican
#

hey guys do you use some sort of script templates in your projects? for example, it's annoying to create a SceneLoader.cs each time, but writing that script pretty much takes the same amount of time as copying it from your gists... so... you got any tips or tricks for this?

undone coral
unkempt nova
#

Can't you make new default projects from the hub too?

#

As a new template. Sounds like that may be what they're refering to actually

undone coral
unkempt nova
daring pelican
daring pelican
unkempt nova
#

Basically. I have mine on github though

#

Keep the tools separate enough from eachother that you can snag only the tools you need, or grab them all and delete the others

undone coral
ancient sparrow
#

How to detect if 2d or spriterender is overlapping the screen?

wind pasture
#

Anyone have experience with moq and nunit?

daring pelican
ancient sparrow
daring pelican
daring pelican
#

or maybe you wanna check when the whole object is withing the camera planes

ancient sparrow
#

This is how it should supposed to look like. What im thinking of doing is when program detects that edge of image goes offscreen it reduce its scale so that i would like this

minor shadow
#

if you need it to be sprite renderer, the way to go is to change the pixel per unit value

mint sleet
#

Hello Folk, Do you know how to prompt a custom 'authorization denied' message back to the client?

#

It throws an error and looks like a garbage.

olive lion
#

Hi, does anyone know how I can custom sort an array of Tiles based on the color?

#

Having the Color as an attribute of the Tile object.

fresh salmon
#

You can use LINQ and a lambda expression to do that

#

Getting link...

olive lion
#

I've heard about LINQ and lambda, just not sure how to use them properly

#

Because Color is not something that I can sort by

grave sandal
#

you can with linq 🙂

fresh salmon
#

Yeah, but the results might not be as expected

#

A first would be to know what makes a color "lower" than another one

#

This can be your own criteria you define yourself

olive lion
#

I see.

#

Can I implement my own CompareTo then? or is there something easier?

fresh salmon
#

First see if Color already implements IComparable, then that'll make your life easier

#

Otherwise you'll have to define your own comparison method

olive lion
#

Doesn't look like it

fresh salmon
#

Okay, so you can define your own comparison method and use it in a lambda, and Array.Sort that takes in that lambda (in the form of a Comparison<T> delegate)

#
Array.Sort(items, (i1, i2) => i1.Whatever - i2.Whatever)

for example

regal olive
#

I need Simon says 3d code

#

For a game

#

I tried hard

fresh salmon
#

What have you tried? This is #archived-code-advanced where debugging, explanations, and more globally a correct question format is expected. Switch to another channel if that doesn't match your question

olive lion
fresh salmon
#

It shows up, it's just that Comparison<T> delegate expects an int to be returned

olive lion
#

I'm sorry I just don't quite understand this stuff completely

fresh salmon
#

Integer value that denotes the comparison between the two elements:
0 if they're the same
1 if the second one is greater than the first one
-1 if the second one is lower than the second one

olive lion
#

I do understand that I need my own comparison method though

#

Do I need to extend a class or something?

#

Where do I define the custom comparison method?

fresh salmon
#

Nope, all of it can be done in the lambda. The custom comparison is the one you make yourself, in the lambda

#

In that example it doesn't use a lambda, but rather a full method to do the comparison

olive lion
#

I see.
Well the plan I had was to subtract the RGB values from one another, but a better idea is, since I use 4 colors I will determine by myself which one should be the lowest and which one the biggest.

fresh salmon
#

Yep exactly, and that's the part you make yourself. It could be getting the average of the RGB values and comparing that, or a single channel of the color, or the alpha, you choose

olive lion
#

Alright then, I'll try it.
Thanks for your help.

olive lion
#

And have them put at the end of the array.

fresh salmon
#

You can have a special case where if i1 is null, you always return 1, so it gets pushed at the back

olive lion
#

How do I add a if condition inside the lambda?

fresh salmon
#

You can't, unless you make it a lambda block statement, or a method

(i1, i2) => {
  // statements can now go here
  // use 'return' to return values, like in methods
}
olive lion
#

Ok

fossil prairie
#

Uff, so I am trying to Build a clean RPG System and I'd like to have my Single Attributes as Scriptable Objects with name, description and icon. Then I have another Scriptable Object which should be a List of Attributes + It's specific value in this instance. I made a Class that has an Attribute and a value property. That i put as a List into the Attribute List Object but It doesn't really work in the Editor like this. Is there a good way to make this work or do I need to do this in a completely different way?

Attributes are Aspects because I was trying stuff with System.Attributes and the naming got confusing

summer shore
#

Hello, I'm using Python for Unity 4.0.0pre.1, I've tested simple hello world scripts following the API instructions shared in the documentation (https://docs.unity3d.com/Packages/com.unity.scripting.python@4.0/manual/inProcessAPI.html).

I'd like to use the data processed by the python script in the C# script. For example, the python script will show an array of numbers and I want to do something with those numbers in the C# script.

I thought that I could convert the data to JSON, save it in a file, and then the C# script would read the JSON file and convert it. The problem with this is that initially I tried to do a simple write string into a text file using this

# Write-Overwrites file = open("myfile.txt","w")#write mode file.write("Test") file.close()

But after running the python code I couldn't see the file in assets folder (location of the python script), I'm not sure if it was created, and where it could be.

Any thoughts or recommendations? Doing this differently or a way to solve the current idea I have to implement it if it's a good way to do so?

Thanks

tribal pivot
#

Is it one folder up? Afaik the root is not assets, but one up

#

@summer shore

summer shore
#

Woww yessir there it is, thank you!

drifting galleon
#

be aware that this package is for editor use ONLY. there is no runtime support

summer shore
drifting galleon
#

you can use that as a starting point^^

#

they list various possibilities

undone coral
undone coral
#

the python program should be in c#

#

i know that's not really helpful, but trust me

#

you shouldn't try embedding a python program this way

undone coral
#

you shouldn't try to metaprogram this way

#

create a single class that is a master data container ([Serializable] class GameEntity {}) and reference it in your scriptable objects as needed class MyAsset : ScriptableObject { GameEntity thisEntity; }

regal olive
#

How am i supposed to do this? The prefabs are naturally "non static" since i have to add them in the editor

frozen imp
#

@regal olive Don't cross-post

regal olive
frozen imp
#

Then remove it

regal olive
#

i was tabbed into gen chat not advanced

regal olive
frozen imp
regal olive
#

like my other dicts

#

im just a monkey

frozen imp
#

How or why really are you referencing prefabs as static? They would not exist at compile time.

regal olive
#

and it seems to work just fine™️

frozen imp
#

You can't serialize static fields

regal olive
fossil prairie
# undone coral it's not clear what problem you are trying to solve

I am not metaprogramming. I just have scriptable objects that describe some stuff and want to have a list of those and assign them a number (attributes and their value). And I would like to easily add and remove attributes. I wanna build something that will not become a giant mess of scripts and objects and references but something that is easily editable and creatable. I would love to have this list automatically be populated with all existing attributes that I've created but I can live without that.

undone coral
#

well i don't hear a concrete example of a piece of gameplay in here

#

when i've looked at RPG asset store assets, the data types are pretty focused

#

in the grand scheme of things, building a huge abstraction to save you from having to touch a few files to add an "Attribute" (maybe you mean item attributes) is low ROI

regal olive
#

Seems like making my prefabs static doesnt let me define them on the editor

#

how could i define them?

frozen imp
#

You don't use static to cache prefabs. Initialize them at runtime.

regal olive
#

how? can you send me an example

frozen imp
#

You are trying to initialize instances in the field. Do that on Awake or Start instead

regal olive
#

so i move these to void Awake() ?

#

Sadge seen

frozen imp
#

Your dictionary initialization. Your original question. Move that

regal olive
#

xqcPeepo Visual studio has browned its pants

frozen imp
olive lion
summer shore
# undone coral you shouldn't try embedding a python program this way

Got it, this is just for a course project from school. Basically we worked on some AI functionalities using Jupyter Notebook and sharing it with the class using colab. The thing is that the project is to create a UI that someone can use it to test things more "pretty". So I was hoping I could create a UI in Unity for this purpose. In case you are wondering, the AI is for a shop and it recomends products to clients and checks a list of comments based on some data to see if they are positive or not, not big deal from the Unity side since it would be just UI and sending some data around.

#

And since I'm comfortable using Unity I was hoping to create a UI and something the teacher could test and such. But I think I'll look for something else

urban warren
#

I got an architecture-ish question.
I am creating a plant mesh generation tool using the advanced mesh API with Jobs. I have nodes that form a hierarchy, and each node has parameters for generating/populating a MeshData.
(Each node would handle like a set of leaves, or flowers, or stems etc.)

Now to my question, when a node has its parameters changed and the mesh needs to update, what would be a good way to do it.

I was thinking of having each node have their own Mesh, and then combine the meshes on export but this feels messy to me, and feels like it would be more expensive.

Another option would be to have a single Mesh and regenerate the entire thing each time via Mesh.AllocateWritableMeshData(..) and Mesh.ApplyAndDisposeWritableMeshData(..).
But that feels also needlessly expensive.

Other ideas or thoughts?

#

Beyond speed I am also not sure how it handles memory allocation.

undone coral
undone coral
#

lol

#

@summer shore or slope-one or ...

#

what is it?

undone coral
#

how else could it work

#

combining isn't expensive

#

presumably you're trying to save time on the latent space to mesh computation

#

not the mesh to mesh copy

urban warren
undone coral
#

can you post or DM a screenshot?

undone coral
urban warren
undone coral
#

of the plant

#

i don't know, in 3d editing tools 99% of the time, something like XGen is realtime

#

and it manipulates the whole mesh so it couldn't be that smart about it

urban warren
#

Oh, I don't have a plant yet to show. Most of the plants will be really simple though, like under 1k I would assume. If/when I have it support trees, it could go up quite a bit of course because of those leaves.

summer shore
# undone coral what is it?

For recommending products we use association rule to see which products were frequently bought together and then given a product that the client is interested in, it will give products that were bought with product 'selected'.

undone coral
#

can you tell me the name of the thing you're doing from the literature?

#

or it isn't that

#

it sounds like "whatever Y is most frequently also bought with X, counting down"

#

which is called "baseline"

#

it might be faster to just reimplement it in c#

#

i feel like it would take you... 20 minutes

#

i was going to share you my real, in-unity code of a recommender

summer shore
#

We have a dataset which you can see it as a list of lists. And each list is like a receipt that the shop has that has strings with item names.

Now, we convert this into a matrix with boolean data that shows which items were purchased (true if purchased, false if not). In this case we only have two receipt.

Then, with an algorithm "priori" we check how often products are purchased.

Then we generate all the association rules. And based on the selected product we get the recommendations from here.

#

Now indeed, this could be done in C# but the course has to be in Python specifically. At least this part of processing data

undone coral
#

and unitywebrequest against your python code

crisp frigate
#

Hey Yall, Im trying to use UnityWebRequest to download a m4a file and play it on a AudioSource. I am trying to use UnityWebRequestMultimedia.GetAudioClip(songMusicURL, AudioType.UNKNOWN); And Then Downloading the file by AudioClip song = DownloadHandlerAudioClip.GetContent(songMusicRequest);
Im getting errors because of the unsupported filetype how could I convert this to the right file?

wispy epoch
#

I want to add critical chance to my game for bullet damage. Would it be too expensive performance wise to have a random value generate for every shot to determine this? Some guns fire over 15 rounds per second. If it is performance heavy, is there an alternative? (Context: mobile game)

gray pulsar
wispy epoch
# gray pulsar Given that you're in <#885300730104250418>, I'll give the advanced answer. You s...

Thanks for the help. That's not the advanced answer. Thats the pretentious answer. If you dont wish to help you can ignore, no need for the snark. Obviously i can test it myself on my device but im not doing all the work to implement and then send it to beta testers when someone thats not being pretentious can give me a simple answer. Either rand.value is too inefficient to be called so many times on mobile, or its not.

regal olive
#

also googled it second result "No. Random.Range is extremely fast as Unity uses Xorshift128. "

gray pulsar
# wispy epoch Thanks for the help. That's not the advanced answer. Thats the pretentious answe...

sure, but you don't need to send it to beta testers to determine the answer to that. You need to create a test environment that calls your random function many times per frame (say 1,000,000?) that you can use the profiler to evaluate the performance. You need to build it and deploy it to your target hardware and test the performance on that hardware.

Also, if your game is running at 30 fps, 15 rounds per second is only 1 round every 2 frames.

If you're posting in #archived-code-advanced, people are going to expect you to be able to do basic arithmetic and realize that you're not even calling the function 1x per frame.

subtle river
#

in 2021.3 the not keyword is now supported.
would this circumvent the native lifetime check?

if (someComponent is not null)
austere jewel
#

yes

subtle river
#

bummer! 😔

#

thank you!

wispy epoch
wispy epoch
# gray pulsar sure, but you don't need to send it to beta testers to determine the answer to t...

Im trying to make my code as efficient as possible. Calling things once every 2 frames isn't great for performance if there are better options so i asked if anyone knew better options since this is the advanced channel and i expected a real answer like "no unity uses methodology thats about as efficient as you're gonna get for finding random values. Calling it less than once a frame shouldnt impact performance too much."
Or "you can actually do X instead which is much less intensive. With all the other calculations in your game you probably don't want to be doing random value calculations 15-45 times per second."

cedar ledge
#

In the spirit of "not writing the same pattern of code everywhere", would it make sense to extract the typical while(true) { ... yield return new WaitForSeconds(Time.deltaTime) } into a separate function? For example:

private IEnumerator LightColorBounce()
{
    while(true)
    {
        SetColor(Color.Lerp(Color.red, Color.grey, 2 * Mathf.Abs((Time.time % blinkPeriod / blinkPeriod) - 0.5f)));
        yield return new WaitForSeconds(Time.deltaTime);
    }
}

becomes

private IEnumerator LightColorBounce()
{
    RepeatEveryFrame(()=>
    {
        SetColor(Color.Lerp(Color.red, Color.grey, 2 * Mathf.Abs((Time.time % blinkPeriod / blinkPeriod) - 0.5f)));
    });
}
austere jewel
#

why would you wait for Time.deltaTime?

cedar ledge
#

i could be wrong but i thought that's the proper way to do something each frame, like lerping the color of a material

austere jewel
#

yield return null will wait for a frame. new WaitForSeconds(Time.deltaTime); would wait for the time the last frame ran, and would allocate while doing it

cedar ledge
#

what does this change? startcoroutine have the waiting functionality built in?

#

oh ok

#

so the coroutine runs once per frame by default

austere jewel
#

yielding for null has that behaviour

#

if you think that's "default", then sure

cedar ledge
#

how is yielding related to the framerate?

#

my understanding is that an IEnumerator just runs whenever you ask it to using MoveNext() and the yield return is the value .current gives you. I would imagine the functionality to only call MoveNext() once per frame is inside of StartCoroutine()

#

https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
Yielding of any type, including null, results in the execution coming back on a later frame, unless the coroutine is stopped or has completed.
so you're correct about the yield return null behavior, but it would seem that it's the implementation of StartCoroutine() that makes it continue on the next frame. waiting for more time would just be every other frame or whatever

gray pulsar
austere jewel
#

Of course how Unity handles StartCoroutine is what makes it do what it does 🤷

#

When you yield Unity will evaluate that and come back on a later frame.
Yielding for null is how you wait one frame. That's it 🤷

cedar ledge
#

i just wanted to clarify that just in case i was misunderstanding it and that if i were to use an IEnumerator in a way that isn't a coroutine, then my understanding of yield return null would be correct

austere jewel
#

sure

cedar ledge
#

sorry if it was pedantic, i just wanted to double check whether it was the yielding itself that waited 1 frame, or if it was the idiosyncratic way unity uses it

#

what is the use case of WaitForEndOfFrame vs null?

gray pulsar
#

You can use it to read the display into a Texture, encode it as an image file (see Texture2D.ReadPixels and Texture2D.Texture2D) and store it on a device.

austere jewel
cedar ledge
#

yeah just intuitively i thought that "before the next frame" is the same thing as "after the current frame". the difference is that Update(), input, and physics happen between one way, and then game logic and rendering is in between the other way

#

thanks

#

if it doesnt matter when during the order it happens, i guess null is just the de facto choice

wispy epoch
#

"generating random values generally isnt considered an extremely expensive operation but you'll obviously want to test out if calling it 45 times a second effects performance. Nothing else will perform better so you'd have to choose another way to implement crit chance if it is affecting performance"
would have been a simple answer that didnt require any sass.

dawn yew
#

Poor man asking for help here🥲
Right now i have a debug script which executes in editor mode. It will create a game object during its life scope. And I want to let the lifescope of the created GO matches the debug script. (the Destroy() logic is inside dispose())

Now the problem is that every time I recompile the codes, the domain reloads I assume, which resets the state of the script and it will create a new GO again after compilation. However the GO it created before is never destroyed (seems like reloading the domain won't trigger Dispose() on objects) and the GO keeps stacking up.

My question is that is there a way to properly destroy the GO when compilation happens (or any other thing that will "reset" the state of the script due to domain reload i assume)

#

ok setting the GO to DontSave kinda help
but it still requires the user to manually re-launch unity to clean the stuff

tribal pivot
dawn yew
novel plinth
split sundial
#

Does anyone know how ContentSizeFitter calculates preferred width/height?

regal olive
undone coral
split sundial
#

That said, apparently, it iterates over each element in the game object searching for their width/height and return the largest

gentle yew
#

Or if there are any alternatives?

gentle yew
#

Found it. We can use [ExcludeFromCoverage] from UnityEngine.TestTools

wispy epoch
#

What? Lol dude i wasnt taking you out of context. I wasnt even quoting you. I was saying what a good answer to my question would have been using part of your explanantion. I did not imply you said the answer.

You are completely misunderstanding what that last message was about. And no im not an idiot so i wouldnt be dumb enough to ask a question i knew the answer to. Literally in that message you're quoting, I gave examples of what a good answer to my question would have been, which i was looking for. I thought it'd be pretty simple for an "Advanced" unity dev to answer either way whether it was too inefficient or if it was the most efficient option and should be fine performance wise. Instead I got snark because many devs like to talk down to other people asking questions.

austere garnet
#

have any of you encountered this issue before (or something like it)?

  1. create a prefab variant (and git commit the variant)
  2. add an instance of that variant to your scene (and git commit the change)
  3. perform a git rebase to squash commit #2 into commit #1

—Step 3 changes the GUID of the prefab variant and breaks the prefab reference for the object from Step 2?

#

it's not strictly necessary for me to rebase this particular commit, but I'm concerned that if I rebase in the future it might break the references again.

undone coral
#

you could try quitting unity

austere garnet
#

I don't either

#

I did try that

undone coral
#

while you do the rebase

#

then it's a red herring

austere garnet
#

ah, not during the rebase

#

I'll give that a try

#

it is very weird but clearly happening when I rebase

nimble imp
#

I have this for loop to spawn buttons and assign actions to it: (I simplified it here)

for(int i = 0; i < 10; i++)
{
ButtonGameObject.GetComponent<Button>().onClick.AddListener(delegate { ButtonAction(i);});
}

But the button always returns i = 10.
Any suggestion on how to get the actual 'i' I assigned to it?

humble onyx
nimble imp
#

ok that makes sense, thank you!

ashen merlin
#

hi anyone can help please,i updated my visual studio to the 2022 version but now i can't see the types of some variables, they aren't colored, just white. anyone knows how to fix this? ty

thin mesa
gentle yew
#

I think you can find it in the top left part of the menu. "Close solution" and then re-open it manually again

sinful fossil
#

Hey can someone help me with a lens flare issue? I am using URP but the Lens Flare (SRP) component doesn't show up?

sinful fossil
#

In the add component button on an empty game object

sly grove
#

should be under Rendering

#

it's not there?

sinful fossil
#

all i see is the normal one. I checked the rendering tab but I mainly just search for things by name. But both cases its not showing up

sly grove
#

Are you sure URP is set up properly 🤔

#

and what version of URP is it

sinful fossil
#

I am using URP 10.3.2

#

And I opened this project in non URP but then added it later

unkempt nova
soft pewter
#

Ops

#

Wrong channel sorry

#

Thought I clicked on general

#

I'll delete and post there

unkempt nova
#

You're fine, that's the answer though

soft pewter
#

Ok thanks

unkempt nova
#

There's also IPointerDragHandler or something too you'll need

sinful fossil
#

Anyone know why the Lens Flare (SRP) component wont show up on my URP project?

unkempt nova
#

This is a coding channel

sinful fossil
#

we can address components in this channel

somber swift
#

Don’t be surprised if you don’t get answers on this channel tho, sounds far from scope of this channel

soft pewter
unkempt nova
#

Think so

soft pewter
#

Yeah, so can't use

unkempt nova
#

Oh. For 3D objects just use OnMouseDrag

ember torrent
#

not sure if this would be considered advanced, but im trying to make it so my audio clips volume fades out very quickly instead of stopping instantly with audioSource.Stop(). for context im working with undertale/typewrtier style dialogue with sound effects and i currently am running a loop that stops the last audio before playing the next one and its creating a small popping sound every time its cut off atm

#

is there an easy way to do this or would i need to make a separate function/coroutine of some sort

hybrid carbon
undone coral
sly grove
#

you just need to have the right components in the scene

dawn yew
#

i'm very confused regarding how to destroy gameobjects under editor mode.
i first tried Destroy(), and it throws out the following error:

#

So then I switched to DestroyImmediate() and it throws out another error:

#

how am i gonna Destroy an game object then...

austere jewel
#

I would probably do EditorApplication.delayCall () => DestroyImmediate(thing);

dawn yew
#

lemme try that

short junco
#

Can someone give a advice about how to batch skinned mesh renderers ? I tried Mesh Baker but in some situations i need to update mesh so its not for me i guess I tried animation instanceing but that package give me an error when targeting mobile and also tried to SRP batcher but not covers the skinned meshes

livid kraken
short junco
livid kraken
#

Why do you even want to do crowds on mobile ?

short junco
#

In some part of mechanic i need to render hundreds of low poly characters (very low tris count) so i need to optimize it somehow

#

I saw these vertex shader tech. yesterday other than that ı dont know how can i optimize it for mobile

livid kraken
#

Its not a trivial issue to solve

#

The simplest way is to bake to a vertex animation texture do get rid of the perf cost of a skinned mesh and let unity handle the batching

#

Gpu instancing is not really friendly to mobile

short junco
#

I dont have knowledge about vertex animation thing

#

but i will search doc or article about that

#

thanks a lot i will move on your road

livid kraken
short junco
livid kraken
#

Gl

short junco
#

@livid kraken I'm starting to get stuck already 😄

#

I dont know what i am doing wrong but ı guess in some points of my fucntions are incorrect they why they didnt give any sample or something like that : D the above texture is theirs and other is mine

#
    {
        Mesh meshState = new Mesh();
        TargetAnimator.Play("IDLE", 0 , (1/TargetClip.frameRate)*frame);
        TargetAnimator.speed = 0f;
        TargetSMR.BakeMesh(meshState,true);
        return meshState;
    }```
#
    {
        Matrix4x4 localToWorld = transform.localToWorldMatrix;
        Vector3[] vertices = new Vector3[mesh.vertices.Length];
        for (int i = 0; i < mesh.vertices.Length; i++)
        {
            vertices[i] = localToWorld.MultiplyPoint3x4(mesh.vertices[i]);
        }
        return vertices;
    } ```
#

I would appreciate if you let me know if there is an error that catches your eye.

livid kraken
sly grove
dawn haven
sly grove
undone coral
#

in principle iOS devices can support it if macos does

#

and android vulkan

formal rover
#

Anyone familiar with mapbox and photon for multiplayer spawning? I want to spawn players at their GPS location in a multiplayer GPS game. I heard about having to use Class Conversions maybe, but I'm lost on how they work. Any help would be appreciated.

supple crest
#

Is it possible to schedule batches of raycast commands from within a job? Trying to perform some raycastcommands, get the results, and perform some work from the results all in one job.

unkempt nova
#

When just checking if a type is another given type or not, is it better to use GetType and typeof like this:

if (someClass.GetType() == typeof(someOtherClass)) 

or use pattern matching (is this the correct term?) like this:

if(someClass is someOtherClass)

I ask because I think the second one boxes it, right? And the first one does type manipulation stuff, probably creating a little garbage (or does it). I'm not sure if there's much difference in either case, but curious if so. I prefer the second as it's much more readable imo, but worried about boxing a big class. I'm not sure if the size of the class matters at all during boxing, if it's even happening here

#

For context, I'm trying to disable a list of abilities on an object. Movement is an ability. I just need to know IF one of these abilities is movement, and stop input if that's the case.

flint sage
#

It's not boxing unless you do x is Interface y where x is a struct

#

Just is shouldn't be allocating

#

And second one is generally considered better unless you need some very specific info from the type

#

I.e. does it inherit from a type

tough tulip
brittle pumice
#

Wondering if someone could help me with something

#

In the editor I’m copying an external script in , normal via FileUtils. Then trying to invoke a method via reflection

#

The reflection error with NullReferenceException

#

Runs the script again deleting and coping back the same file it works

flint sage
#

Share some code

brittle pumice
#

Making me feel like i need some sort of reload refresh

#

O one sec let me past some code

#

This is in editor in unsaved scene

#
        {
            AssetDatabase.Refresh();
            for (int i = 0; i < overrideDescriptor.afterSceneBuild.scriptPaths.Length; ++i)
            {
                string sourceFilePath =  overrideDescriptor.afterSceneBuild.scriptPaths[i];
                
                string targetFilePath =  
                    Application.dataPath + 
                    "/Bla/"+
                    ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FullFileName);
                
                var assetsPath = 
                    pathAsset+
                    ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FileNameWithoutExt) + 
                    ParseFilePath.ToFile( overrideDescriptor.afterSceneBuild.scriptPaths[i], ParseFilePath.ReturnFile.FileExt);
                
                FileUtil.CopyFileOrDirectory(sourceFilePath, targetFilePath);
                AssetDatabase.ImportAsset(assetsPath, ImportAssetOptions.ForceUpdate);
            }

            AssetDatabase.Refresh();
            CompilationPipeline.RequestScriptCompilation();
            AssetDatabase.Refresh();
            Type t = Type.GetType(" com.bla.Editor.BlaBla,  Assembly-CSharp");
            MethodInfo method = t.GetMethod("BlaMethod", BindingFlags.Static | BindingFlags.Public);
            method.Invoke(null, null);
        }```
#

Sorry super messy

flint sage
#

RequestScriptCompilation is async and thus won't be done reloading when you try to use reflection

brittle pumice
#

I threw in refresh all over the place

flint sage
#

Besides, if the domain gets reloaded then your code will likely not be executing anymore

brittle pumice
#

That ok this just need to run in editor

#

Once

#

Wait I miss read what you said

#

Ok so how can I do this , in editor

flint sage
#

Subscribe to some callback that triggers after domain reload and then do your magic if needed

brittle pumice
#

Do you have a example? Are then any in unity callbacks that you ca n recommend or an attribute I can add to the method on the script I’m importing

#

All static methods

#

Basically I just need a method to fire on the script a line after importing the script

#

Is there a way to yeild return until reloading is complete

flint sage
#

There's a compiliation completed callback somewhere

#

But that might also not work since the domain is thrown away

#

It's pretty hard to do in general

brittle pumice
#

So hard 😦

#

Throwing the kitchen sink at it

brittle pumice
#

How does unity know if a script has been reimported vs a new script created ?

sage radish
brittle pumice
#

I see thank you

#

Can I trigger a reload on script via other script

novel plinth
#

wdym reload?

fresh basalt
#

so this is in StateMachineBehaviour that is on a single animation controllers state.

#
    {
        if(!stateInfo.loop)Destroy(animator.gameObject, stateInfo.length);
    }```
#

i need to destroy the whole gameobject when the anim ends only if the animation is set to not loop

#

this doesn't work

snow grotto
#

is the animator gameobject never null?

fresh basalt
#

no?

#

this script is attached to a state so the animator wont be null.

snow grotto
#

have you tried removing the delay / stateInfo.length?

fresh basalt
#

that's the thing i think it checks if the state is looping not if the animation clip assigned to the state is set to loop

#

and i have no idea how to get it

snow grotto
#

ah ye, you are sure that the function gets called and there are not base calls missing

fresh basalt
#

no no this is a native callback

#

it gets called

snow grotto
#

you might be able to get the animator current state from the animator, but that would be a bit of a work around

fresh basalt
#

hmmm, i'll try do it in monobehaviour script and set it

#

on this one

gray pulsar
dire berry
#

Hi! Anyone know how to solve this issue? I have just got when i introduced the AI experimental package. Any way to dump/free allocated memory?

undone coral
undone coral
undone coral
undone coral
fresh basalt
#

It didnt work because stateInfo.loop gets the state loop status not the animation clip

stray plinth
undone coral
#

what is your objective?

#

you can't use the animation state machine for gameplay implementation

#

it's too arcane

#

you'll have too many bugs

fresh basalt
#

player launches a object with a combo. I instatiate the object, apply speed to it and based on the animation (a lot of different animations for characters and different combos) i want to destroy it on animation end if the animation clip is not looped and let it fly if the animation clip is looped

fresh basalt
stray plinth
#

Should work 🙂 Does for me, let me know

fresh basalt
#

thank you, i will.

undone coral
#

this is going to be hard 😦

fresh basalt
#

yeah 😄 a pain in the ass

#

if @stray plinth answer doesnt work i think i'll get the statebehaviour script in my monobehaviour code and just set a variable if it is looped or not

#

thanks guys

undone coral
#

have we already discussed this?

#

i don't remember

#

from first principles, you can just use frames counts and assume the application runs at 60fps or whatever, and you will be fine setting up this kind of game

#

where the speed issues don't matter for less than 60fps

#

like where you just fix your game until it performs well enough to exceed 60fps

#

or use a logical timestep of 30fps (i.e., out of every 30 to 60 frames rendered, choose 30 to timestep your game)

fresh basalt
#

hmm, maybe but that will require quite a lot of painfull work to write every animation time in frames

#

i'll try to automate it

undone coral
#

well that's the downisde of these games

cloud crag
#

where to save at local on webgl. please. application.persistent data path is not working

#

Please ❤️

#

file. to Save/Load data

#

Webgl Game

sly grove
#

persistentDataPath works file as the location

stable spire
#

so i have a simple perlin terrain generator which makes a 20x20 surface terrain mesh, however i want a 20x20x20 cave mesh. how would i go about doing this?

compact ingot
stable spire
#

ah alr

undone coral
stable spire
#

and how might i do that?

compact ingot
stable spire
#

alr

compact ingot
#

those assets only work for small scale things, but 20x20x20 is right in their ballpark

cloud crag
cloud crag
brittle pumice
#

@undone coral the purpose is trying to use unity in a more traditional vfx pipeline. No build needed just scene assembly and recording frames. In a traditional pipeline you inject script during various time. I’m trying to get that same behavior in unity by having delegate sitting at different stages of a scene build. New scripts outside the project are copied in and self assign to the appropriate invocation list depending when a artist wants to execute the script

#

The problems I’m running into are forcing assembly reloads and setting up a callbacks addi g to delegate invocation list

undone coral
brittle pumice
#

I know

undone coral
#

is there a vehicle rendered in your scene?

brittle pumice
#

?

undone coral
#

like is there

#

is there a car

#

are cars involved

brittle pumice
#

No

undone coral
#

or a fashion item

#

lol

#

okay

brittle pumice
#

Not fashion

undone coral
#

why would you inject scripts at all

brittle pumice
#

Just pain

undone coral
#

like why not just... add the .cs file

#

to the assets folder

#

etc. etc.

#

what is the idea

#

an artist isn't going to know how to use any of this stuff, so you might as well make the exact UI for the exact bespoke thing they want to do

#

and implement it as simply as possible

brittle pumice
#

The cs file are unknown

undone coral
#

it sounds like you have all the disadvantages of having a way to build the project

#

with all the disadvantages of trying to program at runtime instead of buildtime

#

it's bonkers

#

who's idea was this

brittle pumice
#

Only thing that is know is it will use a giving delegate

undone coral
#

you're going to say the word delegate to a graphic designer?

brittle pumice
#

They are all technical

undone coral
#

New scripts outside the project are copied in and self assign to the appropriate invocation list depending when a artist wants to execute the script
in the editor, there's [Initialize]

#

at runtime, there's [RuntimeInitializeOnLoad]

#

it sounds like you are reinventing one of these two attributes

brittle pumice
#

I saw that late last night

undone coral
brittle pumice
#

But the issue is still getting the assemble reload

undone coral
#

why would you need to worry about that

#

i don't understand why if the .cs file is present in the Assets/ folder

#

and if it's not, why isn't it?

#

why would you start the editor, headlessly, then add a dll file... why do all of that

#

it makes no sense

#

maybe if you gave me a concrete example of what the idea is here

#

is this to procedurally generate graphics of some kind?

#

like what is the concrete application?

#

the only traditional VFX pipeline this makes sense for is some kind of ad / product photography

#

where it's product customizations or whatever

#

otherwise i would not be able to reason why to do this in unity at all

#

or some kind of game inventory

#

like it's animatics for a game that already exists in unity

#

then again... why pilot it from the command line

#

it would help me a lot to know what the real application is

#

lol

#

i'm concerned this is taking a while

#

i think you can give me a logline

#

i have been doing my work in the background 🍿

brittle pumice
#

So in a traditional vfx pipe you have not project folder equivalent to unity project folder. To add permutations to a shot for example you write you python code and at offline render time all tbe various code execute

#

Allowing you to scale permutations 1000x

#

It in that vein

undone coral
#

but what is the actual project?

#

it's not conceivable the artists would need this level of flexibility

#

it would really help to understand what it is

#

because i can help you identify the exact minimum piece of code you need

#

i do vfx, and build pipelines

#

i run a unity builder service

#

is it a crypto thing?

#

are you doing an NFT blah blah?

#

it's okay if the answer is yes @brittle pumice

brittle pumice
#

I’m just sensing frustration from you. I appreciate you taking the time to chip in, I’m going to run a few more test base on some of your suggestions

undone coral
#

i can't help unless i know what it is

brittle pumice
#

Fair enough, I’m also limited it what I can share. I think I need to rethink some things, been a long night

undone coral
#

and you want to render some kind of video for them

#

you would... write the script to do this. everything should be set up in the editor

#

let's say this is for some kind of ad where the end user makes user generated content

#

you would... write the script to do this. everything should be set up in the editor

#

do you see what i mean?

#

let's say this is for a steam workshop sort of deal. people are making UGC unity assets

#

i don' tknow. whatever. you would still write a script ot do this direct4ly

#

so do you see why i'm struggling to understand how this fits in? you say VFX pipeline, but that makes no sense. you gotta help me out here

#

it happens that i am working with someone who is working with a guy named francois, and i think it's just a coincidence @brittle pumice

#

which would make sense for your problem description

#

lol

brittle pumice
#

Not impossible but unlikely

ornate niche
split sundial
#

Is reflection the right way to turn special keywords from a text into their actual ingame values? Or is there another preferred alternative?

#

I essentially rolled up my own localisation system and I'm trying to figure out how is the proper way to replace the values

rocky mica
#

if it helps, I have a singleton manager that handles localization

#

it has an scriptable object with all of the text entries of the game with all of the languages , separated by a dictionary key

#

so everything on the game that uses texts has some kind of script that checks if the language changed, and if it did, updates the text

split sundial
#

Yeah, I mean.. I got that part working
But how do you handle, for instance, a text that says "This upgrade costs X"?
Currently, in my localized file I have "This upgrade costs {cost}", but I'm not sure how to replace "{cost}" with the actual property value

rocky mica
#

We use separate entries for those

split sundial
#

Mind explaining a bit more?

rocky mica
#

instead of using a single TMPro for example

#

we use 2

#

or more, depends on what we are doing

split sundial
#

And then you use a script that sets the value of the second TMPro based on the property value?

rocky mica
#

yup, with that said, we didnt use that many of the type of messages that need parsing. You could also tell translators to leave some stuff like that untranslated

#

and you could do a simple replace

#

Thats my personal experience at least, somebody else might have created their own approach haha

#

but yeah tldr separate tmps is what we did

ashen ravine
#

Hey guys I have very weird question that I gain nothing by googling

#

If you have some docs/blog post I would love to read it

ashen ravine
#

One of the games I am playing which made by unity, downloads patches without updating from appstore. I dont know if its the illusion of patch or not.

#

Is it possible to change the client code in iPhone without making real update from appstore?

#

If so how does this happen?

rocky mica
#

serialized data most likely?

split sundial
ashen ravine
split sundial
#

Images, videos, audio, all of that can get pretty big pretty fast

ashen ravine
split sundial
#

Sort of.. I mean, without any concrete example, it's hard to say, but taking the event example I gave
The code checks at a given time if there's a file called "event.data" (which is only downloaded when an event is ongoing)
The programmers of the game knew beforehand the structure of the evet.data file, so they basically wrote a parser for the data present in it
For instance, the first line is a structure that tells which images need to be loaded in the event banner that will pop up when the player loads into the game
Another line might tell about the music, and yet another might tell about the powerups
It's really a matter of serializing/deserializing data in the appropriate way

ashen ravine
#

Thanks a lot!

split sundial
#

Exactly!

#

Glad to help (:

grim oxide
#

For [Flags] enums, adding a flag is &= and removing a flag is |=

#

Correct?

#

🤔

#

I think it might be the other way around quinThinking

#

I guess remove is ^= quinThinking

#

Apparently it's &= ~X 🤮

final steeple
#

|= X is to add, &= ~X is to remove

undone coral
#

has anyone ever seen

Error when executing git command. fatal: not in a git directory

when building a project that references git repositories in its packages.json?

#

also, is there a way to register events with EventSystem on the "background"? is the only option a "catcher" rectangle in the background?

sly grove
#

Catcher is the simplest way yeah

undone coral
#

for example, i have a big ol terrain

#

i was thinking to have two physics raycaster 3ds, one for the background layer only, and then a normal one

#

but i'm not sure how that'll play out

fresh verge
#

I have a question in relation to FixedUpdate.

When exactly the ApplyForce methods are applied? because I am needing to calculate velocity like this:

_velocity = (CurrentLiftPointPosition - _lastFramePosition) / Time.fixedDeltaTime;
_lastFramePosition = CurrentLiftPointPosition;

_velocityMagnitude = _velocity.magnitude;
_localVelocity = _aircraft.transform.InverseTransformVector(_velocity);

_velocitySquared = _velocityMagnitude * _velocityMagnitude;```

CurrentLiftPosition being = `Vector3 CurrentLiftPointPosition { get => _aircraft.transform.TransformPoint(_liftPoint); }`

It works perfectly fine if I don't apply any force watsoever, but when I do, everything spazzes out at one point, what could the problem be?

Also, I apply forces mostly trough:
```cs
_aircraftRigidbody.AddForceAtPosition(_liftForceVector, CurrentLiftPointPosition);
dire reef
#

Could I create new object of unknown class inherited form abstact class?

undone coral
#

is it possible to differentiate between a click count of 1 on the way to 2 clicks with event system + input system?

#

so far i am seeing, no.

soft hawk
#

like, double clicking?

austere jewel
#

I imagine you would need to write a custom Interaction that checked that you pressed and didn't double click during that press duration

#

Usually most things want to accept clicking instantaneously and will just perform the action regardless of the double-click

#

because having delayed clicks because you could double-click is a bit eh

undone coral
#

i used the unirx solution

novel plinth
#

unirx isn't worth nowadays imho... it's too bloated

tough tulip
# undone coral is it possible to differentiate between a click count of 1 on the way to 2 click...

it also boils down to defining a smart user experience.
most of your single slick actions should be passive. for ex, when single click is performed it shouldn't do some drastic changes to the ui. with that you can simply trigger the single click immediately, and if double click is detected, you can just trigger double click action again.

if you add delay to single click until duble click timer expires, its a bad experience for user and would give a delayed response to them

mint sleet
#
    public async Task<IDataResult<BaseUser?>> Get(string userId)
    {
        return new SuccessDataResult<BaseUser?>(await _iBaseUserDal.Get(x => x.UserId == userId));
    }```
#

Hello. Do you think using ? operator for null operation is a good practice?

#

I am worrying about using too much could cause maintaning issue. What do you think

fresh salmon
#

It makes perfect sense to use nullables where the values can actually be null, whether your type is a struct (all versions) or a reference type (NRT - C# 8+)

#

Makes the code safer by forcing you to take in consideration the cases where the value isn't present

mint sleet
#

Hmm. makes sense to me.

#

Thanks

mint sleet
#
        var resultPhone = await _endUserService.CheckByPhone(phone.Phone);

        if (!resultPhone.Success)
        {
            return new ErrorDataResult<User>(resultPhone.Message);
        }

        await _oneTimePasswordService.DeleteAll(phone.Phone);
        
        var newOTPCode = _oneTimePasswordService.GenerateCode().ToUpper();

        OneTimePassword newPassObj = new OneTimePassword()
        {
            Phone = phone.Phone,
            IsConsumed = false,
            CreationDateTime = DateTime.Now,
            ValidationEndDateTime = DateTime.Now.AddMinutes(1),
            OTP = newOTPCode,
        };
        await _oneTimePasswordService.Add(newPassObj);```
#

My next curiosity is if I need to check all returning objects if it was successfull to proceed?

lapis arch
#

hey guys

#

does anyone know how I could import the System.Windows dll in unity?

fresh salmon
#

Drag-drop into your assets, it'll check if the versions match and throw an exception if it doesn't

lapis arch
#
var uiSettings = new Windows.UI.ViewManagement.UISettings();
        var color = uiSettings.GetColorValue(
                                Windows.UI.ViewManagement.UIColorType.Background
                               );
        return color.ToString();
#

I wanna use this method and it throws me the error

#

The type or namespace name 'Windows' could not be found (are you missing a using directive or an assembly reference?)

#

My target platform is android. However this script is in an "Editor" folder

#

The error should be fixed if I import the windows .dll right?

stone bough
#

this just throws me an 'Player script does not have an variable called [variable name]', maybe because this line T playerScript = player.GetComponent<T>(); is using T the wrong way but not sure how to properly use it
if i put T as a argument like this hi(T component, other variables) the T playerScript = player.GetComponent<component>(); won't work even with a typeof or .GetType()
(oh and im trying to edit a value of an variable by the name on another script)

regal olive
#

is it possible to check if an array contains an object of a certain type?

#

in a simple expression like oneliner?

humble onyx
regal olive
fresh salmon
#

I have Array.Exists<T>(T[], Predicate<T>) on my side

stone bough
#

x is the item in the array

fresh salmon
#

So a one-liner type check would be something along these lines

Array.Exists(arr, item => item is OfACertainType);
stone bough
#

if x.age == 12 is true the function will also return true

#

oh whoops thought he meant value not type

regal olive
fresh salmon
#

You'll have to use LINQ for that

regal olive
#

another query so?

fresh salmon
#

Look into .FirstOrDefault, accepts a lambda, and returns the first item that matches the predicate, or default if it wasn't found

#

Can combine both in one here

#

Not found = returns null or whatever the default value is for that type, check it in a if statement

#

Oh, array has that integrated lol

T item = Array.Find(arr, item => item is OfType);
if (item == null)
//...
regal olive
#

oof

#

it doesn't let me do that with raycasthits for some reason

fresh salmon
#

Ah yeah because RaycastHit is a value type, that can't be null

#

Check hit.gameObject == null, or hit == default

regal olive
#

hit.collider works right?

#

i don't think i can access the go directly

fresh salmon
#

Ah yeah sorry about that

#

You can check the collider yep

stone bough
# stone bough

figured it out just needed to get the field not the property

regal olive
#

well for some reason this isn't working for me...

#

is there a better way I can check if an object is of a certain type? or am I doing it wrong?

#

I didn't want to iterate through all objects and try get component

fresh salmon
#

You'll have to TryGetComponent

mint sleet
#
    public static IResult Run(params IResult[] logics)
    {
        foreach (IResult result in logics)
        {
            if (!result.Success)
            {
                return result;
            }
        }

        return null;
    }```
#

Hey people! Do you have any idea how I could use async for foreach?

#

Thanks

regal olive
#

well any idea why my hit variable isn't updating on the if == null scenario?

#

ps: i found out it was because of the hitCollider variable, but still don't know why

left badge
#

Hello, I am currently moving gameobjects with coroutines using something like that

float curTime = 0.0f;
do
{
var percent = Mathf.InverseLerp(0.0f, duration, curTime);
var newPos = Vector3.LerpUnclamped(startPosition, endPosition, moveAnimationCurve.Evaluate(percent));
transform.position = newPos;
yield return new WaitForEndOfFrame();
curTime += Time.deltaTime;
} while(curTime < duration);
#

And what I want to do now is be able to speed up this animation while it is running, but I am having trouble seeing the best way to do so

#

I thought about shortening the duration but it just makes the animation jump forward because the InverseLerp will not be smooth between the frame with the old duration and the new one

flint sage
#

Add a multiplier to curTime += Time.deltaTime

left badge
left badge
#

Is there any problem with having multiple canvases at once ? (for example one canvas per scene and using additive scene load)

novel plinth
#

nope

#

you can have lotta canvases in one scene

fresh salmon
#

And it's actually recommended to have multiple canvas, as updating a canvas element might redraw the whole canvas [citation needed]

regal olive
#

How can I order an array of gameobjects based on it's layer.
What i'm trying to achieve is an array that is ordered based on a priority, so I want all objects from a certain layer first then the second layer then the third etc...

#

I was thinking about using the orderby but what should be my compare function?

snow grotto
#

How would I translate the blue arrow to the green arrow using the red arrow, I want to move the player along the ground normal

regal olive
#

Why not using playercontroller? I believe it deals with those situations

snow grotto
gentle storm
#

hello there can i ask UnityEditor questions here??

snow grotto
#

at least with the normal move function

snow grotto
gentle storm
#

this is my code when i try to import the prefab

#

it wont accept it

gentle storm
#

pls help me 🥲

snow grotto
#

do you get the selected object?

gentle storm
#

i define the car?

#

i meant select it

ocean igloo
umbral trail
#

can someone tell me what "Instantiate.Produce" in the profiler is doing?

undone coral
#

i am trying to deal with the kind of user who taps repeatedly and give them a big feedback

#

because that's about as much as their monkey brains can handle

undone coral
regal olive
#

does anyone have an idea why ztest isn't working on shadergraph shaders?

#

i'm trying to make an outline for occluded objects but it seems like it isn't working for the occluded parts of my object

umbral trail
ocean igloo
#

that is quite stupid....
will it run the generator for both srcipts in assets and the package?

safe lotus
#

does anyone know why things like position constraints and getting the actual transform position of objects affected by AnimatorIK will have their positions properly show in scene/game view but anything tracking them won't?
I've tried GetBoneTransform, the actual GO, and a few other methods.

wicked eagle
#

Are there any downsides to loading tiles into a Tilemap via SetTile and SetTiles vs having the whole Tilemap and all tiles load when the scene load?

#

I'm planning to load my levels from text files and then setup the Tilemap during runtime but I'm afraid it would affect performance

gray pulsar
#

like loading from text files

#

you could set up a pipeline that does all the tilemap building work at edit time

#

still load from text files, but have an editor tool that loads them then saves as a normal tilemap

#

but honestly, loading screens aren't that bad. If you're just doing it while loading the level the performance is probably not much of an issue

wicked eagle
#

Awesome! Thank your for the answer! As you say the flexibility is very nice and I would only use it during loading screens so it might not be a problem, pipelines sounds interesting as well

#

a good option if loading screens turn out to be too long

gray pulsar
wicked eagle
#

thats a good idea, going to use it for building a level editor so might need my own format but knowing how they do it could be really useful

snow grotto
#

would that be more efficient

cedar ledge
#

Nah I'm wrong my b

heady bane
#

is there a way to get addressables to work on ios?

fickle mango
heady bane
#

no error in unity, but in xcode it gives addressables the key squareapple and makes them unloadable

#

Page changing to: StartUp Ustyler.Behaviours.UI.UIManagers.<SwitchPage>d__31:MoveNext() System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start(TStateMachine&) Ustyler.Behaviours.UI.UIManagers.UIManager:SwitchPage(PageBehaviourType)

#

Unloading 6 unused Assets to reduce memory usage. Loaded Objects now: 7826. Total: 9.534333 ms (FindLiveObjects: 0.257750 ms CreateObjectMapping: 0.127042 ms MarkObjects: 9.084500 ms DeleteObjects: 0.064458 ms)

#

ArgumentException: An item with the same key has already been added. Key: SquareApple at System.Collections.Generic.Dictionary2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior)`

#

though in unity the script asset pack group schema cannot be loaded

#

so I think that is the cause

#

which would suggest a compilation error, but there arent any I can see

surreal vessel
#

anyone got any experience with math parsers or something sinmilar i could use here?
essentially i want to have a lot of flexibility when it comes to designing my ais, and that includes the direction every bullet is shot. sometimes thats a fixed value, sometimes thats at the player, potentially with an offset, but sometimes i may want to do it based on time, or sin time etc. without having a million checkboxes

#

my idea is a string field where i can put something like $PLAYER + 90 or Sin($TIME / 2) * 90

fickle mango
surreal vessel
#

yes but how would i interface that

#

how would i then be able to choose which to use

#

or maybe different shoot behaviours depending on what type of expression im using?

#

so one thats like FixedAngleShoot and one thats SinTimeShoot or something

#

i suppose it could work

unkempt nova
#

That sorta thing is usually done by like, a dropdown to select Value where you enter a literal value of 90, or some other option and the editor will show an object field. Could use a scriptable Object or something to drag into this, to spit out a value or perform some operation on it. I think Game Creator does their numbers this way, similar to what you're wanting

#

Not saying use GC, but the idea they're using here fits I think

regal olive
#

hello im a beginner coder, and ive never coded before (besides lua but not much). how would i correct errors in a unity project? (the project in question is HyperEngine by CodeParade)

unkempt nova
regal olive
#

okei

heady bane
#

im getting this on several of my asset pack group schemas

#

I cannot see an error in the console that would be causing this

#

could reinstalling addressables help?

heady bane
#

a reinstall did not help

#

is there anything im missing with addressables? its just I cannot see a reason why this would be happening, and im currently going off by best assumption of what will solve this problem based on the missing assetpackgroupschema script reference.

#

ive tried now removing that file for one of the groups to see if it has made a difference, but I wont know til a build has been done, which does give a very slow turn around with debugging problems

#

Tried a build and nothing

#

still the same problem

#

doesthe squareapple key mean anything in xcode?

fickle mango
heady bane
#

only ios as far as I know

#

my co worker can build to android and run it on android fine

#

I cant find build player content?

#

ive be building the asset groups?

#

im pretty sure ive been doing that

#

clean build then a new default build

#

could the default build script be broken and not building anything outside of the default group?

heady bane
#

should i light the addressables on fire?

wooden cedar
#

You will feel better if you do