#archived-code-advanced

1 messages ยท Page 146 of 1

gusty rivet
#

would be this the proper place for asking about git and unity?

#

I am attemtping to add .csproj files to it (since unity generates them)

#

but it just ignores, all other file types are ignored as per .gitignore rules

#

but .csproj files are not

#

I somehow fixed it... it would remove to stop tracking changes, but if I delete the file, comit, and restore, it will not be re-added to the git

sly grove
#

They are auto generated by Unity

#

This will just cause unecessary churn

gusty rivet
#

yeah, I was trying to remove them from source control

#

and git was refusing to accept that I wanted them gone

sly grove
#

Yeah you have to do git rm --cached <thefile> then commit that

#

if it's already being tracked

gusty rivet
#

until I deleted them, commited, and then restored them from the trash bin

#

hmm, well, now I know that it won't stop being tracked just because it was told to be ignored

sly grove
#

yeah if it was already tracked, it will continue to be tracked

#

until you explicitly remove it

fervent sage
sly grove
quiet rivet
#

Hello everybody,
Someone has used the Unity packages for integration with ROS?
For robotic simulation.

undone coral
#

is this in editor?

fervent sage
undone coral
#

first play in editor?

fervent sage
#

yes

undone coral
#

it seems painful i'm sorry

fervent sage
#

?

undone coral
#

this bug

fervent sage
#

oh? will it matter though? it seems fine when I build it

#

and I can play now in editor no problem

#

I have another issue now XD

#

I'm having a lot of trouble figuring out how I am meant to use asset bundles so they don't take gigabits of RAM.
I am downloading my bundles with:

UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url,version,0)
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);

Then saving that bundle to a variable in a singleton for access during runtime: data_bundle = bundle;
Then, when I need the images for my cards in the bundle, I load them all into a dictionary from the bundle like so:

imageCache[imageName] = bundle.LoadAsset<Sprite>(imageName);

And then when a card needs an image take it from the imageCache.

This is obviously wrong, I did the same thing with the resource folder, and I am now using more than double the RAM. Why? - what is the correct method to use AssetBundles?

undone coral
#

you're kind of running into headache after headache of... reinventing the distribution of JPEGs

#

it's just tough

#

you're not doing anything wrong

fervent sage
modest lintel
#

Looks like when using bundles your assets when decompressed are living entirely inside RAM..? And when using Resources they aren't fully stored there? Spitballing honestly

undone coral
#

i can help with that

#

and i've used addressables

#

asset bundles have always been radioactive so i never bothered mastering them

#

how can i help the most

fervent sage
undone coral
fervent sage
#

.>

undone coral
#

lol

#

but i was doing something pretty idiosyncratic - addressables for WebGL

#

do you want to hear out the alternative?

fervent sage
#

hmm

#

yeah

fervent sage
undone coral
#

you can DM me

#

it just happens that i run a card game

woven crow
#

Hi,
What could cause some Unity components to stay after being destroyed ?

sly grove
woven crow
woven crow
#

But anyway if i swap to an empty scene they should be destroyed right ?

sly grove
#

Destroy cleans up the native half, and tombstones the C# half

woven crow
#

I guess it's the case, and I suspect ML-Agent to keep references of my agents

sly grove
#

But C# is garbage collected - so if you have any references to the C# part, it will stick around

#

could be

woven crow
#

So if I understand correctly, everything inheriting from Unity.Object is managed by unity, but if I still keep a reference to a component somewhere, then everything related to this gameObject will stay in memory ?
But from my previous experiences, when I try to access to a destroyed component, either unity will tell me i'm trying to access to a destroyed component, or the value is "null"

sly grove
#

that's how it knows the difference between a reference that was never assigned vs a reference that was assigned to an object that got destroyed

#

I wouldn't say "everything related to this GameObject" stays in memory. Just the bits and pieces you have references to

woven crow
#

I see, thanks for the explanation
I see, and in case something out of my control keep a reference to an object, and I want him to free it, what are my options ?

#

I guess I could unreference everything in this component relative to my game in OnDestroy

#

Cause I suppose using some kind of GC.Collect(identificador, GCCollectionMode.Forced); would be too dangerous to use in the gameLoop with Unity Execution order loop

sly grove
#

It won't collect anything there's still a reference to

woven crow
#

I see, okay thanks

small badge
olive totem
#

It's better to program defensively though, so don't allocate when it's not needed and reuse as much as possible

woven crow
#

Ok, well i guess c# is not designed to choose when to free anything, GC handles it by itself.
Yeah, but in my case with ML-Agent, there is a big part of Observation Data collection, and it's quite hard to do it without allocating tons of stuff

olive totem
#

The allocation itself isn't the problem, the potential reallocation is when you don't pay enough attention

woven crow
#

Yupp, and it became hard to debug afterwards

tough tulip
small badge
tough tulip
#

there's only one component attached to it. give it a try

undone coral
undone coral
#

there aren't many things you have to Destroy though

gray pulsar
undone coral
#

for things like textures, you're better off using virtual texturing nowadays

undone coral
#

i never need to know the difference between a null and a destroyed Unity.Object, i don't think anyone else does

woven crow
undone coral
#

i wouldn't characterize it as a leak though

woven crow
#

I have still tons of references of destroyed components in the snapshot

undone coral
#

you might load something, and not use it, but it's not a leak

undone coral
#

components rarely do

#

what are you really trying to do?

woven crow
#

In fact, it's mostly strings

#

I'm using ML agent, so I run a very big simulation

undone coral
#

okay

#

and you're saying, "my thing that is designed to use incredible amounts of memory, is using incredible amounts of memory"

#

like what do you expect ML agents to do?

#

use less memory?

#

that is its modus operandi

#

the lifecycle of what it does uses huge amounts of memory

#

so what specifically are you observing?

#

are we talking about system or graphics memory?

#

for this sort of thing, if you appear to be doing everything right, seriously, buy more RAM

#

that is the #archived-code-advanced solution. for sure, for ML-Agents tasks that matter, that are scientifically interesting, you do not want to be wasting time on this

woven crow
#

with 6x fields, 8 envs, time scale x10, and the memory keep increasing
And now i'm investigating with the memory profiler, I still see tons of references to somes classes my characters uses

undone coral
#

what is your application

#

like what are you trying to do

#

are you training an agent that...

#

or are you trying to run an agent that...

woven crow
#

It's a game, basically ML-agents IA vs BehaviorTree IA

undone coral
#

okay but what are you trying to do

#

for example, "I'm training a neural network based AI in a physics based ... 1v1 whatever kind of game ... with bootstrapping against a heuristic AI"

woven crow
#

Oh i see
Basically an autochess Game powered by ML-agent on one side, against BehaviorTrees enemies

undone coral
#

okay

#

is your game playable?

#

without the ml-agent?

woven crow
#

Yup it is, ml agent is working correctly also

undone coral
#

first, i would say, this is hopeless for a neural network to play, for all but the absolute most simplistic versions of this game, which you might as well first implement in an embedded library

#

if you're at the obstacle, "it's using too much memory," you're at the start of a very very long journey

#

if you want to do this is a serious way, yeah, go buy more RAM

#

and probably, write a non-physics version of this game in C++

#

a headless version

woven crow
#

The game is already working, the training works on a linux healdess server with 128G ram
My main concern is the memory increase during training, and I can't figure how to release it, at first the env are 400mb and some point each instances take more than 10G

#

So I can restart the trainingevery 8hours, it's fine, but I'd like to understand what's going on

#

Tons of classes still stay in the last memory snapshot, and they shouldn't exist aanymore

undone coral
#

what is the learning task here?

#

why are you doing the training inside unity?

#

in a competitive AI task, you would only do inference inside your game engine

#

since this doesn't sound like a robot

#

i haven't found a single peer reviewed paper that uses ml-agents yet

#

okay, i found one for a PPO task

#

it just doens't make sense is all

#

it's not a physics driven game

#

it's not even 3d

#

the ml-agents code is going to be really buggy

#

do you want to fix bugs in the ml-agents package?

#

that's what you are signing up for

#

it doesn't "leak memory" so much as it is "not designed for some tasks"

#

i would recommend getting a 2TB RAM headless server for this

#

i don't know why you decided that 128G is enough, when it's telling you it's not

#

or don't do the training inside of unity, but i can't recommend that because you haven't told me what the task is

woven crow
#

The training task is "Fighting enemies and aim to win the fight"
And i'm following the normal way of training/inference with Unity Ml-agent, however, the memory increase is still there even if i'm not training (when y agent do not move and get killed)
Because everytime my agents succeed/fail, I reset the instance, and replaces agents and enemies with new ones. And the memory increase more and more

#

We already have a game release with ml agent

undone coral
#

PPO doesn't work for strategy games

woven crow
#

This one is another

#

Training is working, fighting is working

#

mobile inference is working

undone coral
#

i think you should get a 2TB server

#

there are a lot of high memory options on AWS

woven crow
#

And i'm 100% sure i'm doing something wrong, cause otherwise my memory usage would stay stable

#

and a stable 500mb/instance

undone coral
#

i think you do your training in a system built and tested for it

#

if you want to do this in a serious way

#

it's probably not a memory leak

#

i don't know what it is

woven crow
#

We are using ml agent cause it facilitate inference on mobile devices

undone coral
#

the simplest solution is to use the larger memory AWS servers

#

yes but you can train differently than you can infer

#

there isn't any cross-platform inference in reality, but some people experiment with ONNX

woven crow
#

it's not in ML-agents, there are tons of references of my own classes in the "new scene snapshot"

undone coral
#

which Barracuda the ml-agents inference engine can use

woven crow
#

thoses references should not exist anymore

undone coral
#

anyway i think this is the start of a very long journey

#

you'll figure it out ๐Ÿ™‚

woven crow
#

Still there was some disagreement on the fact that destroying a monobehavior also free the references attached to it, as malloc and thm disscussed about

undone coral
#

i just can't see how this has anything to do with anything

#

Destroy isn't recursive

#

is that what you mean?

#

just because you Destroy an X x, doesn't mean a texture referenced in it x.y will also be destroyed

woven crow
#

I mean, if you have a component on a gameObject, and in another gameObject, a reference to this component

undone coral
#

you're being way too abstract

#

what exactly are you looking for?

#

is it a texture?

#

it should tell you

#

you said "strings mostly"

#

like what specifically?

#

the C# references to destroyed game objects are meaningless

#

they will not impact your RAM significantly

#

if they appear to be, that's a red herring

#

it means you're misinterpreting what it's trying to tell you

#

the memory profiler is telling you what is using up memory

#

so what is it? textures?

#

for eample, does your game do var material = renderer.material; material.color = Color...; renderer.material = material;?

#

Destroying an object with an instance material will not destroy th einstance material

#

and materials can sometimes take up a lot of memory, but it's unlikely

#

they'd have to be really radioactive

#

if you do

var x = new GameObject("").AddComponent<X>();
x.listOfStrings = new String[] { ... one million strings ... };
this.privateListOfStrings = x.listOfStrings;
Destroy(x);

you will still have an array of one million strings, because they are referenced

woven crow
#

I have my creatures in my game, they contains tons of stuff inside, abilities, characteristics, but also the last observation inputs (with their string id), the strings are the biggest part but it's not crazy. Thing is i'm destroying agent and recreating them every time a game restart in the simulations, so there are thousands of creation/deletion of agents

#

And in the last memory snapshot, I still find all thoses references to dead (and destroyed characters)

undone coral
woven crow
#

And thoses component have been destroyed, so their fields must also be null, unless something keep them alive

undone coral
#

are you sure you're Destroying the right thing?

#

no

#

destroying doens't set fields to null

woven crow
#

if nothing references the fields it should cause the fields would be garbage collected no?

undone coral
#

destroying isn't recursive in most circumstances

woven crow
#

I mean, I changed scene to another one

undone coral
#

yes, but garbage collection is not destruction, and your memory snapshot might occur before garbage collection, etc. etc.

woven crow
#

all gameObjects should be destroyed after scene change

undone coral
#

do you use DontDestroyOnLoad anywhere?

#

is this memory snapshot generated from the editor

#

or from the running player?

woven crow
#

No, I uses scriptableSingletons for my Singletons, but I made sure my singletons references doesn't keep any references to the creatures

undone coral
#

...do you though?

#

i mean

#

those references wouldn't matter

#

the arrays of strings

#

they could be referenced anywhere

#

and the profiler isn't going to tell you where

woven crow
#

Can't be sure for BehaviorDesigner and Ml-agents, they might keep references to my agents

undone coral
#

for example, a list of observations - i don't know how ml agents works, but it could reference them

#

it doesn't matter if it's a field

woven crow
#

The profiler tells me where the objects are referenced

undone coral
#

destroying an object does not destroy the fields in many circumstances*

#

well clearly that's a red herring

#

right?

#

i mean it's obviously wrong, so there must be something you're misinterpreting about what it's telling you

#

so if your profiler says this array of strings "isn't referenced" that doesn't mean it's not referenced

woven crow
#

Everything is referenced somewhere, otherwise they would not appear

#

you mean the profiler may not be accurate?

undone coral
#

this might be easier to use

#

but really you should use a pro memory analyzer like dotMemory or Visual Studio's

woven crow
#

Anyway I just want to make sure of something, let's say I do

GameObject mygameObject = new GameObject();
var mycomp = mygameObject.AddComponent<MyComp>()
var lstr = mycomp.lstr1;

With:

public class MyComp : MonoBehavior {
  public List<string> lstr1;
}
#

And then I Destroy(mygameObject)

#

then lstr would still be existing, but mycomp would be = null right ? ( 1 frame after cause of Unity execution order destroy object after everything)

#

I'll try this memory Profiler thanks

long ivy
woven crow
#

Okay thanks, yeah that's quite an important distinction

#

So yeah I understand better the previous aswers about this

small badge
#

I'm still philosophically opposed to Unity's overload of == null, but I have to admit I've been tripped up more often by the cases where it isn't used than the ones where it is.

woven crow
#

Until now, I didn't had to care at all about the duality of UnityObjects and c# Objects of components

#

So I guess it's not that bad haha

brave sail
#

Guys, how can I make an infinity loop in a simple class (not MonoBeh) without alocationg new memory for Task.Yield or Task.Delay in every cycle of loop?

frigid notch
#

For example if you want to make infinite loop for a countdown you can
private void Update()
{
countdown -= 1 * Time.deltaTime;
}

brave sail
# frigid notch Can you give more details?

I have an infinity async loop, and every cycle i'm awaiting for Task.Delay or Task.Yield, but each of that methods creates new class instances that will be removed by GC in the future, can I make my loop in a better way? or with a little bit more performance? : D

frigid notch
#

while(true)
{
}
or for()
{
}

brave sail
#

I don't want to use monobehaviour(

frigid notch
#

I don't think that's possible

#

Why not in MonoBehaviour?

#

@brave sail?

flint sage
#

While true is an infinite loop

#

What's your actual goal

brave sail
#

My goal is to not make garbage from Task.Yield and Task.Delay

#

@frigid notch , okay, thanks, I guess I will rewrite my code to use Action/Events, and remove my loop (

frigid notch
tough tulip
tough tulip
thorny gulch
#

Hi all. i have Tap strap 2 connected to my pc with bluetooth. but Unity Editor seems not seeing it. when i build on Android, app works
But unity editor and building for pc not working.
what can be the problem?
Thanks

woven crow
frigid notch
#

Also make sure to change game aspect and simulator

tough tulip
woven crow
#

Oh okay, that's a specific case for WeakReferences

tough tulip
#

yes which also means that my test about fields not being gc'ed might be wrong

flint sage
#

I'm skpetical that your test is done correctly tbh

thorny gulch
frigid notch
#

@thorny gulch

thorny gulch
#

it is called platform

#

yes i do have

#

windows and android

frigid notch
#

what's problem then

#

when you build it doesn't execute?

thorny gulch
frigid notch
#

switch platform?

thorny gulch
#

on android it works, when im connecting devices to the phone

#

building for windows and connectin devices to the pc, not working

frigid notch
#

wdym by not working

tough tulip
woven crow
#

I just found out my issue tho,
My agent were subscribing to a static Action, and never unsubscribing, and that was leading to keep all the references to everything

#

Pretty bad idea to use Static Actions

#

Even if it's convenient at first

small badge
mortal orchid
stable spear
#

oops misread

stable spear
#

Also, you are launching a different instance of WaitAndRun() every frame that NotIsCollided is true

#

you could end up with 100s of WaitAndRun()'s running simultaneously, which is probably not what you actually want

mortal orchid
stable spear
#

what is the goal ?

mortal orchid
#

See there is a yellow bar slider

#

When the green segment collided with the red segment the bar would be in an idle state but the moment both segments do not collide with each other and 4 seconds have been passed then the yellow bar shaking animation has been started running and it will stop the moment they collide again

stable spear
#

Try this?

Coroutine waitCoroutine;
...
        if (moveRunner.IsCollided())
        {
            anim.speed = 1.5f;
            movementSpeed = 1500f;
            sliderAnim.SetTrigger("toIdle");
            if (waitCoroutine != null) {
                StopCoroutine(waitCoroutine);
                waitCoroutine = null;
            }
        }
 
        else if(moveRunner.NotIsCollided())
        {
            anim.speed = 1f;
            movementSpeed = 1000f;
            if (waitCoroutine == null) {
                waitCoroutine = StartCoroutine(WaitAndRun()); 
            }
        }
tough tulip
stable spear
mortal orchid
stable spear
#

are you sure moveRunner.IsCollded() / NotIsCollided are doing the right thing?

#

you might want to put Debug.Log("IsCollided"); and Debug.Log("NotIsCollided") in each respective branch to see if it is doing the right thing

mortal orchid
#

colliders are working perfectly fine because the animation was running just the 4 seconds delay was the issue.

tough tulip
#

also, you should add logs once just for the sake. even im suspicious of IsCollided checks

tough tulip
# mortal orchid both logs working

log printing is one thing, and working as intended is one.
well, can you move the logs inside both waitCoroutine != null check, and also the waitCoroutine == null now

#

there's a possibility for such situation where:
i) NotIsCollided becomes true for 1 frame, Coroutine starts which waits 4 secs before triggering the animation
ii) Next frame or any frame before 4 seconds, IsCollided becomes true, hence cancelling our the Coroutine which was supposed to wait for 4 seconds before triggering the animation with delay

mortal orchid
#

The animation is not playing entirely when doxdust changes the code.

tough tulip
mortal orchid
#

I have moved the logs as you described in null checks

#

still collision and not collision printing on screen

#

as before

tough tulip
mortal orchid
tough tulip
#

it should be IsColliding only. and when its false, its not colliding. you shouldn;t need a second func

mortal glen
#

is it possible to use an attribute like [Range(0, 19)] but have the value range differ based on for example a bool or enum?

#

example isHuman = true, [Range(0, 5)] else [Range(0, 10)]

devout hare
#

You can use variables instead of number constants

#
int max = isHuman ? 5 : 10;
whatever[Range(0, max)];
#

or put the ternary directly as the parameter

small badge
mortal glen
#

@small badge I have Odin, but besides its being paid, it also has its own revcap.

#

(in its tos)

#

Thanks for the solution @devout hare

small badge
#

Yeah, it's a limiting option in a couple of ways (though if you're lucky enough to be making over $200k annual revenue a $250 annual fee is much more manageable).

devout hare
#

Oh yeah, a variable prob won't work in attributes

small badge
#

It won't, no. Even with Odin's solution the code would look something like [PropertyRange(0, "@this.isHuman ? 5 : 10")] (and the inspector code would parse the logic out of the string parameter).

tough tulip
grand stag
#

I'm trying to grab this string from a web API anyone now how I could do that?

#
        string formulaJSON = "";
        // Get JSON for Formula 
        using (UnityWebRequest webRequest = UnityWebRequest.Get(jsonMolecularFormulaURL))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();
            
            string[] pages = jsonMolecularFormulaURL.Split('/');
            int page = pages.Length - 1;

            if (webRequest.isNetworkError)
            {
                Debug.Log(pages[page] + ": Error: " + webRequest.error);
            }
            else
            {
                formulaJSON = webRequest.downloadHandler.text;
            }
        }
        var Formula = JSON.Parse(formulaJSON);
        Debug.Log(Formula);```
long ivy
grand stag
long ivy
#

I don't know what JSON library you're using, but if you wanted to use Unity's JsonUtility, you can just create a set of objects to deserialize the json into and grab it directly, e.g.:

[Serializable] struct MolecularFormulaJSON { public PropertyTable PropertyTable; }

[Serializable] struct PropertyTable { public List<Property> Properties; }

[Serializable] struct Property { 
    public string CID;
    public string MolecularFormula;
}

and then
var result = JsonUtility.FromJson<MolecularFormulaJSON>(formulaJSON);
finally
Formula = result.PropertyTable.Properties[0].MolecularFormula;

grand stag
#

Thanks so much, I'll try that out

drifting galleon
#

or if you are confident that the structure never changes, and you just want the C9H.... just use Regex

young spoke
#

Im making a skateboarding game. I have everything done besides grinding and most tricks. I need help with having the player locking into the rail in the direction the player rides into it. I mostly just need ideas, not much help. For now

#

Please dm me rather than @ - ing me

#

ty

untold moth
slender stag
#

I am making a stationary turret in my game, and the turret will only shoot if it sees the players position so if a player peaks out from a corner and hits the aims for the corner of the turret, they will destroy it without the turret hitting them because it doesn't see them.... how could I make it look at the colliders or the mesh of the player?

untold moth
#

You could make it respond to taking damage. If it's damaged and the damage source in it's reach, it should turn and fire at the damage source.

slender stag
#

Problem is, if the players transform.position is behind a wall for example the turret will think it's impossible

slender stag
untold moth
#

Clipping?

slender stag
#

No, if they are behind a corner

#

Because my player is a tank, but if they get their Hull behind a corner, and their turret, they can hit the stationary turret and it won't respond

#

This is why I posted it in this channel, since I want to see how I can get the colliders (vertices) of the player and see if I can hit it

#

Or the mesh, not sure which one is better

untold moth
#

You could do that with vertices of course, but assuming you're gonna raycast to see if there's a wall in between, it might be super performance heavy.

slender stag
#

How much raycasts do you think should I make?

#

I am thinking maybe 5 or 6 at max

#

(Counting tranform.position raycast)

untold moth
#

Maybe 4 or so near the corners of the tank mesh.

#

8

#

So like cube or rhomboid corners.

#

Could also do something like frustum check for the turret. And see if the collider bounds are withing the frustum.๐Ÿค”

#

But you'll still need some way to target the exposed area.

timid coyote
#

Anyone around that can help me with a Projector setup?

slender stag
#

Yeah cause I want to use this method for my vertical autoaim for the tanks (tanks only shoot straight currently)

timid coyote
#

@slender stag ... Is the raycast basically the barrel of the firing tank?

slender stag
#

Currently, I use only the raycast for the bullet

#

(Bullet, uses Update every frame to shoot a raycast from its previous position to its current position, if it hits something it explodes and does its checks if it's a hittable object)

timid coyote
#

@slender stag... So yes, the raycast represent the bullet's trajectory.

#

If I remember my racasts correctly you'll get an array of all the HIT objects ... so all you need to do is check the first item and if it's not the tank, or a hittable collider on the tank then ther is no hit.

slender stag
#

That was not the question though

sly grove
# slender stag How much raycasts do you think should I make?

I would make an array of points (empty child objects) on your character representing the extremes of the character, so one of the extreme right and left, one extreme top and bottom, one in the center. Don't do a fixed number, just do one raycast per point in that array

#

then you can configure it differently for different characters etc

slender stag
#

Is LookAt also intensive?

sly grove
#

no

slender stag
#

Cause I could make it use lookat to see in which direction is the player, then shoot a raycast in that direction, to see if it hits the hull

lean mason
#

can i get feedback on my singleton design pattern

#

thanks!

wise bobcat
#

is there any way that I can also serialize animations

slender stag
#

Make player objects white (for the camera) and all other objects black (fixed autocorrect)

mint kraken
#

@wise bobcat animations are simply just position rotation scale stored in a timeline, so you can sample the anmation get all the data ,serialize it, but deserialize the data make a animation is the hard part

#

I'm using shader to play animation so I don't have the second part problem

wise bobcat
#

however custom serialized anims would make things go hard

#

will any encryption work at this point?

tough tulip
#

why do you need encryption just to make animation work? Unity animations are well optimized at what they are doing

#

But yes, unity reads and parses the yaml for you and also generates the yaml for you when you animate something in unity. Unity also generates the clip from any fbx you import

dire sparrow
#

Is there any RUDP Solution with proper documentation for C# that you know?

flint sage
#

Why would you want to encrypt your animations 0.o

mortal glen
#

is there a smarter way than to attach your player gameobject to a platform as a child?

#

going up and down will work good enough because of gravity

#

(i want the Zelda mechanic, where the platform keeps moving with you on it

tough tulip
tough tulip
lunar raft
#

So, I have a procedural model generation framework that I am thinking about converting to a multithreaded system and introducing dependencies. (Imagine generating two cubes and then creating a union of those two cubes.. so clearly the generation of the two cubes are independent actions... but the union action is dependent on the completion of the first two actions.)

Is there a good pattern/framework in Unity to do this?

sage radish
lunar raft
sage radish
lunar raft
sage radish
lunar raft
lunar raft
#

Is it just me or did Unity complicate things by backpedalling on how beta packages are managed.

mortal orchid
#

https://pastebin.com/hSP4Aank I want the animation to be triggered after every 4 seconds when a collision does not occur. But the animation is running after 4 seconds just for once then after every collision Exit animation starts running suddenly without any wait. It would be kind if anybody could see it.

devout hare
mortal orchid
lunar raft
#

Is there a common fix for this. Googling is a dark and deep rabbit hole:
[Package Manager Window] Unable to perform online search:
Cannot connect to 'staging-packages.unity.com' (error code: ENOTFOUND). Verify your environment firewall policies allow connection to this host name. If your system is behind a proxy, verify your proxy environment variables (HTTP_PROXY and HTTPS_PROXY) are properly set.
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

fresh salmon
#

Doesn't exist on the internet*

lunar raft
regal olive
#

hey sup guys so my weapon has a firerate script that works fine like it is but i have more weapons so i want my weapons to have different firerates how can i do that

young spoke
untold moth
# young spoke could you explain in more detail? thx

Ummm... There's nothing much to explain. You just need to know the direction that goes along the rail and project your facing/movement direction to to get the new movement/facing direction along the rail. Of course you also need to set/lerp the position to a point along the rail(at least initially).

young spoke
#

why is it that when I rotate my player when not playing the game it rotates of the z axis but on the y axis when playing the game?

shell horizon
#

Ran into an obnoxious issue with script execution order and coroutines. Apparently everything after the first yield executes after all updates are finished. I need it to run at the same time or before start. Is there anyway to achieve this using coroutines or am I going to have to find another solution?

tough tulip
#

I just tested few days ago and mentioned it here as well. WeakReference prevents GC collection in Unity. Not sure if that will ever be fixed or if it's known even

#

I'm not sure if it's caused by incremental gc or not

tough tulip
tough tulip
shell horizon
#

@tough tulip That's exactly what I was looking for, thank you. And yeah I know it's intended I'm just a little annoyed that scene loading forces you to wait a frame

tough tulip
shell horizon
#

@tough tulip actually you wouldn't happen to know where in the script execution order the scene is loaded would you? I can't seem to find the answer anywhere

small badge
#

The scene is loaded in the background, it can take several frames. I don't know whether there are any guarantees about when calls like Start/Awake happen?

shell horizon
#

I'm not using the async load, so it finishes in one frame

#

I just need to know when that actually happens

untold moth
shell horizon
#

you'd think, but nope

untold moth
#

wdym?

shell horizon
#

this code throws an error
SceneManager.LoadScene(2, LoadSceneMode.Additive); yield return null; SceneManager.SetActiveScene(SceneManager.GetSceneAt(2));

#

that the scene isn't loaded

small badge
#

The "synchronous" load is rather misnamed, yeah; it just means "asynchronous, but guaranteed to take at most one frame".

shell horizon
#

ahh, that makes much more sense

small badge
#

My assumption is that LoadScene() would call Awake() and Start() after the previous frame's EndOfFrame, but before the first (fixed)update calls in the new frame. I don't know if that's guaranteed, though.

#

(I guess I should say "current" rather than "previous".)

tough tulip
#

LoadScene starts with Awake on all active gameobjects in the scene

#

It should most likely be initialized somewhere between Update and LateUpdate

#

No guarantees though, haven't tested myself

untold moth
shell horizon
#

I wish it was a simple error like that, but no, that code loads the main scene and unloads the menu scene, while keeping the preload scene loaded

#

it works as intended, just the execution order really screws things up

untold moth
small badge
#

Would it be the end of the world to just wait another frame? I don't know that I would want to rely on anything that's trying to rush more than that.

shell horizon
#

The problem is I need to pass information to the new scenes scripts before their start functions run

#

So it needs to be precise

untold moth
#

Just initialize the scripts in Awake

tough tulip
small badge
#

I very much doubt you can guarantee a window between creating an enabled object and Start() being run; you can't even do that when calling Instantiate().

#

If you need to execute code on a new object before Start is called you usually need to create it inactive/disabled, then activate/enable it after you've done your setup.

shell horizon
untold moth
#

You can always wait until everything is initialized, then override with the loaded data.

tough tulip
# shell horizon Yeah, you're probably right. I'm working on a save/load system for a project tha...

you can go with tjm's approach, although you'd need to enable objects manually. but the problem is still there of previous scene being unloaded, you probably would lose previous data.
There are still few alternatives:
I) make current scene as ddol, load new scene, pass data, then destroy unwanted gameobjects and do Resources.UnloadUnusedAssets once
ii) load new scene as additive, pass data, unload old scene. although additive loading can lead to some weird behaviour with camera and audiolistener, so be cautious of it

shell horizon
tough tulip
#

The reason why it waits for a frame is because how synchronous code works. When a new scene loads, all previous gameobjects would be destroyed. If that happens, it would be a mess in Unity's internal gameobject callbacks like other Update/LateUpdate, and Destroy wouldn't be called.
Hence everything happens at end of frame, and this the 1 frame delay

#

For actual synchronous load, I don't know how AssetBundle.Load would work for this case, but you can also try Resources.Load which would work like Additive loading, and after load, just destroy unwanted gameobjects.
Destroy is anyway at end of frame

#

But yes don't go with these approaches. It's a way for absolute synchronous load, not your solution you re looking for

humble leaf
#

@oblique narwhal Stop crossposting.

worthy lodge
#

Is there a way to change materials or textures in the pre-build process?
I want to include different materials in an android version of my game, but am looking for a way to change them without changing them in runtime, which takes a lot of time

flint sage
#

Just write a script that changes it and then triggers the build

worthy lodge
flint sage
#

Well, change it back after the build is done?

untold moth
#

Afaik there are pre and post build callbacks that you can hook your code to.

worthy lodge
#

Ah yeah, forgot post was a thing

#

Thanks!

mint sleet
#

Hey, I got this issue after making a HTTP response.
I am able to get "response" but when I click on this it produces this exceptions:

ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length

GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced.

#

Do you have any idea?

#

and I can not click on Debug.Log messages, if I do it does not open.

flint sage
#

That's a bug in Unity

#

Looking at the stacktrace it tries to create a hyperlink but somehow fails

mint sleet
#

how am I going to handle this?

#

I need those values in fact ๐Ÿ™‚

#

@flint sage

flint sage
#

No idea

#

Look at the editor log instead

#

Sanitize your log somehow so that it doesn't crash the console

#

Update unity to aversion where that's fixed

frail dock
#

I have an issue where i'm generating a mesh and drawing a texture on it, but when i try to reapply to same uv to it it comes out twisted, anyone have a clue why?

#

this is my code:

#
    public List<Vector3> newVertices = new List<Vector3>();
    public List<int> newTriangles = new List<int>();
    public List<Vector2> newUV = new List<Vector2>();
    private Mesh mesh;
    
    private float tUnit = 0.0625f;
    private Vector2 tOne = new Vector2 (0, 8);


    void Start () {
  
        mesh = GetComponent<MeshFilter> ().mesh;
  
        float x = transform.position.x;
        float y = transform.position.y;
        float z = transform.position.z;
  
        newVertices.Add( new Vector3 (x  , y  , z ));
        newVertices.Add( new Vector3 (x + 1 , y  , z ));
        newVertices.Add( new Vector3 (x + 1 , y-1 , z ));
        newVertices.Add( new Vector3 (x  , y-1 , z ));
  
        newTriangles.Add(0);
        newTriangles.Add(1);
        newTriangles.Add(3);
        newTriangles.Add(1);
        newTriangles.Add(2);
        newTriangles.Add(3);
  
        newUV.Add(new Vector2 (tUnit * tOne.x, tUnit * tOne.y + tUnit));
        newUV.Add(new Vector2 (tUnit * tOne.x + tUnit, tUnit * tOne.y + tUnit));
        newUV.Add(new Vector2 (tUnit * tOne.x + tUnit, tUnit * tOne.y));
        newUV.Add(new Vector2 (tUnit * tOne.x, tUnit * tOne.y));
  
        mesh.Clear ();
        mesh.vertices = newVertices.ToArray();
        mesh.triangles = newTriangles.ToArray();
        mesh.SetUVs(0, newUV.ToArray());
        mesh.Optimize ();
        mesh.RecalculateNormals ();
        
        // makes it all twisted
        mesh.SetUVs(0, newUV.ToArray());
    }
#

first one is without the last line

#

second as you can see is cut and twisted for some reason

flint sage
#

Remove optimize and try again

frail dock
flint sage
#

Chances are optimize reorders your mesh

frail dock
#

ohh

#

what would be the disadvantage of leaving it out permanently?

flint sage
#

In this case, probably not much

frail dock
#

what if my mesh had like 80k triangles?

flint sage
#

This function causes the geometry and vertices of the mesh to be reordered internally in an attempt to improve vertex cache utilisation on the graphics hardware and thus rendering performance. This operation can take a few seconds or more for complex meshes and should only be used where the ordering of the geometry and vertices is not significant as both will change.

frail dock
#

hmm okay ty

misty crescent
#

Anyone here used Unity as a Library? How can I run Application.Quit() WITHOUT exiting my parent app? Anyone from Unity know the answer to this?

misty crescent
#

@drifting galleon from our React Native app or from within Unity?

#

Also isn't this whole problem because React Native is single threaded? Like because Unity runs on the same main thread or something?

drifting galleon
misty crescent
drifting galleon
#

haven't worked with that. so you probably need to dig a bit yourself

misty crescent
#

Is there any way I can interact with someone from Unity regarding this?

drifting galleon
#

unlikely

#

especially since the repo you're using is not made by unity

misty crescent
#

@drifting galleon I've gone through the repo's code, the guy is running Unity on the UI thread, which incidentally react native also uses

#

So my question actually becomes: can I run it on a separate thread or does it have to run on the main thread? That's something any Unity dev who's built this can answer

drifting galleon
#

sorry. but i have no idea

misty glade
#

UnityEngine.EventSystems.IPointerDownHandler doesn't seem to work well if the application isn't focused when the pointer down is executed. Anyone have any ideas/tips on how I can make that work better? Or is that just life

#

It basically doesn't capture the pointer down event until the application is focused/topmost for 0.5sec or more.. which is fine I suppose? but a little clunky feeling

misty crescent
regal olive
#

Say I wanted to create an in-editor modeling tool ala ProBuilder. How could I go about storing the mesh data inside the scene itself (or rather a component instance)?

sly grove
#

Then it'll be stored in the scene just like any other monobehavior data

#

That's pretty much how ProBuilderMeshFilter works

thin merlin
#

Looking for a way to change the layer-based collisions via code (the thing in the image)

thin merlin
#

I just found that before you sent it XD

thorny lintel
#

Hello, i need to set transform.position of StarSystemPrefab i Instantiate to new with offset of size of sizeOfSector. So they will have Boxcolliders next to each other and not inside each other.

public class Universe : MonoBehaviour
{
    public Vector3 universeSize;
    public Vector3 sizeOfSector;

    private Vector3 transformPos;
    
    [Space]
    public GameObject UniverseRoot;
    [Space]
    public GameObject StarSystemPrefab;


    private void Start()
    {
        GenerateStarSystems();
    }

    private void GenerateStarSystems()
    {
        for (int x = 0; x < universeSize.x; x++)
        {
            for (int y = 0; y < universeSize.y; y++)
            {
                for (int z = 0; z < universeSize.z; z++)
                {
                    GenerateSystem(new Vector3(x, y, z));
                }
            }
        }
    }

    private void GenerateSystem(Vector3 location)
    {
        GameObject system = Instantiate(StarSystemPrefab, location, Quaternion.identity, UniverseRoot.transform);
        system.GetComponent<StarSystem>().SetSizeOfBoxCollider(sizeOfSector);
        system.name = String.Concat($"Star System: (x:{location.x}, y:{location.y}, z:{location.z})");
    }
}
stable spear
#

oh, and float instead of int

ripe bloom
#

Yoooooo anybody have any experience integrating Google crashlytics into their unity app?

thorny lintel
stable spear
#

did you end up with an infinite loop?

#

if you mistyped something

thorny lintel
#

lol

#

i see it

#

iam dumb

stable spear
#

y += and z +=

#

yea

thorny lintel
#

shame on me

#

thx for help, but i think still need to solve how many i wanan spawn

#

best solution is to spawn 0 0 0 chunk in middle and around it a chunks

#

but i dk

stable spear
#

that loop will spawn a cube with (universeSize.x / sizeOfSector.x) objects in the x direction, etc

thin merlin
#

Physics2D.IgnoreLayerCollision(LayerMask.GetMask("Player"), GameManager.groundLayers[1]);
in GameManager.cs:

  groundLayers = new LayerMask[] { LayerMask.GetMask("Collision"), LayerMask.GetMask("JumpThruPlat") }; // can confirm that both layers are being recognized in the inspector
}```
Result from top code:
#

What gives? Why is it saying I'm entering "layer1"?

stable spear
sly grove
#

LayerFromName

thin merlin
#

LayerFromName or LayerToName?

sly grove
#

Fromname

thin merlin
#

doesn't seem to recognize it ...

sly grove
#

Look it up in the docs

#

I'm on my phone

stable spear
#

NameToLayer

sly grove
#

Yeah that

stable spear
#

and change the type of the array to an int[]

thin merlin
#

but the array is supposed to hold layers, isn't it?

stable spear
#

layer indices are int, layer masks are LayerMask

#

a mask is a set of layers

sly grove
#

I'm not sure that array is useful at all but my suggestion is for the IgnoreLayerCollision piece

thin merlin
#

oh wait, if it's a set of layers

#

LayerMask.NameToLayer("Collision", "JumpThruPlat") would work?

stable spear
#

IgnoreLayerCollision only allows you to specify two layer ids

#

no

#

NameToLayer returns the index of a SINGLE layer

#

GetMask() will let you use multiple layers

#

LayerMask.GetMask("Collision", "JumpThruPlat") is valid

#

but it returns a LayerMask

thorny lintel
stable spear
#

that's not what you want for IgnoreLayerCollision

thin merlin
#

so I need to use both GetMask for standard collisions (my purposes since switching to NameToLayer in general broke things) and NameToLayer for the Ignore. Got it.

stable spear
thorny lintel
thin merlin
#

so, I think I have the IgnoreLayerCollisions written properly ... private IEnumerator FallThroughPlatform() { Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("JumpThruPlat")); transform.position = new Vector2(transform.position.x, transform.position.y-0.5f); print("Platforms disabled"); fallThroughPlat = true; int timer = 0; while (fallThroughPlat) { if (!GameManager.gamePaused) { timer++; } if(timer >= 60) { fallThroughPlat = false; } yield return new WaitForEndOfFrame(); } Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("JumpThruPlat"), false); print("Platforms enabled"); }

#

but when I try to run it

#

the platform:

#

the player:

sly grove
#

Depending on framerate that's very short

thin merlin
#

60FPS

sly grove
#

Should probably be waiting a specific amount of time instead of frames

thin merlin
#

here's the thing: according to the print statements, it's not even causing the collision to be ignored at all

sly grove
#

That whole while loop can be replaced with a single WaitForSeconds

thin merlin
#

noted, but the problem right now is that I don't think it's actually trigger the collisions to be ignored

sly grove
#

Also when and where are you starting this coroutine?

vapid mauve
#

going by the console output, the delay should be long enough for it to fall through

thin merlin
#

in the playercontroller's update I have this:

#

if down is being held and the jump button is pressed, it works. The fallThroughPlat is a class level varaible used by the coroutine.

sly grove
#

I can't read the console in that video ATM on mobile sorry ๐Ÿ˜

vapid mauve
#

Ah ^^

sly grove
#

BTW unity has a built-in well trodden way of doing this effect with a PlatformEffector2D

#

There's some good tutorials about it floating around

thin merlin
#

I have jumping up through the platform figured out, what I'm trying to do is make the player fall through on command, like in Castlevania or any other game where you can drop through platforms with an input.

vapid mauve
sly grove
#

It honestly just looks like you're re enabling the collision way too fast

thin merlin
#

the print statement shows that's not the case though

#

it comes out a full second after

#

and the player object is grounded on the platform way before it comes out

sly grove
#

Or the platform

#

And if so do any of those children have colliders?

#

And if so what layer are those colliders on

#

Child objects may have different layers from their parents

thin merlin
#

the player has children, and one of them has a collider on another layer. I could disable that ... but there are situations where it will need to collide with that layer.

#

essentially, the game gives the player the ability to rotate the entire level, and when the platform is sideways it becomes effectively a wall on both sides

sly grove
thin merlin
#

that's not the issue

#

just noticed, could this have something to do with it?

#

the platform effector itself?

sly grove
#

I didn't think you were using a platform effector

thin merlin
#

platformEffector.colliderMask = //what do I put here, then?

#

I think this is precisely what I need to make this work.

sly grove
#

A layermask

thin merlin
#

took some workarounds and trying different things but I've managed to implement the fallthru mechanic rather cleanly after learning about manipulating the collider mask. That was the missing piece!

ocean cedar
thorny lintel
# stable spear huh?

As next ste i tried to fill that cube with smaller cubes ๐Ÿ˜„. But i cant Divide Vector3 Size of BigCube / Vector3 SizeOfSmall cube

thorny lintel
#

How i find size and number of cubes i need to fill a Cube i know its size? ๐Ÿ™‚

thorny lintel
#

I know size of BigCube(Vector3)

mighty latch
#

Well, let's say your big cube is 5x5x5 and your small ones are 2x2x2, you could put 8 of them inside

#

Mathf.FloorToInt(bigCubeSize / smallCubeSize);

thorny lintel
mighty latch
#

You can do it the other way around if you want a certain amount of cubes inside

#

But you must either know the size of the small cube, or the number of cubes you want to be inside

thorny lintel
mighty latch
#

wdym?

thorny lintel
#

Like what is greatest number to / number 100 so i get int and not float

compact ingot
mighty latch
#

That doesn't answer my question: what information are you supplying here? You already know the size of your big cube, but do you know which size you want your small cubes to be? Or do you know how many of them you'd want to fit inside?

thorny lintel
#

All i know is sice of Big Cube. I wanna avoid to set manualy number of cubes.

mighty latch
#

I'm assuming that you also want your small cubes to be of int size?

thorny lintel
#

It is to create Sectors in StarSystem

mighty latch
#

Well, the smallest size will always be one

long ivy
#

then the problem is simple, isn't it? small cubes should be the smallest int size possible, and therefore you can fit min(big.x, big.y, big.z) ^ 3 small cubes inside

mighty latch
#

If it's a cube, you can simply cube one of its dimensions

compact ingot
#

in gameplay terms

mighty latch
#

The smallest will always be one because it is the smallest positive integer (not accounting for 0's bullshit) and any number's greatest divider is itself

thorny lintel
#

Iam generating one big StarSystem Cube (Box Collider)

#

Thats is that big cube

#

now i need it filled by small cubes (sectors) so i can make custom cords system and LOD and Spawn and so on

#

Basicaly Cubic Chunks with smaller chunks inside

compact ingot
#

alright, but where is the problem?

#

do you want to know good sizes for the sectors so they perfectly fill the big cube?

thorny lintel
#

yes

#

cause i can make StarSystem bigger and bigger

compact ingot
#

any number ^3 works

thorny lintel
#

so sectors can grow too

#

power of 3?

compact ingot
#

yes

thorny lintel
#

next. harder thing is to generate them in right Vector3 ๐Ÿ˜„

#

Like this code up can palce sectors nicely next to each other

#

place*

compact ingot
#

1, 8, 27, 64, 125, 216, 343, 512

thorny lintel
#

i tried, and i got crash ๐Ÿ˜„

compact ingot
#

i really don't understand your problem, you are asking in advanced code but this seems extremely trivial

thorny lintel
#

sorry, i thought it will be complicated

misty glade
#

also why are you += size, instead of 1

compact ingot
#

number of sectors in your code can be any number

#

but the code itself makes no sense

thorny lintel
#

yeah it is code that fillup memory and crash

#

iam waiting to crash it so i can fix it

#

sizeOfSector = new Vector3(sizeOfSystem.x, sizeOfSystem.y, sizeOfSystem.z) / numberOfSectors;

misty glade
#

like, if you have numberOfSectors=10 but sizeOfSector you're.. uhm.. using two different "things"... do you want 10 by 10 by 10 or do you want "as many cubes fit"

thorny lintel
#

i think best is to be 10 10 10 and set size acording to it? or?

misty glade
#

and obviously you're sure your Vector3 has x, y, z > 0?

#

probably? I don't really understand your code, but if you want that, then you just:

#
for (int x = 0; x <= numberOfSectors; x++)
  for (int y = 0; y <= numberOfSectors; y++)
    for (int z = 0; z <= numberOfSectors; z++)
#

not that wonky "size" and "number" (and also floats as your for loop counters is . odd)

thorny lintel
misty glade
#

when you need to GenerateSector then figure out your location and cast it to float based on x, y and z which are indexes - ie, float xloc = (float)x * sizeOfSector;

thorny lintel
#
    private void Start()
    {
        GenerateStarSystems();
    }

    private void GenerateStarSystems()
    {
        for (float x = 0; x < universeSize.x; x += sizeOfSector.x)
        {
            for (float y = 0; y < universeSize.y; y += sizeOfSector.y)
            {
                for (float z = 0; z < universeSize.z; z += sizeOfSector.z)
                {
                    GenerateSystem(new Vector3(x, y, z));
                }
            }
        }
    }

    private void GenerateSystem(Vector3 location)
    {
        GameObject system = Instantiate(StarSystemPrefab, location, Quaternion.identity, UniverseRoot.transform);
        system.GetComponent<StarSystem>().SetSizeOfBoxCollider(sizeOfSector);
        system.GetComponent<StarSystem>().GenerateSectors();
        system.name = String.Concat($"Star System: (x:{location.x - sizeOfSector.x}, y:{location.y - sizeOfSector.y}, z:{location.z - sizeOfSector.z})");

    }
#

this will make as many System i set i wanna

#

later i make it so center is in middle

misty glade
#

your for loops are fragile and will break for a variety of reasons, the obvious one i see is that sizeOfSector with 0f components will stackoverflow

thorny lintel
#

is there better way than loops?

misty glade
#

are you intending that all the sectors are just adjacent like that? ie, densely populated?

thorny lintel
#

It should work as boudaries to load data from game/server

#

when u pass to other box

misty glade
#

i mean functionally your code works but .. depending on the universeSize and sizeOfSector you're going to be instantiating a lottttttttt of shit, and i don't know what is in GenerateSectors()

#

also you don't need String.Concat, you're already using string interpolation

thorny lintel
#

oh, okey, thanks for tip

misty glade
#

So, I mean, this is a little advanced but your code indicates that you still need to learn some basics (so these questions might be better suited for beginner/general), but a better approach if that's the case might be to only load sectors adjacent to the player (and unload them if you don't need them) instead of literally loading the universe

thorny lintel
#

I tried some numbers.

misty glade
#

you're trying to make a 64x64x64 grid?

thorny lintel
#

yeah for start 64

misty glade
#

ok so it's a question of scale

#

64^3 is a big number and it's likely you don't need anywhere close to that number of items

#

262,144 sectors

#

your player is maybe going to what, interact with a handful of them?

thorny lintel
#

Starmade, Game coded in Java

#

has this map and chunks system.

#

basicaly u dont load stuff outside of that big cube i think

misty glade
#

ok..?

#

just saying if you're trying to instantiate 260,000 items you're gonna have a tough time

#

even if the items don't have anything in them

#

Unity staples a lot of functionality to those items, so even if they don't do much or anything, unity is going to check in on every single one of them every Tick, meaning.. your game won't run

thorny lintel
#

There is no way to skip a Systems that are without players?

#

Unloaded Chunks?

#

Thx for help ๐Ÿ™‚ yeah iam begginer ๐Ÿ™‚

#

Just noticed that StarSystem should be 0 0 0 ๐Ÿ˜„

#

Btw if you hear a explosion in Prague, u know why

#

Nope. u f*** up ๐Ÿ˜„

misty glade
#

hm?

mighty latch
#

The thing is that these guys are probably pros that found way to greatly increase performance with some workarounds

#

Like loading and unloading chunks dynamically

young spoke
#

I am using a spline with only two points. Everything works but I am looking for a way to attach the player to the spline halfway through the spline instead of at one of the two ends

compact ingot
sly grove
young spoke
#

so would I have to use a spline editor tool? I am currently just using one through code

compact ingot
#

no

#

but you can use one of the methods in the spline library you are using to find a position on the spline

young spoke
#

ok

compact ingot
#

each library has one, its kinda what they are all about

young spoke
#

ill take a look at that, thank you

young spoke
compact ingot
#

the core implementation of the concept of a "spline" requires you to write an interpolation function. just use that to find your position.

#

where do you get that spline from? did you write it yourself?

young spoke
#

no

#

code monkey video

#

heres my code

compact ingot
#

that is not a spline

young spoke
#

how so?

compact ingot
#

that is just linear interpolation

young spoke
#

ok

compact ingot
#

when you say "spline", people usually expect something like this:

young spoke
#

well thats what I meant when I said 2 points

#

sorry for the confusion

compact ingot
#

my first answer is all you need

young spoke
#

oh ok, tysm

#

have a good day :)

primal flame
#

I wonder if there is something like baked animation and Ik animation blending for humanoid? Like for example ringing the door bell - every time it's same animation reaching out for door bell, but the position you stand can vary, so can the end position for hand. But.. still it is the same animation with some xyz correction. Any help appreciated.

livid kraken
primal flame
livid kraken
#

There is one such package in the package manager

#

Made by unity juat get the latest version

primal flame
#

Ahh ok

#

@livid kraken can you give additional tips?

#

Its a lot to swallow

livid kraken
#

Well Im pretty sure there are official tutorials that cover exactly what you need. It can be overwhelming but the package is very powerfull. What you need is to set up a two bine ik on the arm and then set the target to what ever you want from code

primal flame
#

doc says "correcting animation" - that is what I need. But can't find anything on the topic later in doc

reef bloom
#

How can I send multiple UnityWebRequest (around 40-50) without making the game not responding?
I can't use yield wait because it is very slow for 40 calls I want to load all async.

long ivy
#

launch all of them, and then yield until all are done

reef bloom
long ivy
#

are you storing the AsyncOperation, or are you yielding the AsyncOperation directly? if the latter, you're waiting for one to complete before going to the next

reef bloom
#
        {
            request = UnityWebRequest.Get(tokenAddress + x);

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError(request.error);
                yield break;
            }```

This is the current code currently it sends 1 by 1 
I tried sending it without the yield return and it made it crash.
long ivy
#

launch them first, then start waiting

#
var requests = tokens.Select(x => UnityWebRequest.Get(tokenAddress + x)).ToList();
var waiting = requests.Select(request => request.SendWebRequest()).ToList();

foreach (var wait in waiting) {
    yield return wait;

    // error checking here
}
primal flame
#

So I cant find anything about correcting baked animations with IK. Just taking full control

long ivy
#

that's untested code btw, but you get the idea

reef bloom
pulsar isle
#

I want to search for a specific frame(let's say frame number 15) in a video, pause there, extract video frame into a Texture2D. Then seek another numbered frame and do the same etc. What would the process look from a high level perspective. I'm close but for some reason instead of getting the frame I seeked I get the previous I seeked. Like I seek to frame 15, pause there, extract the frame to Texture and I get something irrelevant like the frame 0, then I seek frame 15, pause there and now the correct frame is extracted.

slate stone
#

Why is it when you pass an index in a button.onclick.addlistener, it only calls the last index of the array or list?.

modest lintel
#

because the captured index is probably being modified in the loop

small badge
# pulsar isle I want to search for a specific frame(let's say frame number 15) in a video, pau...

Depends entirely on the video player. Most players are designed first and foremost for streaming video to the user's screen in 1:1 time as efficiently as possible, so other operations - like seeking to exact frames, getting video data for specific times, etcetera - often aren't implemented rigorously. For example, when you seek to frame 15 and play, it might not start decoding video until it plays to the next keyframe on or after frame 15.
Whereas other players might be more rigorous, and would seek to the last keyframe before frame 15 and silently play forwards to it before reporting the seek as complete.

modest lintel
#

copy it, and then set it

pulsar isle
#

I'm using the Unity Video player , in API mode. https://pastebin.com/jMtdwnrE This is the basic thing I want to do in code. With the results I described. I know it depends on the frameReady events the Unity Video player provides so I'm missing something probably. I have managed to extract all the video frames in a Texture2D List for example that gets frame, pauses, extracts it and plays again but it seems that when you actually want to SEEK a frame the process gets different.

small badge
#

Yeah, my experience with the Unity Video Player is that it can't do that sort of thing. Forward play at roughly normal (or slower) speeds, with occasional asynchronous seeks, is the only behaviour I could get it to do consistently. You could try an alternative video player like AVPro Video from the asset store, but those tend to be very expensive for anything other than trial versions.

pulsar isle
#

Oh...really ? Why is that the case, I mean from an internal perspective. I'm not that experienced so if you have any ideas please share them as they will help me to become better. Just to clarify again(because I tend to not explain things properly when I'm blocked), the challenge I want to tackle is: having the ability to seek to whatever frame I please in a video and extract it to a Texture2D. Unfortunately, paid solutions are off for me :(.

small badge
#

Naturally I don't know the internals, so all I can do is speculate... and I can't really add anything to the speculation I posted above. For example, if you assume the video has keyframes every 10 frames, if you tell it to seek to frame 15 and play it probably won't start decoding frames until it gets to frame 20 (because the alternative would be to seek to frame 10 and decode frames 10-15 all at once, which it doesn't want to do because it could cause a stall when playing the video real-time).

#

That's certainly not the only possible reason, though; just one of many.

pulsar isle
#

Interesting.

#

So I'm a bit cornered it seems. Sigh.

#

Your input was quite valuable and I enjoyed the back n forth. Will research further.

#

The idea of creating a buffer of the first 20 frames extracted into Texture2D List, use them, clean them and redo the process MIGHT also solve my problem in a way.

#

Also I experimented with just extracting the current video frame(whichever that is) and using it on my models but that seems to affect the performance even compared to extracting and saving all frames in a list on Start() (for example).

primal ivy
#

what does "Unity.Services.Lobbies.LobbyServiceException: HTTP/1.1 401 Unauthorized" mean? using Unity's multiplayer lobby system.

onyx blade
primal ivy
#

not sure if this is a programming question anymore :p

onyx blade
#

it probably isnt programming related. I havent used that multiplayer system. I just know what a 401 is xD

primal ivy
onyx blade
#

there are other frameworks you can use if its urgent

primal ivy
proven blaze
#

Can somebody help? How to remove OpenGL validation at runtime? Oculus does it inside their .so file - how can we do it in Unity?

wind pine
#

I'm working with a 3rd person CinemachineFreeLook camera, and I want to clamp the rotation around the playerCharacter in one of the player states. I'm new to using Cinemachine, so does anyone know what I can do or even referance?

#

Any Documentation I've seen on it doesn't seem helpful in scripting it.

amber kite
#

Is it possible to set properties for a material owned by an Image or CanvasRenderer component in script, similar to how it can be done for materials attached to meshrenderers?

fresh salmon
bleak geyser
#

What's the difference between a normal (unlit) shader and a compute shader~~, except that a compute shader runs on the GPU~~?

#

And when to use a compute shader, and when to use a (unlit) shader?

cursive horizon
#

both run on the gpu

gray pulsar
bleak geyser
#

So in normal shaders there cannot be any logic, just properties with values?

gray pulsar
#

they have logic

#

they just don't return any data back to the CPU

#

(I believe, I'm not an expert)

cursive horizon
# bleak geyser So in normal shaders there cannot be any logic, just properties with values?

(I am also not an expert, here's my best explanation)
A shader is just a program that runs on the GPU. Normally, you feed data into it and it renders stuff to the screen. Some of this data is passed in by Unity for stuff like lighting (but not if it's an unlit shader, for example!). That's the 'standard' way of using them. You can't really 'read' from them (and mostly wouldn't want to).

A compute shader is written the same way, but is intended to take data in, process it, and save it to a buffer where you can read it back. It doesn't render anything and it doesn't need access to stuff like lighting, because it's only working on the data you pass in. In this case, you are using the GPU more like a CPU rather than for rendering.

vapid mauve
#

In addition (and maybe obviously) when normal shaders run is pretty specified (e.g. a vertex shader running once per vertex per frame). While compute shaders are triggered manually and you tell it a bit more about how you want threads for that shader to be arranged

bleak geyser
cursive horizon
bleak geyser
#

Oh! I haven't seen that channel yet, thanks

compact ingot
#

Is there a way to generate fast loading textures from jpg/png at runtimeโ€ฆ tried loading a compressed DXT array directly. Makes almost no difference, getting around 450 ms for 4K.

steady tartan
#

Im confused... What am i missing?

sly grove
frozen imp
steady tartan
#

Oh. My. God.

#

Cringe

fervent sage
#

How to trigger the OnSelect on a class inherriting Selectable?

  • I have a button with down navigation set to be my Selectable, but when I press down arrow from it it does not trigger the OnSelect function. Am I missing something?
sly grove
#

to the Selected Color?

fervent sage
sly grove
#

can you share some screenshots?

fervent sage
sly grove
#

If you have a Color Tint transition, the graphic is the thing that will be tinted that color

fervent sage
sly grove
#

any graphic you want

fervent sage
#

it would only be for the selectable functionality

#

Yes as you see in the screenshot I have it but it still does not work

sly grove
#

show the inspector for the Login object?

fervent sage
sly grove
#

my bad didn't notice there were two

fervent sage
#

I am trying to "navigate" to it by going from the password input field, I know that works because I can navigate to that one from the username input field

sly grove
#

yeah makes sense...

#

Are you sure you ever actually have Password selected?

#

I guess it's an input field so you probably are ๐Ÿค”

fervent sage
#

I can go back to the username

sly grove
#

I notice your ZoomHoverNavigation script is disabled

fervent sage
#

so I know that works

sly grove
#

is that intentional?

fervent sage
#

maybe thats it no idea how that happened

fervent sage
sly grove
#

cool

#

ok good I was beginning to question my own understanding there

chrome osprey
#

Hey guys, I'm trying to call java code from Unity.

I made a project in android studio, made and built a module, and then copied the .aar file into Assets>Plugins>Android

#

I then tried to build, but am seeing this error

#

Any idea what I could be missing/doing wrong here

fringe latch
#

Hi, I'm currently trying to create a game within Unity.

I'm confused on why I'm getting this error. Can anyone explain?

Thanks in advance.

chrome osprey
#

Is it a serialized field?

fringe latch
fringe latch
chrome osprey
#

mm

#

newShip.GetComponent<ShipBehaviour>() may be returning null

#

best way to check is to debug your code and find out what's null

fringe latch
#

ok

#

I'll try that

chrome osprey
#

gl

sly grove
fringe latch
#

okay, thanks

misty glade
#

I'm designing my entities for my idle / battle multiplayer game and not sure if my design is good. Tentatively I'm going to make:

  • PlayerClient : MonoBehaviour
  • PlayerSerializeable
  • PlayerBattle

Serializeable will be the POCO that's saved to the database and passed to the client on login. It'll be fully serializeable (as a document into the Cosmos DB and as a byte stream for network).

Client will be instantiated a singleton owned by the client and synthesized populated from the Serializeable. Save() calls will create & populate a Serializeable and send it to the server (where it will be checked for cheating, validated, and saved to the database).

Battle will be instantiated by the server & client at the start of a battle - it as a bunch of members that aren't needed permanently (like "current energy" and "current ability cooldown").

Thoughts?

#

I also worry that PlayerSerializeable will get kind of big over time .. and so passing it back/forth to the client/server might be expensive or bloaty - but on the flip side if I do lots of small messages to update/save state of only specific members, then I will have a fair bit of state-desync-bugs..

gritty lagoon
drifting galleon
gritty lagoon
#

yea but how do i know the version

drifting galleon
#

if you use 2021 you can just add it by name in the package manager. if you use 2020 just try 1.0.0 and then update it through the package manager if it works

gritty lagoon
#

i'm using 2020

#

but it's a preview package so 1.0.0 wouldnt work

drifting galleon
real kestrel
#
 death target = hit.transform.GetComponent<death>();
                if(target != null)
#

I have a stair asset that shows up in the inspector but it wont destory when i shoot it?

#

Im new and was just tryimng to ask some on advanced sorry

real kestrel
#

i did but they said to ask here they didnt know

compact ingot
#

people here also check beginner code

#

just because one person says they don't know, doesn't mean others won't either

real kestrel
#

could you help though cause nobody else helped either

compact ingot
#

only if you provide all the info to actually make the question answerable, this is probably the reason why nobody has helped you yet

real kestrel
#

what else do i need to provide?

untold moth
misty glade
#

Anyone know why I have to manually import some DLLs for c# namespaces that .. should be included..?

Per https://forum.unity.com/threads/system-configuration-issue.470166/ I can't just import System.Configuration.ConfigurationManager, I need to manually bring the DLL to the plugins folder, and this feels smelly to me? (Yes, I'm aware there are other ways to handle client side configuration - especially ones that unity provides.. was just curious about why this works this way)

mellow mesa
#

Hello guys, I'm using unity localization 1.0.5. In the unity editor I see a selection of languages โ€‹โ€‹but I wanted to do it for the unity UI element - dropdown, but I don't know how, can you help me with that?

drifting galleon
near escarp
#

so the console says the importer object I've created is null even though I create a new instance of it. I wanted to try and use the ModelImporter to reduce keyframes in an animation clip and compress the clip. but is it not possible to create a ModelImporter this way or is there a different way I need to do it? or is it even possible to do in the first place?

untold moth
near escarp
untold moth
near escarp
#

the issue is that I'm able to create a clone of an animation clip through code but even though I'm reducing the number of keyframes manually the file size still ends up being larger than the original clip. one clip went from 250 kb to 0.8 mb or something. but in the inspector it mentions Dense and Stream which I understand to be two compression methods. but I can't seem to find a way to access them and use them to compress my animation clip

near escarp
#

because it's not a clip in a fbx model. it's a single stand alone animation clip. I was hoping I could use the ModelImporter to somehow inject my animation clip into it and use the compression feature but that doesn't seem to be a viable option

untold moth
#

Yeah, I don't think that's possible. You could probably try to remove some keyframes manually though.

oblique spoke
#

how do i make realistic speech synthesis

mortal glen
#

can i design a timeline with a "default" model using a animator/mecanim controller and switch this default model per runtime?

near escarp
untold moth
small badge
near escarp
small badge
mortal glen
small badge
regal olive
#

So I want to make my Unity game moddable, and I know how to import dlls and other stuff. But I 'm still lacking an decent amount of knowledge about using them properly. My question is, how to call a function I have in the Unity project via a newly created C# project? I know that I have to import a moddingAPI.dll for the game into the C# project, but I don't really know what I have to do. Let me explain:

Let's say, I have this function in my Unity game, It's not the moddingAPI.dll:

public class exampleClass : MonoBehaviour{
  
  public static void exampleFunction(){
    //Do various stuff in here, like getting important Camera references or something like that.
  }
}

How do I call this function with a moddingAPI.dll? Do I have to import my moddingAPI.dll in my Unity Game?

small badge
thorny gulch
#

Hi all. any idea how can i stream my game view into Facebook(or other platform) directly from Unity.

near escarp
# small badge Just to check: When you say "file size" you don't mean the size of the file in t...

I do mean file size as in the physical size of the clip on the disk. this is the size I'm interested it and the size I wish to reduce. more specifically it's for uploading the clip to another platform where size is limited so I need the physical size of the animation clip to be as small as possible which is why I'm attempting to use keyframe reduction and compression. there is no fbx. I only tried to use the ModelImporter to simulate a fbx to hopefully use it as a tool to reduce the file size of a standalone animation clip

mortal glen
steady tartan
#

Isnt there syntax sugar for this?

    private List<UserInputReceiver> userInputReceivers = new List<UserInputReceiver>();

    public delegate void UserInputReceiver(UserInput input);

    ...

    [ServerRpc]
    private void SendPlayerInputServerRpc(UserInput userInput)
    {
        foreach (var userInputReceiver in userInputReceivers) // For this
        {
            userInputReceiver(userInput);
        }
    }
crimson umbra
#

As in a concise replacement for the basic foreach?
Linq has .Select (for IEnumerable arrays or lists), which should let you do that

small badge
steady tartan
#

I think i prefer this lambda:

    private void SendPlayerInputServerRpc(UserInput userInput)
    {
        userInputReceivers.ForEach(receiver => receiver(userInput));
    }
mortal glen
small badge
crimson umbra
#

Notably, ForEach returns void, while Select is supposed to return whatever your function (which is usually a lambda) spits out
*And Select uses deferred execution, so it's not what you want to use if you're using - ninja'd - side effects

small badge
#

As, so there is.
Using Enumerable.Select for things with side effects is a little awkward, because Select doesn't make any inherent guarantees about how many times it will evaluate the function - or even whether it will evaluate it at all. In practice myEnumerable.Select((a) => return MyFunction(a)).ToList() will probably run MyFunction exactly once for each element in the enumeration, but it's not guaranteed.

#

(I assume that's why ForEach is only in List, not the Linq extensions; it would be odd for that one method in the Linq extensions to have significantly different side effect guarantees from all the others.)

crimson umbra
#

This is my first time seeing the Action type, anyhow
... which is just a built-in generic delegate type, I see

olive totem
#

@steady tartan not sure why you're not just declaring an event and let methods subscribe to it, then you can invoke all functions with a single line of code

#

Delegates and events go hand in hand

small badge
#

Yeah, events would be even more syntactic sugar in this case.

steady tartan
olive totem
#

Your code will not look very different compared to what you have now, the difference is that you won't have a list with that delegate type but instead you'd have declared an event and invoke it, no need to loop through the list

#
public delegate void UserInputReceiver(UserInput input);

public event UserInputReceiver onUserInput;

...

[ServerRpc]
private void SendPlayerInputServerRpc(UserInput userInput)
{
    onUserInput?.Invoke(userInput);
}
small badge
#

(Or private event, if you prefer.)

olive totem
#

Yeah but how do you subscribe to it then

small badge
olive totem
#

Sure doesn't need to be public but in this specific case I wouldn't see a big benefit to make it private. It would be more convenient if any class can subscribe to this event and you wouldn't have a need to create a separate function to pass a method to subscribe. The advantage of using event is that you can only invoke it from the class where you created it even if that event is public. You keep the convenience of accessibility from anywhere which makes sense in my opinion

#

Either way you could say an event already has its own list of subscribed methods so there's no need to create your own

regal olive
small badge
#

I'm afraid this is a community, not a premium support service; there's no guarantee anyone here will have the knowledge or time to answer any specific technical question. If you need prompt, guaranteed business-critical technical answers that's a service you will generally need to pay a lot of money for.

olive totem
#

@regal olive The ModdingAPI.dll does indeed need to have a reference to the assembly that has the function you want to call

fresh salmon
regal olive
#

Hm that kinda makes sense, would this work?:
Unity Game Script:

using moddingAPI;
public class exampleClass : MonoBehaviour
{
  public static void exampleFunction()
  {
    //stuff
  }
}

moddingAPI.dll:

public class moddingClass : MonoBehaviour
{
  public static void callExampleFunction()
  {
    exampleClass.exampleFunction();
  }
}

newly created C# project with the moddingAPI.dll added:

using moddingAPI;
  public void callModdingAPI()
  {
    moddingAPI.moddingClass.callExampleFunction();
  }
olive totem
#

Yes seems right

#

Would indeed be better design to just reference the ModdingAPI from any mod you plan to add, then mods don't need to have access to the assembly that has all actual functionality

#

I think that's what the post that @fresh salmon linked to proposes as well

regal olive
olive totem
#

I mean the way you structure the project so modding becomes easier to do

regal olive
#

ohhhhhhh design, I thought you mean de-sign (de-assign)

fresh salmon
#

Another example that conforms to my explanation

ModBase, present in the shared Class Library

abstract class ModBase {
  abstract void OnInitialize();
}

Mod, a class that a modder creates

using ModMaker;
class Mod : ModBase {
  override void OnInitialize() => Log("I'm alive!");
}

Loading the mods in Unity

using ModMaker;
class Loader {
  void LoadMods() {
    // Insert library loading shenanigans here...
    foreach (ModBase userMod in loadedMods) {
      userMod.OnInitialize(); // "I'm alive!"
    }
  }
}
regal olive
#

Oh that looks clean

fresh salmon
#

That's the base of it, where Unity "talks to" the mod, but it should be able to do the inverse too, and that's more complicated

#

Maybe using dependency injection, passing an object that makes the link?

override void OnInitialize(Environment env) {
  env.FindPlayer().Kill();
}
#

So you have the liberty to expose (or not) whatever you want to your modders

regal olive
#

Hm makes sense, thanks a lot to you guys for adding this to my knowledge UnityChanThumbsUp

tiny lotus
#

Hi there ๐Ÿ™‚
Some of our players have this message
ShaderProgram is unsupported, but because jobified rendering is enabled the ShaderProgram can not be removed.
that spam there player.log.
It's very performance consuming and for us it's hard to read and find informations in logs when they send them.

We are in HDRP and Unity LTS. Do you know how to remove this warning or just avoid to write it in the log?

small badge
#

Googling the message returns a lot of results discussing it on the Unity forum; have you read all of those and investigated the things they found that caused it?

tiny lotus
small badge
#

Just checking; a lot of people don't.

tiny lotus
#

^^, Discord is my last chance :p

#

We log the shader Level and the ComputeShader Comptability, every thing is ok, we add a custom command to check all shader with 'isSupported' and log is one is unsupported but without success :/

zinc shard
#

is it posible to interqact with files with HLSL?

sly grove
#

definitely not

#

HLSL code runs on the GPU. The GPU for all intents and purposes can only access its own memory

#

you can certainly load data from a file into video memory from C#

#

Using either Textures or a ComputeBuffer/GraphicsBuffer

zinc shard
#

aight

#

i need to initially calculate some stuff for a thingy during level load and with the loading times already being really long, i want to move the calculqations to the GPU because its really doing nothing during the loading

#

its a mod for a game btw

sly grove
#

potentially possible with a compute shader - but it depends on what kind of calculations and what you plan to do with the results

mortal glen
#

@small badge thank you, I got it working ๐Ÿ˜„

zinc shard
sly grove
zinc shard
#

Basically, in the game you build space stuff out of other parts

#

And what i want to ro

#

Do

#

Is i want to calculate when there's an enclosed space

#

With no gaps

sly grove
#

sounds complicated ๐Ÿ˜›

zinc shard
#

Yes

sly grove
# zinc shard Yes

Well the question of "can I do it on the GPU" is going to depend on the nature of those calculations.

#

Are they something that can easily be parallelized?

#

For example, computing the color of each pixel on the screen - easily parallelizable. Each pixel is its own distinct calculation. That's what GPUs are good at

#

there's no dependency between different pixels

#

So if you can model your problem in such a way, it would be a good fit for the GPU

zinc shard
#

Yeah i think it can be parallelized, as i can just first get all the places where two or more bounding boxes touch, and then give each thread one of such areas to calculate

#

Each part can touch multiple other parts, but each part could be given to different threads multiple threads, in pair with different other parts

stable spear
#

volume hermetics? what is that

#

I hope you don't mean volumetrics ๐Ÿ˜†

sly grove
#

related to hermetic seals I think

stable spear
#

oh

sly grove
#

as in - are these two areas of space connected

#

in such a way that gas can flow between them

zinc shard
#

Yeah

#

If the volume is hermetic there are no gaps

#

I mean I'm not going to make it tolerate small cracks so building hermetic things isn't such a pain in the ass

stable spear
#

you have a mesh representing your shape?

sly grove
#

if it's arbitrary meshes, then it's a different animal

zinc shard
#

ye the parts are made of meshes

zinc shard
#

its a tough problem

#

also im not going to calculate all the meshes in a craft (bunch of parts slapped together), just gonna make a custom part and calculate stuff attached to it

stable spear
#

do any of the triangles intersect other triangles?

zinc shard
#

they might

stable spear
#

that's not going to be fun, heh

zinc shard
#

yes

#

very not fun

stable spear
#

If you can first reduce it by detecting the intersections and splitting the triangles up so they no longer intersect. Then its just a matter of tracing along the surface (faces), and identifying the closed areas

#

Is there an industry standard algorithm you know?

zinc shard
#

i dont think so