#archived-code-general

1 messages · Page 231 of 1

misty ibex
#

but not a good one

#

i think chatgpt just made some hallways instead of rooms

#

i mean that's fair

misty ibex
#

my problem here seems to be hyper niche

pearl otter
#

@misty ibex I really have no idea what could be causing the issue, everything does seem correct. I wish you the best of luck with getting it working though!

tulip walrus
#

Would modding questions go in this chat?

somber nacelle
#

modding discussions should be directed to the community for the game you are modding, they are not allowed here

latent latch
#

Well, unless you're asking how to make your own game moddable, but that seems like some research of your own.

tulip walrus
somber nacelle
misty ibex
strange scarab
#

Is there a way to check if a dictionary contains no key, value pairs I.e if they have all been removed

somber nacelle
#

its Count property will be 0 if it contains no objects

strange scarab
modern creek
#

I'm .. stumped.. What else could control which scene starts from editor play mode? I wrote some code a long time ago to force it to a loading scene, but .. commented that bit out and I'm still starting from the loading scene (instead of the current scene in the editor)

misty ibex
modern creek
#

In my loading scene, yes, but in this new scene it's .. empty-ish.

I do have some "load first utils" in a script but nothing that should be ... doing anything that would instantiate anything?

#

Nothing is in the "Test Spine Character Rigs" scene and yet.. somehow my app gets forced back to the Loading scene

#

nothing in the codebase with InitializeOnLoad, nothing even that controls scenes that exists outside of my own scene manager which is instantiated after the game loads the loading scene....

cosmic rain
misty ibex
#

yeah that could be it

modern creek
#

oh, good thought

misty ibex
#

maybe the settings are somehow still being loaded

modern creek
#

can i force the editor dll to be recompiled?

misty ibex
#

trying rebooting

modern creek
#

(aside from restarting unity)

#

oh, wait, no - that's not it.. see that line that's commented out that warns? I see that in the logging as expected

#

"forcing scene to 0"

#

Oh, wait. Does DDOL persist between plays?

#

I see the DDOL "scene" appear when I press play

cosmic rain
#

No. That's normal.

#

Usually. Depends.

cosmic rain
modern creek
#

wtf.. The funny thing is most of the google results are how to avoid this behaviour and start from a fixed scene 😛

cosmic rain
#

Your commenting out probably didn't save or get compiled.

modern creek
cosmic rain
#

Make sure the editor refreshed after your changes.

modern creek
#

negative ghost rider, code's still compiling

#

note "player manager awakened" - there's no player manager in that scene (or anything, actually)

cosmic rain
#

..? So it didn't print?

modern creek
#

"dlich likes candy" followed by commented out lines of scene redirection

cosmic rain
#

Then it could be what I mentioned before.

#

Try restarting your editor.

modern creek
#

brb phone

cosmic rain
modern creek
#

those are a bunch of game objects that exist in LoadingScene

#

I'll restart the editor but.. still don't quite understand what would be causing it since that code is clearly compiled/updated (and the part that's sending the scene to [0] is commented out)

cosmic rain
#

You're messing with the editor runtime. Which I'm not sure resets between domain reloads.

modern creek
#

Weird, now it works. Interestingly, I see the "dlich likes candy" as soon as I start the editor (before I hit play once)

#

And yeah.. I suppose the editor compilation of the editor code only happens at some sort of .. editor domain reload? while the play mode compilation occurs on demand

cosmic rain
#

It's not related to code compilation lol

#

It's the runtime that is not being reset. Which is totally normal for programs.

modern creek
#

well I mean that bit of code there in the InitializeOnLoad doesn't .. get updated if I recompile/play. Isn't that part of the domain reload?

cosmic rain
#

It does

#

What it did to the editor doesn't

modern creek
#

Any way I can.. have it do so? re-instantiate the static LoadFirstUtils?

cosmic rain
#

Don't mess with editor scene manager in the first place 🤷‍♂️

thick socket
#

I know how to use "normals" to make a projectile bounce off walls

#

how could I "project" that path with a laser?

#

(like an ingame laser...not necessarily a raycast laser)

pearl otter
#

@thick socket You could use the LineRenderer component although I don't think they can be bounced off walls

thick socket
#

ooh perfect thanks

thick socket
#

not sure how "pretty" line renderers will be

#

but worth looking into

pearl otter
#

👍

soft shard
#

How is Unity.Mathematics.Random meant to be used? All examples I can find online just hardcode a number when initializing it, and some dont even bother, others suggest to use DateTime.Now.Millisecond or .Ticks, but the constructor only takes a uint, and .Ticks is a long (while Millisecond is an int), and converting or casting Ticks restricts the long to int.MaxValue (which makes sense) - in those cases random will always be the same seed anyway, though with this code im always getting min (in this case, 5), even with a different seed, is there another way its meant to be used or am I missing something in the logic?

public static int GetRandom()
        {
            var rng = new Unity.Mathematics.Random(System.Convert.ToUInt32(System.DateTime.Now.Millisecond + 1));
            var rnd = rng.NextInt(5, 10);

Debug.Log((System.Convert.ToUInt32(System.DateTime.Now.Millisecond)) + " | " + rnd);

            return rnd;
        }

According to the docs, .NextInt is exclusive, so id expect a value between 5 and 9, but I always get 5 (or whatever I set as min), why might that be?

dusk apex
#

What did the log print?

#

Millisecond plus one btw for the printing

fervent furnace
#

i use unityengine.random.range to seed it

muted valley
#

Can python be used in unity

dusk apex
fervent furnace
#

i remember they created a new extension so that you can use python, but i dont know the details, google it

muted valley
#

Ok i will thank you

soft shard
# dusk apex I'm assuming you're reseeding it every call to the function. Try seeding once on...

Seeding it once did seem to randomize it more often than not (still returns 5 quite often but that might be only having 5 numbers to choose from), though if the suggested usage with Random is to seed with millisecond/tick, wouldnt you want to update the seed every time you use it, as new miliseconds/ticks would have passed since the last use? - for the prints, I do get the current milisecond between 1 and 999 (as online suggested the constructor errors with a millisecond of 0)

fervent furnace
#

not sure if you can use python in game script

muted valley
#

I have a whole game in python 2d text based i want to translate to unity 2d mobile with ui

#

Any way to make scripts constant through multiple scenes?

#

Like i wanna declare a ton of variable when people load in

pearl otter
muted valley
dusk apex
#

If the seed values are all the same the results will all be the same - first element.

pearl otter
# muted valley Thank you sir

You're welcome, but you should consider using C#, by using Python you will most likely be slowing down your game, and you won't be able to get coding support in the Code Support channels. Plus all of the tutorials online and forum posts around coding are in C#.

pearl otter
#

I also wouldn't be surprised if unity Deprecated their Python scripting package soon, I'm surprised they even have one.

muted valley
#

I couldnt find a answer online

pearl otter
#

What is the question?

fervent furnace
#

c# or python script?

muted valley
#

Any way to make variables constant through multiple scenes

#

Like i add a ton of variables in beginning

#

And trace them later on

fervent furnace
#

not sure what you want: constant or static variable

muted valley
#

Constant

pearl otter
#

ScriptableObjects could work. You could also make game objects set to DontDestroyOnLoad which will bring Game Objects and their scripts across scenes.

soft shard
# dusk apex What's the actual print result?

first number is the milliseconds, second is Unity.Mathematics.Random and last is System.Random if I run it a few times, ill get different numbers for all of them, but usually 5 for the last 2

muted valley
#

I believe

#

Like i want to say
recruitableqb1 = “Johnson John” could i trace this later

fervent furnace
#

u cant modifiy constant in runtime, it is compile time defined
constant modifier

#

or readonly static

dusk apex
muted valley
#

So no?

soft shard
fervent furnace
#

yes, though the range of seed in mathematics.random is uint, but easy to write

pearl otter
# muted valley So no?

As I mentioned above, you can use ScriptableObjects or DontDestroyOnLoad() on your game object to access variables across scenes.

fervent furnace
#

or just unchecked the return value of random.range to keep the bit pattern

soft shard
# dusk apex So consider trying to acquire a different value for seed

Sorry im not sure I understand - right now this is what im doing:

static System.Random r1 = new System.Random(System.DateTime.Now.Millisecond + 1);
        static Unity.Mathematics.Random r2 = new Unity.Mathematics.Random(System.Convert.ToUInt32(System.DateTime.Now.Millisecond + 1));


        public static int GetRandom()
        {
            var rnd = r2.NextInt(5, 10);
            var rnd2 = r1.Next(5, 10);

            Debug.Log((System.Convert.ToUInt32(System.DateTime.Now.Millisecond)) + " | " + rnd + " | " + rnd2);

            return rnd;
}

The seed is now only being set once, are you suggesting to use a hard coded value for the seed instead or a larger number?

pearl otter
#

@muted valley Have I answered your question?

muted valley
#

Yeah you did

#

Thanks

pearl otter
#

You're welcome.

muted valley
#

Time to get to work tmmrw

dusk apex
soft shard
# dusk apex You're not supposed to reseed per call to random

Oh sorry, I forgot to remove the var rng part, I wasnt using it in that snippet just testing - though I thought you were meant to use the latest value of tick/millisecond when you wanted to make sure the value youd get back is not always the same most of the time, when should you usually reseed Random?

dusk apex
#

You'd seed once and simply call next whenever you're needing a random whatever.

soft shard
# dusk apex Never again unless you're wanting to explicitly reset random to a default initia...

Ah ok, one last question, if the value is only meant to be passed once, does the value of the seed not affect the results? It makes sense why it would reset to the initial value (as to why I always got the min) im just trying to understand why using the current millisecond/tick is often suggested over just a hardcoded value or someone mentioned with using UnityEngine.Random to generate a seed, is it just preference?

dusk apex
#

A hard coded seed value will always give you the same result - which you might want for certain games. You can use anything to initially seed it. Oftentimes the current time in milliseconds or some not so predictable value.

soft shard
#

Ah I see, thanks for the info and help on this

waxen burrow
#

is there a way to pre-calculate the magnitude of a rigid body before applying a force to it?
IE if(rb.addforce's magnitude < maxMagnitude){ rd.addforce;}

fervent furnace
waxen burrow
#

appreciate it

#

unfortunate but thank you

waxen burrow
#

Was able to make something that got close enough...
||May or may not have GPT'd this one||


        Vector3 currentVel = body.velocity;
        Vector3 acceleration = force / body.mass;
        Vector3 dragForce = -dragCoefficient * currentVel;

        acceleration += dragForce / body.mass;
        
        Vector3 predictedVelocity = currentVel + acceleration * Time.deltaTime;
        float estimatedMagnitude = predictedVelocity.magnitude;

        return estimatedMagnitude;
    }```
 I do not believe this will work with any other forcemodes other than force.
Also note that any forces outside of drag wont be accounted for unless added, so things like gravity will mess with the prediction
Final thing to note is that the dragCoefficient is some arbitrary constant that I made up... In testing I used 0.1 which works but Im sure a much better constant can be found without much work
waxen burrow
#

Ya know I just realized how pointless this is for my use case but it exists now I guess

craggy totem
#

hello devs, do someone know how to calculate proper position,
i have problem - particles should emit at collision point but it differs according world position of collision point, and i've made wrong position calcs
Custom_SimSpace_Transform is "ParticlesSystem's" Custom Simulation Space and it is located at center of car
here is script , thx in advance

        private void OnCollisionEnter(Collision collision)
            {
                var emitParams = new ParticleSystem.EmitParams();

+          //   IF I USE
-       /*      emitParams.position = new Vector3(0, 0, 0);     */
+          //   It will emit particles at "Custom_SimSpace_Transform" it is -> for example at (257,533,1043) in world postition . in other words it'll emits at center of car
+          //   So i made this thing bellow
               emitParams.position = Custom_SimSpace_Transform.position - collision.contacts[0].point;       <--- I assume ,Issue  is here
+          //   But it works not right as shown in video

                emitParams.applyShapeToPosition = true;
                Emit_1_obj.Emit(emitParams, 30);
            }

https://streamable.com/opgvy2

untold bobcat
#

Hey, guys, does someone know how to write a script to alternate between two different sprites based on a key input? I'm remaking Flappy Bird and need to switch between two sprites of wings flapping for each spacebar input.

fervent furnace
dawn nebula
dusk apex
dawn nebula
#

fancy, never seen that before

dusk apex
#

With + and - on the necessary lines.

#

You won't get proper c# syntax highlighting with it though.

craggy totem
#

Tranform.position calculation help

spark flower
#

i get null refrence here

cosmic rain
dawn nebula
# spark flower i get null refrence here

Code tip. Instead of doing spawnPoints[_index] every time you want to access the element, just do
var spawnPoint = spawnPoints[_index];
and use the spawnPoint variable instead

#

will make things a lot easier to read

#

also faster

spark flower
cosmic rain
dusk apex
spark flower
#

for the resistance[i]

dusk apex
spark flower
#

well making an instance fixed it

fervent furnace
#

looks like resistance is reference type

#

and you just create an array of reference but you didnt actually create the instance

dusk apex
#

The potential for error is quite high due to i being constrained to spawn point resistance length solely and not enemy point resistance length - not related to the specific error but should be considered.

#

You could also clear up some clutter by having local variable references of the elements being accessed from the arrays.

#
var enm = ...
var point = spawnPoints[_index];
...
for (int i = 0; i < point.resistance.Length && i < enm.resistance.Length; ++i)
{
    var enmRes = enm.resistance[i];
    var pointRes = point.resistance[i];
    point.sprite.enabled = true;
    pointRes.type = enmRes.type;//NRE here would mean that the element is null
    pointRes.modifier = enmRes.modifier;
}```
native fable
#

maybe stupid question

I have a list List<SystemBase> systems

Is it possible to go through the list to get exactly the heir (automatically bring the system to the class of the heir)?

mellow sigil
#

What do you mean by "heir"? The derived class?

hard viper
#

I am leaving all my methods and fields to my heir.

#

And nothing for my good-for-nothing daughter.

dawn nebula
#

It's not like programmers are strangers to giving multiple names to the same structures/concepts.

#

Method

#

Function

#

Map

#

Dictionary

latent latch
#

method and function do have different meanings

#

but function sounds cooler

#

same with vectors vs list

fervent furnace
#

i just call dictionary/hashmap/hashtable/array/unordered_map mapping
maps A to B

dawn sundial
#

Hi all, would you know how to add force (impulse) to CharacterController to Jump? Any ideas?

pearl otter
half prawn
#

Is there any way to check that there isn't any particles inside sphere? Like CheckSphere(), but seems CheckSphere() doesn't work with particles.

grim kiln
prisma birch
#

Is there a way to make objects permanently lockable/unselectable in the Scene View? There are certain VFX I have in my game that use large cubes and quad meshes with alpha clipping and transparency that I don't EVER want to be able to select from the scene view. To get around this, I can toggle picking on them in the Hierarchy or Layers options but Unity always seems to arbitrarily reset these options and there doesn't seem to be a good way to modifiy them via editor scripts. Am I missing something totally basic that would solve this problem?

grim kiln
hard viper
#

I need a bit of physics help again. My blue circle is moving down through the red edge colliders (which are both a part of one composite/custom collider). The red colliders are supposed to have a one-way effector. When I use .Cast, the blue ball only gets a hit on the upper red edge shape, which it has been told to ignore because it is in the middle of it. How do I detect the lower shape?

#

assume my blue ball-like colliders could get complex, so raycasting from each lower surface individually is not a good idea

grim kiln
prisma birch
hard viper
#

(sorry if I didn’t specify 2D earlier)

thick bough
#

In 3D you would use Physics.RaycastAll to receive a list of all hits

grim kiln
hard viper
#

yes. both are part of a composite collider produced from a single tilemapcollider2D

#

tilemapcollider2D have been making things more complicated in terms of physics tbh

grim kiln
#

That's tricky

dawn sundial
hard viper
#

yeah. I’m thinking I might need to query the composite, and make a series of customcollider2D for bundles of shapes. But it seems like a hackey solution that contradicts the point of a composite collider

grim kiln
pearl otter
dawn sundial
# pearl otter Which is why I gave you code for CharacterController jumping

I'm confused, I saw there RB only, maybe you edited, not sure.
Anyway, I have that code there. Not working :/ I'm trying to do the jump like 5th time. Never had an issue in 2D. I don't even know my name how angry I am (doing 3D movement first time for last 50 hours).. never had an issue with complex coding of various systems, but seems like 3D caught me unprepared 😄

hard viper
#

that might cause issues later when my colliders get more complex, as raycasts are similarly expensive to casting a polygon, but i’d need several to handle more complex geometries.

pearl otter
hard viper
#

maybe unity just doesn’t give the tools to query this for 2D

leaden ice
hard viper
#

the issue is the red lines are all part of one collider

#

.Cast only gives me one hit result per collider

#

Unless there is some setting idk about

leaden ice
#

ah yeah didn't realize that. Is it not possible to split that collider somehow?

#

You can also try doing another cast from the other direction

hard viper
#

i could split the collider, but I would need to potentially make 100 colliders separately to split it

#

example hard case

#

i would be ok with the top right part of the blue either ignoring or registering the widest red shape. But i need to know that I would detect the bottom red shape.

leaden ice
#

yeah i'd do a staged raycast here

#

but definitely hard with the complex shape

#

What's the use case of this?

hard viper
#

my semisolid (one way) platforms are generated by a single tilemap for a level. They all feed into one composite collider.
The blue blocks are blocks of arbitrary shape that can be made and pushed around

#

blue blocks are made by one tilemap => composite collider

grim kiln
#

Why do you need to raycast to get the lowest platform?

leaden ice
#

I think you might need to make them not one composite collider as the most straightforward solution

hard viper
hard viper
leaden ice
#

do you really need all of them at once?

#

How many platforms will be on screen at a time

hard viper
#

potentially many. it is a maker-style game

#

so nothing would stop the player from just drawing a bunch of platforms in a weird line like that

grim kiln
#

I'm not completely sure I understand the use case but you could try getting the corners of your custom shape and doing raycasts from the lowest ones, that would probably find your platforms.

hard viper
#

the normal unity way is to make each platform one gameobject.

grim kiln
#

Or even from all the corners, and getting the best platform to rest on.

hard viper
#

that might be the solution, but since this is for a custom physics engine, 20 raycasts for a complex shape every frame is like 20x more expensive for the most expensive part of my little physics simulation

#

i have just benchmarked Collider2D.Cast vs Raycast. Both are weirdly very close in cost

grim kiln
#

You could do a single corner per physics step, or frame, so the cost would be fixed but the accuracy would go down as your shape gets more complicated.

#

Single or fixed number.

hard viper
#

all these solutions just feel so expensive because the shapes can have arbitrary sizes notlikethis

grim kiln
#

There's always a limit of some kind.

hard viper
#

it just feels like a really silly reason for the limitation

#

just that the cast only gives one hit per collider instead of per shape

grim kiln
#

You can alternatively choose to have many colliders, it's just another performance consideration.

#

How much of this do you have running right now?

hard viper
#

would you know how the scalign is in terms of cost? 1 composite with 100 shapes vs 100 custom colliders with 1 shape each?

hard viper
grim kiln
#

The only really good way to measure is to test in your project. How much of this have your built?

hard viper
#

my physics engine is like 95% done. Just working out some last oddities/bugs

#

custom solver… however you want to say it

grim kiln
#

So pick one of the above options and profile. Measure on a target device. See what the cost is, scale various factors and find out how much works and to what scale.

#

It's the only way to be sure 👽

hard viper
#

makes sense

grim kiln
#

You may be surprised what you can get away with.

hard viper
#

yeah, I just want to avoid the kind of surprises of players breaking the game in terms of unintended lag

grim kiln
#

profile first and worry later

hard viper
#

btw feature request wise: it would be nice if CustomCollider2D were not a sealed class. So you could just inherit and make your own collider classes with their own parameters

#

it’s just a lot harder to use customcolliders when inheritance isn’t allowed

thick socket
#
protected bool explodesIntoMoreFireballs = false;
#

I have a class extend the class this is declared in...is there a way to have the extended class make this into a Serialized Field?

thick socket
#

darn, thanks 🙂

latent latch
#

why not just serialize it

thick socket
#

Dont want the extra "garbage" on more classes

gray mural
thick socket
#

however I've only got 3 enemies left so dont wanna re-configure it all rn 😄

tawny moth
#

Hello, I want to make an animation listener for server client infrastructure. The client gets the state it is in with stateInfo.fullPathHash and updates the animID in its object to other clients, if the script animatorType == server, it updates the animator with the animID from the server, but I have problems with loop animations like walking, idle. How should I use the data I get from stateInfo.fullPathHash or are there any other methods you can suggest?

    void Update()
    {

        if (animatorType == animatorType.client)
        {
            AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
            int currentStateID = stateInfo.fullPathHash;
            animID = currentStateID;
            Debug.Log("currentanim Hash" + currentStateID);
        }

        //remove the query prevAnimID != animID I tried refreshing it continuously, but it had no effect.
        //I also tried animator.Play(animID, 0, 0f); but the problem is still the same

        if (animatorType == animatorType.Server && prevAnimID != animID)
        {
            animator.CrossFade(animID, 0.2f);
            prevAnimID = animID;
            
        }
    }

video: https://youtu.be/PfmqvWi__7I

polar marten
tired forum
#

This might seem like a super silly question, but it is a gap in my knowledge. I understand I can't play DirectX games on linux, but can I build a StandaloneWindows64 target on linux and use DirectX for the graphics API

polar marten
tired forum
#

Aka -Can I build a D3D Game on Linux for Windows

leaden ice
#

don't see why not

tired forum
#

Using the unity headless, is there a parameter I can pass that will force only using D3D graphics API ?

polar marten
#

you are at the start of a long journey if you are trying to render headlessly

tired forum
#

I am using game-ci to build our client - every time it builds it fails compiling our shaders because of GLES

tawny moth
polar marten
polar marten
#

for everything but the simplest projects

tired forum
#

Yeah - this would not be that unfortunately

#

So for CI (aside from using Cloud Builder , which will explore) do you recommend just doing a script

polar marten
#

where does the CI have to occur? what is its purpose?

tired forum
#

I have a PowerShell script that I use atm that works on windows and headless

#

We would like it to occure in Github using Github ACtions

#

purpose is to just make our life easier and be able to reduce depedencies on people to do an internal build

polar marten
#

i guess, bigger picture, the goal is to save money? you will have to pay for a unity license anyway to run on github actions

tired forum
#

Oh no we will still pay for a license

polar marten
#

yeah i guess i'm saying that cloud build is what you should use

tawny moth
polar marten
#

because you will not succeed in building a complex project in CI in the short term. it will take a really painfully large amount of product development

tired forum
#

We would like to keep our build systems all in th esame place if we can

#

As we have other tools that aren't unity

polar marten
#

i'm not saying it's impossible

tired forum
#

Thats unfortunate

polar marten
#

you will never be able to build il2cpp windows correctly on github actions, for example.

tired forum
#

Oh that is ok

#

we use mono

polar marten
#

anyway, you should use cloud build

tired forum
#

lol ok - point taken , I'll go take a gander

#

Thank you for the help!

polar marten
#

i have definitely tried to raise issues with game-ci in the past, and they were ignored

#

so i feel the same pain as you

tired forum
#

yeah atm, I just have a Github Self-hosted runner that execute a headless powershell script

polar marten
#

it's ultimately one guy. he doesn't have the bandwidth to test people's projects

polar marten
tired forum
#

ha - well it does work pretty well atm

#

I just hate windows and would prefer it to build on linux

polar marten
#

welll....

#

we built all our infrastructure on top of windows

tired forum
#

so if I can solve for the D3D problem, I am fairly comfortable with the rest , so long as their aren't other Unity issues

#

Ah - we are the opposite

polar marten
#

you definitely, absolutely cannot build unity on linux for anything but the most simple projects

tired forum
#

I am leaning that 🙂

#

couple of our shaders throw up when compiling with Volkan , which is why Iw as asking about forcing D3D

polar marten
#

you shouldn't have issues compiling to vulkan on any platform

#

it is very easy to specify the graphics devices though

tired forum
#

We are geting a reserved keyword issue , gl_

polar marten
#

well... that's a real error

tired forum
#

only happens with Volkan

#

Vulkan

polar marten
#

are you using ASE?

tired forum
#

Ha - I am not a shader guy - so I have no idea what that is 🙂

polar marten
#

amplify shader editor

#

i think you should use cloud build

tired forum
#

I'll have to ask - I don't thin so

polar marten
#

they're going to tell you this is an issue with your project

#

you don't specify the linux build target when building for windows, so you never have to build for vulkan anyway

#

so i think there are some basics you haven't figured out yet

tired forum
#

And that does make sense - infact in our project settings, we specify the graphics API for the windows target

#

I am wondering if this is a game-ci thing

tired forum
#

@polar marten Answer to your question - no we did not use ASE , just built in unity shader graph

scarlet viper
#

any way to pass a custom parameter to SceneManager.sceneLoaded ?

#
    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
      }
#

it looks like this

#

so i cant add custom params

pearl otter
scarlet viper
#

ID of some sort

pearl otter
#

You could create your own function in your own script that can take in extra parameters.

knotty sun
scarlet viper
#

im explaining the situation

pearl otter
#

Why do you need to pass an ID anyways?

spring creek
knotty sun
simple egret
fluid lily
#

Just reading over the Unity.Logging code, and I have seen a continued theme on Unities new packages. Why does Unity hate people modifying their code so much? Like the Unity.Logging.Logger has no virtual methods, poor documentation. Like I just want to be able to make a Logger with a specific decorator for the class Type that I pass it to with my Dependancy Injection framework

pearl otter
fluid lily
#

I think you miss understood. I am not trying to modify the source code, but inherit the class to make custom implementation

#

Thus virtual

pearl otter
#

Oh I see

#

That's a good point

#

But do you really need to create a custom logger? In most cases it will meet the needs of the user considering all it does it log messages for debugging purposes

fluid lily
#

Anyone who has used actually good logging frameworks have more needs then what they offer. I have Serilog working, but the adapter for it and Unity is rough at best, so was hopping this had more potential

pearl otter
fluid lily
#

What? I think you are talking about the console, vs the logging framework. Console is responsible for the display of the logs, which I am using Seq, and there are assets on the store that have better editor consoles. The logging framework is what gets/formats the logs, and then sends it to sinks(like console/file/seq/database)

pearl otter
#

Ah, well why not create your own logging framework?

fluid lily
#

I figured out how to do what I wanted. using

Log.Logger = new Logger(new LoggerConfig()
.MinimumLevel.Debug()
.OutputTemplate("{Timestamp} - {Level} - {Message}")
.WriteTo.File("..absolutPath.../LogName.log", minLevel: LogLevel.Verbose)
.WriteTo.StdOut(outputTemplate: "{Level} || {Timestamp} || {Message}"));

and my DI framework I can just hardcode the type in the logger I inject.

fluid lily
pearl otter
hard viper
stoic warren
#

hello I have a problem in my code. it doesn't want to take "else" please help me, thank you

vagrant blade
dusk apex
vagrant blade
#

You're also misspelling your reference to your sprite renderer

simple egret
#

Hey at least their VS is configured properly

#

But yeah you're missing a bunch of curly brackets, and that's what's making it angry

spring creek
hidden flicker
#

how do i average two vectors

simple egret
#

Like you would with two numbers

#

Add them, divide by two

#

Or you can do a fancy Vector3.Lerp(a, b, 0.5f) to get the mid-point between the two, which is the average

hidden flicker
simple egret
#

new is not expected here, Lerp is a method

hidden flicker
#

got it ty

simple egret
# hidden flicker got it ty

Hm seeing your code, you seem to average two direction vectors, so you'd be better off using Slerp which will give off a normalized vector out of the box

fluid lily
#

So I am setting up my bootstrap scene loading. Currently if I have multiple scenes loaded in editor with bootstrap not the first one, the other scenes scripts will be called first. I tried to get all active scenes, and unload any but bootstrap and then reload them, but they won't unload on
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
I can't find a way to reorder the load order of active scenes in the manager. Does anyone know how to do this?

quaint crypt
#

I bought a new pc and am trying to open up my project in the same exact editor version, but all script links are broken and prefab links as well. (game objects have missing links to their prefabs, linked game objects are broken as well). I brought the exact same code that was pushed from the other pc via git, so there is not a single change that i dont have on the new pc. what am i missing?

gray swift
#

Hello i have a quick question. I dont really understand how audio sources work. I am using them to make 3d sounds. I get how to set them up and do the range and everything and it works how I want it to. Now im having issues where in my script I am trying to play a 3d sound. I cant really get it to work and it isnt doing the distances right. ```using System.Collections;

public AudioSource flickerSoundOn;
public AudioSource flickerSoundOff;
private readonly float offDuration = 0.2f; // Fixed duration for which the light is off

IEnumerator Flicker()
{
    while (true)
    {
        // Turn the light off and apply the off material
        lightToFlicker.enabled = false;
        objectRenderer.material = offMaterial;
        flickerSoundOff.Play();
        // Wait for a fixed duration of 0.2 seconds
        yield return new WaitForSeconds(offDuration);

        // Turn the light back on and apply the on material
        lightToFlicker.enabled = true;
        objectRenderer.material = onMaterial;
        flickerSoundOn.Play();
        // Wait for a random time before turning the light off again
        float waitTime = Random.Range(minTime, maxTime);
        yield return new WaitForSeconds(waitTime);
#

object
I cut the code cuz it was long. But do I just make an empty object that has the audio source and refference that?

simple egret
#

What I'd do is only use one AudioSource placed correctly in the world. The script references it, as you have it now.
Then the script would also reference two AudioClip in which you'll drag-drop the sound effects, and call source.PlayOneShot(clip). This has the advantage of using one source to play a variety of sounds, without the sounds cutting each other out if you play them fast enough for them to overlap a bit

gray swift
#

Oh hm I see. So make an audio source in the object that I want to change and then that audio source gets recieved the clip from the code and plays there?

simple egret
#

Yep, in that case you don't drag-drop the clip to play in the Audio Source, but in the script

gray swift
#

I see. Thing is. On the object I want to make this flickering sound I already have an audio source constantly emitting a hum. So would I just make another audio source as a component. If so how would I access that one in my code? Sorry im really new to this need to watch a video or smth

simple egret
#

Yeah you can have another one on the same object, and you'd have to drag-drop it into your script.
Place your cursor where it says "Audio Source", and start the drag-drop from here

gray swift
#

Ok thank you so much. Im going to quickly try and if it doesnt work ill probs text again lol. but thanks

mild orbit
#

Is there a more performant way to stop all components that have [ExecuteAlways] from running than doing

foreach (var comp in go.GetComponentsInChildren<MonoBehaviour>())
    comp.enable = false;
#

Basically I only want to render a GO, not have any of its logic execute.

latent latch
#

Could seperate the logic from the render

gray swift
latent latch
#

so you only need to disable the logic GO

simple egret
tawny elkBOT
gray swift
#

Okay yeah thats what i was looking for. Its not that long but dont wanna disturb. gonna send it rn tyy

mild orbit
gray swift
#

https://hastebin.com/share/xanevedawi.csharp okay so this is my code now. Im still kinda confused on how to get the right audio source to play

#

Do I just drag and drop it

#

where I set the audio source at the top

simple egret
#

Yes, but to be able to see it in the Inspector, you need to make it public like the two clips

gray swift
#

Oh yeah idk why i made it private that was dumb of me

simple egret
#

And then also remove the lines 25-28 which will overwrite the value you drag-dropped

gray swift
#

Wait whats the difference between readonly and private.

simple egret
#

Read-only is well, read-only. You can't put a new value into it with =
Private is not visible outside of the class

gray swift
#

Oh I see so once you set a read only it cant ever be changed. Thats interesting. Thank you so much for the help I figured out the other thing aswell just drag and dropped it

latent latch
lean sail
gray swift
#

Wait im having an issue still

#

I did what you said and dragged and dropped it in but its still not playing in seperate audio sources

#

I want it from the second one

simple egret
#

Did you remove the lines in void Start() that fetch an AudioSource again, overwriting what's in the variable?

gray swift
#

I removed the ones you told me to i think\

#

rn its just this

#
    {
        if (lightToFlicker == null)
        {
            lightToFlicker = GetComponent<Light>();
        }-------

        audioSource = GetComponent<AudioSource>();
      

        StartCoroutine(Flicker());
    }```
simple egret
#

The one in the middle of that code still puts a new value into it

#

audioSource = - puts a new value into the variable

#

It says "Look for the first AudioSource component you can find on this object, and put its reference into the variable"

mild orbit
latent latch
mild orbit
#

Using the preview scene is how Unity does all of the renders and previews of things internally too.

elder obsidian
#

Any one does have any idea about why this is happening? I'm just trying to spawn an prefab on client and host...

#

This is the class


using Unity.Netcode;
using UnityEngine;

public class TestPrefabSpawner : NetworkBehaviour
{
    [SerializeField]
    private GameObject _NetworkPrefabToSpawn;

    public override void OnNetworkSpawn()
    {
        Logger.Info($"Spawned with Network.");
    }

    private void Update()
    {
        if (!Input.GetKeyDown(KeyCode.Return))
            return;

        if (IsOwner)
        {
            if (IsServer)
                SpawnPrefabClientRpc(LocalPlayer.Transform.position, OwnerClientId);

            if (!IsServer)
                SpawnPrefabServerRpc(LocalPlayer.Transform.position, OwnerClientId);
        }

    }

    [ClientRpc]
    private void SpawnPrefabClientRpc(Vector3 position, ulong id)
    {
        var instance = Instantiate(_NetworkPrefabToSpawn, position, Quaternion.identity);

        instance.GetComponent<NetworkObject>().SpawnAsPlayerObject(id);
    }

    [ServerRpc(RequireOwnership = false)]
    private void SpawnPrefabServerRpc(Vector3 position, ulong id)
    {
        SpawnPrefabClientRpc(position, id);

    }

}

#

And it's a direct children of the player network object

#

I'm this close 🤏 to give up on 5 months of work because of this

#

For context, the prefab is being spawned on the host and visible on the client. But this error is triggered when the client tries to spawn the prefab from the ServerRpc

gray swift
#

Hey. I am trying to bake a nav mesh. Why is this happening this gap?

hexed pecan
gray swift
#

Oh wait I see. I used pro builder to make a gap in that wall. Apparently unity still thinks there is a wall there. Do you know how I can fix that?

hexed pecan
#

No idea about probuilder. Is there some leftover invisible object?

#

You baked again after removing it, right?

elder obsidian
#

try checking out the size of your navmeshAgent, sometimes it's too thick

gray swift
#

Yeah look

#

Thats when I select the walls

#

It thinks there is a wall there

elder obsidian
hexed pecan
# gray swift Yeah look

What object is selected/outlined here? Looks like that object actually has a gap. Hide it and show what remain?

gray swift
#

Its the wall selected

hexed pecan
#

Ok looks like it still has mesh data but no materials or something... you probably need to fix that with probuilder somehow

gray swift
#

Yeah this is weird

#

The edge is still there

#

idk how to remove that

hexed pecan
gray swift
#

Ah

#

Didnt realize that was a thing thanks

#

I have a nav mesh setup with a sprite renderer set to follow my player. How do i set the direction the nav mesh faces. It is coming backwards towards me

#

It works when I make the material double sided and regular but I want it to be affected by lights so I put diffuse on

hexed pecan
gray swift
#

Sprite renderer sorry yeah

#

It doesnt face the right way that the nav mesh makes it face and walk

hexed pecan
#

Should it face the camera or should it use the rotation of the player?

gray swift
#

Idk ig face towards the camera. Rn the nav mesh AI seems to be running its direction already ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class testMonster : MonoBehaviour
{
public NavMeshAgent ai;
public Transform player;
Vector3 dest;

// Update is called once per frame
void Update()
{
    dest = player.position;
    ai.destination = dest;
}

}``` this was all the code

hexed pecan
#

If you want the spriterenderer to face the camera, you can use LateUpdate, set its rotation to the camera rotation and then rotate it 180 degrees on Y

toxic vault
#

Why would this work fine

buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent(TextMeshProUGUI).text

But this throws an error

buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent<TextMeshProUGUI>()
#

And this only works in immediate window. The first code won't even compile!

spring creek
#

You really would want to separate the calls instead of one long chain too. Find on its own line GetComponent on another

toxic vault
#
selectedPlayerIndex = Int32.Parse(buttonGameObject.transform.Find("IconContainer/Text_Index").gameObject.GetComponent(TextMeshProUGUI).text);

is how it goes. I have a Text_Index child object inside of the main gameobject where it stores an index in a TextMeshPro component

#

But I can't get it to compile. Although if I do this in immediate window, it works

cosmic rain
#

Seems like you're using GetComponent .method incorrectly. Read the error and look at the method documentation.

toxic vault
#

This is through immediate window

#

And this is when I try to compile

toxic vault
cosmic rain
toxic vault
#

The reason I started debugging through immediate is because I couldn't get the .GetComponent working at all in code.

cosmic rain
#

You should check it's documentation. The generic method was correct.

#

You probably didn't have the component on the GameObject

toxic vault
#

Ok, will doublecheck everything. I just found it odd that code worked in immediate but not when running. Thanks

indigo plume
#

I lost my usb with a project on it 💀 is there any way to recover it or am i screwed

vagrant blade
#

How can you possibly recover something that was physically on something else?

#

This is the reason you should be using version control which keeps your project on the cloud

#

So unless you find the USB, take this as a learning moment and learn how to use version control before you start your project again

spring creek
clever bridge
#

Hi, not sure if this is the right channel but I'm trying to code a 2d character throwing a grenade at the player. I have this as the angle calculation

#

        Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));

        throwGrenade.GetComponent<Rigidbody2D>().AddForce(new Vector2(final.x * force, final.y * force), ForceMode2D.Impulse);
#

the enemy is not throwing it in the right direction and I'm not sure why

dusky lake
#

First, use SignedAngle

#

Otherwise you get the delta amount instead of the Real delta

#

Is only the direction or also the trajectory wrong?

clever bridge
#

I have no idea, it's all kinds of messed up

#

when player is near 0,0 it seems to work right

#

but if player moves anywhere else it doesn't aim right

dusky lake
#

Then try the signedAngle approach

clever bridge
#

I just want the direction right

dusky lake
#

Instead of Vector3.Angle

clever bridge
#

I did signed angle and it didnt' change anything

#

I did Vector2.SignedAngle

#

since it's 2d

dusky lake
#

Oh wait cause you take positions instead of directions for an angle calculation

#

You need to compare forward to the direction from one character to the other

clever bridge
#

I debug logged the player position and the grenade thrower position and they seem to log correctly

#

so their localScale.x do change

#

both of them

#

I didn't know that affected transform.position

#

I thought I could just get a raw angle from grenade thrower to player

dusky lake
#

Basically

var angle = Vector3.SignedAngle(Vector3.forward, player.transform.position - transform.position)
#

Huh that has nothing to do with scale

clever bridge
#

        Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));

        Debug.DrawRay(transform.position, final, Color.red);```
#

so I had to change Vector3.SignedAngle to Vector2 or it gave a red squiggle

#

and now the angle is always 0

dusky lake
#

Vector3 angle needs an axis I think

#

Im on my phone rn but try adding Vector3.up as a last Argument

clever bridge
#

angle is always 90 now

#

whatever z is it seems to constantly be that now

#

        Vector2 final = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));

        Debug.DrawRay(transform.position, final, Color.red);```
dusky lake
#

What do you mean whatever z is

lean sail
#

How come you even need the angle for this? If you want to throw it at the player then the direction is just player.transform.position - transform.position.

clever bridge
#

oh

#

I'll try that

#

it was a drag converting it from x and y to angle to x and y

lean sail
#

using the angle would only be like if you wanted to see if the enemy had "vision" of the player

dusky lake
#

Oh, was so focused on fixing that Code that I didnt even think about that 😂

clever bridge
#

yep, that did it

#

Thanks!

lean sail
#

i believe that final value you have calculated should give you the same direction. Maybe something needed to be normalized, but yea no point really doing it anyways

clever bridge
#

cool thanks

lean sail
#

oh actually, that final value would only work if this was aligned with the unit circle

soft shard
# indigo plume I lost my usb with a project on it 💀 is there any way to recover it or am i scr...

Losing a project sucks, as Osteel mentioned because its on a physical location there might not be a way to recover it unless you have a backup somewhere else, if you do decide to try version control, I find GitHub or BitBucket as nice gits, with "SourceTree" or "GitHub for Desktop" to access your git quite nice too, since its on the cloud, youd be able to access your projects anywhere with internet this way, and revert backups in case you mess up a version of your working project you want to restore later

lean sail
#

Is it common to get this _unity_self value cannot be null error and can i do something to fix it? It appears everytime I start the game while inspecting a SO instance. It doesnt happen if i start then click on an SO to inspect it. I dont have a custom inspector for it or anything. I assume its some corrupted data, because ive changed whats in this SO a few times (added/removed stuff)
Its not a major issue since i can avoid it, but just kinda annoying

sleek chasm
#

what does this error means ?

rigid island
polar marten
lean sail
sleek chasm
astral oriole
#

`private bool IsVisibleInScreen(Camera c, GameObject target)
{
var planes = GeometryUtility.CalculateFrustumPlanes(c);
var point = target.transform.position;

        foreach (var plane in planes)
        {
            if (plane.GetDistanceToPoint(point) < PlayerController.instance.cameratest)
            {
                return false;
            }
        }
        return true;
    }`
#

Am I able to write this code as a job?

#

I'm having an issue because of the parameters that it needs to take in

cosmic rain
astral oriole
#

Yeah, I'm not sure if it'd be worth it :/

ashen yoke
scarlet viper
#

is that supposed to not work?
I get:
ArgumentException: SceneManager.SetActiveScene failed; scene 'Mountains' is not loaded and therefore cannot be set active

#

but im waiting until scene is valid

dusk apex
#

What's the error line?

#

It doesn't seem to be related to the code shared

scarlet viper
#

Nvm

wheat cargo
#

Anyone know a way to get the .exe path including the file name of the .exe? I tried GetModuleFileName with p/invoke but it is just giving me C:\Users

wheat cargo
#

I'm trying to restart the game from inside the game itself

wheat cargo
#

Yeah I could use those, but I didn't know if there was something that would just give it to me in one go

leaden ice
#

Since if you start a process from this process it'll be a child process, right?

wheat cargo
#

Yeah maybe not, but I was gonna try to launch a launcher process that doesn't get killed by the parent process which will launch the game again

#

Call of duty does this when it updates or fails to connect to the internet so I just wanted to see if I could do something similar

leaden ice
wheat cargo
#

I'm just surprised GetModuleFileName is giving me C:\Users, from what I've researched it's supposed to give the .exe path including the filename of the .exe.

I'll just have to use Application.dataPath and Application.productName for now.

#

Oh my god, GetModuleFileName was working, but I was using a UI toolkit label to display the string and for some unkown reason it was only displaying C:\Users

#

I logged it to the log and it is the full path. I don't get why UI Toolkit was truncating it

#

Lol I think it thinks it is a new line character because my user folder is C:\Users\natha

#

Lmfao

leaden ice
#

Oof

wheat cargo
#

Big oof

maiden quail
upper pilot
#

How would I show a button "disabled" graphic without disabling the button?
I am trying to add speed settings for the game x1, x2, x5 and when you press 1 option, others would show as disabled/not active

rigid island
pearl otter
upper pilot
pearl otter
upper pilot
#

Nope

#

I want something like a radio options I guess, but with buttons.

rigid island
upper pilot
#

Selected item would have different graphic.

rigid island
pearl otter
upper pilot
#

you press x1, x1 button graphic becomes "active", but x2, x5 becomes "Deactivated"

#

I dont want to rename the button text

#

I want to change the graphic

pearl otter
upper pilot
#

Is there a more elegant way?

#

Let me see if there is a radio button in Unity :c

pearl otter
#

If you're wanting to change the image depending on its state, then you will need to change the Image 😑

#

If you're wanting to change the color then you just need to change the button.color variable

upper pilot
#

Buttons have 4 or 5 states that let you set different image for each state.

#

I am looking for a built in way

#

I dont want to set graphic in script

pearl otter
#

The only other way is to have all of the images already on gameobjects and enable/disable the gameobjects depending on the image you want active, but you shouldn't do that.

deft kindle
#

How do i make a gravity tool where you can pickup objects by having the script enabled and then pressing left mouse button to pick the object up and when you hold a object you can move it like its infront of you and rotate if you hold shift and move your mouse also you can move it forward and backwards using scroll wheel and if you press left mouse button you you place it with gravity and if you right click you place without gravity?? (I know this is hard)

pearl otter
#

@upper pilot What you're trying to do is very simple, there's no way to do it without scripting unless if Toggles does what you need it to do.

rigid island
#

most of the convos in here belong there anyway

deft kindle
upper pilot
#

right, its called Toggle Group for some reason, not RadioButton group 😮

rigid island
# deft kindle Yea ik

I think in here you're expected to have some sort of coding experience doing at least one of the things in your question

pearl otter
deft kindle
rigid island
deft kindle
rigid island
#

everyone in gamedev reuses scripts

deft kindle
pearl otter
upper pilot
#

I am using Toggle group and it does what I need

pearl otter
#

👍

pure garden
#

Any idea on why this doesn't work

LayerMask layers = LayerMask.NameToLayer("Interactable") | LayerMask.NameToLayer("Object");
foreach (Transform obj in world.transform)
{
  if(obj.gameObject.layer != layers)
    obj.gameObject.SetActive(false);
}

If I only type one layer it works, but if i do more than one (2 in this case) it doesn't

pearl otter
pure garden
#

yh doesnt work either i have alredy tried

pure garden
#

that actually works tysm

wheat cargo
#

If anyone is curious, I got my app restarter working. Here is the code,

Restarter app code:

// compiled with .NET 8 Native AOT
internal class Program
{
    // first arg is processID
    // second arg is process file path
    static void Main(string[] args)
    {
        int processId = int.Parse(args[0]);
        string processToStart = args[1];

        while (true)
        {
            var processes = Process.GetProcesses();

            if (!processes.Any(p => p.Id == processId))
                break;

            Thread.Sleep(100);
        }

        ProcessStartInfo start = new ProcessStartInfo();

        start.FileName = processToStart;
        start.UseShellExecute = true;

        Process.Start(start);
    }
}

Code in Unity:

public static class AppRestarter
{
    public static void Restart()
    {
        var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
        
        System.Diagnostics.ProcessStartInfo start =
            new System.Diagnostics.ProcessStartInfo();
        
        start.FileName = "restarter.exe";
        start.Arguments = currentProcess.Id + " " + currentProcess.MainModule.FileName;
        start.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Hides GUI
        start.CreateNoWindow = true; //Hides console
        start.UseShellExecute = false;

        System.Diagnostics.Process.Start(start);

        Application.Quit();
    }
}
swift falcon
#

Does Unity loads the texture of any asset "mentioned" in the scene? Even if I have a prefab referenced in the scene Object, and no one instantiate it, it will still load it's textures to VRAM? How do I prevent it from loading everything in the scene?

latent latch
#

Resource.Load or bundles

indigo hound
#

Anyone know how to fix this, what causes this?

rough tartan
#

here is the script that I use to make a player appear when he connects to the game, the only problem is that in certain cases the player who appears does not take the correct ID in his MyID variable which allows him to be differentiated from the other iterations of player, how can I ensure that the player that appears is indeed the ID that is intended for it, that is to say the ID that the script to detect as not assigning to an already existing clone?

the part of the script which makes the player appear (The script has the name CLIENT):

if (!ConnectedPlayer.Contains(NewID))
{
        NewIterationID = NewID;
        player = Instantiate(PlayerPrefab,new Vector3(0,1,0), Quaternion.identity);
        Debug.LogError("NEW PLAYER ARRIVED : " + NewID);
        ConnectedPlayer.Add(NewIterationID);
}

the part of the script present on the player and which is supposed to recover his ID (the script is called Ennemie):

void Start()
{
    clientComponent = GameObject.Find("Player").GetComponent<CLIENT>();
    MyID = clientComponent.NewIterationID;
    Debug.LogError("Player : " + MyID +" has been sumoned");
}

for exemple Here 2 player connected into the game with 2 different ID but the 2 iteration take the same ID

opal mulch
#

!learn

tawny elkBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rigid island
opal mulch
#

I just didnt see it in the others

small schooner
#

Disable Camera and check if there is no other camera in scene

strong oracle
shell scarab
#

hey guys I couldn't really find information about this. I was wondering, if I have a bunch of references to a material, does that material get instantiated a bunch?

#

All the references should just be pointing to the material file right?

soft shard
shell scarab
#

you mean only if I apply that material to something, right?

soft shard
crude mortar
#

well it's just that if you change properties on the .material at runtime, it will create a new instance

#

if you change properties on the .sharedMaterial, it will not create a new instance and instead change the properties on the shared material

velvet relic
#

I reread the rules and I still wasn't for sure on where questions can be asked and if all questions pretaining to unity must go through dots form.

somber nacelle
#

don't crosspost

hallow raven
#

the using UnityEngine;

public class MoveSpriteUp : MonoBehaviour
{
public float MoveSpeed;

void Update()
{
    transform.position += transform.up * MoveSpeed *
        10 * Time.deltaTime;
}

}

#

for vr

late aurora
#

Ok

sterile elm
#

Is there any way to stop player in Air if player click button in opposite direction? Im using RigidbodyFirstPersonController from standard assets

lean sail
lean sail
#

🤷‍♂️ i cant even find the script online, but theres really only one answer to your question. Yes it is possible, you just have to code it

sterile elm
sterile elm
# lean sail 🤷‍♂️ i cant even find the script online, but theres really only one answer to y...

private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();

    if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (/*advancedSettings.airControl ||*/ m_IsGrounded))
    {
        Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
        desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
        FS.currentStepLenght = movementSettings.CurrentTargetSpeed / running;
        FS.PlayStepSounds();
        if (Running)
            Walking = false;
        else
            Walking = true;

        desiredMove = desiredMove * movementSettings.CurrentTargetSpeed;
        if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed))
            m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse);
    }
    else
    {
        movementSettings.m_Running = false;
        Walking = false;
        
    }

}

#

i think its only needed to make this 🤔

lean sail
tawny elkBOT
sterile elm
#

'''cs

lean sail
#

backticks not quotes, also what do you mean "stop player in Air if player click button in opposite direction". do you want them completely frozen in air?

lean sail
#

if you want the opposite direction of movement, i guess you could check the angle between desiredMove and the current velocity. then stopping it air depends on how u want the game to feel. You can make it kinematic but it wont respond to forces

sterile elm
#

test

#
    {
        GroundCheck();
        Vector2 input = GetInput();

        if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (/*advancedSettings.airControl ||*/ m_IsGrounded))
        {
            Vector3 desiredMove = transform.forward * input.y + transform.right * input.x;
            desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
            FS.currentStepLenght = movementSettings.CurrentTargetSpeed / running;
            FS.PlayStepSounds();
            if (Running)
                Walking = false;
            else
                Walking = true;

            desiredMove = desiredMove * movementSettings.CurrentTargetSpeed;
            if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed))
                m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse);
        }
        else
        {
            movementSettings.m_Running = false;
            Walking = false;
            
        }
} ```
lean sail
# sterile elm ```private void FixedUpdate() { GroundCheck(); Vector2 input...

read my message above this, theres probably more to consider like
how long do you want the player stopped for, should they eventually start moving in the direction of input?
you may need to ignore the y velocity when checking the opposite direction as well
Im honestly unsure if the velocity can be reliably used even, because with rigidbodies it may slide up/down slopes causing it to not be what you expect

#

it should be fine to just use the velocity (without the y component) normalized

sterile elm
lean sail
# sterile elm I wanna make it work like in tf2

then you'd probably want to look at guides which replicate source movement. i havent played tf2 in awhile but im pretty sure you dont just stop in midair in that game, which you initially described.

#

Given your response, I dont really think you've understood any of what i wrote above. I think you should ditch this old code you're using and just follow a tutorial online

ebon trellis
#

Hello, i'm trying to achive a swiming movement so i made the character move with rigidbody, and the bouncy effect script uses rigidbody too, the problem here is when the charater moves the bouncy stops till the character stops, any idea how to solve this?

crimson agate
#

What are some ways you guys limit the amount of database writes in order to limit server costs? For instance, I keep track of statistics for the player and I want to store these stats in a database, but obviously it would get pretty expensive to update the database everytime a stat increases since these will increase very often in my game.

spark flower
#

hey guys im trying to get time diffrence betwean a saved time and current time but the numbers are super big and it drops lesser numbers and i aways get a resault of 0. can someone help me?

winged flare
#

Hello I have a question, I want to have a struct or class alter the visual representation in the inspector oppn changing an enum. Besides making a custom inspector.

I have a struct called submission paper that has a list of type Answer.
Currently I have them as structs

#

Example of what I want.

latent latch
#

unfortunately the default way is to make a custom inspector

#

otherwise go grab naughtyattributes off github

winged flare
#

I see, I suppected so

#

thank you

fleet furnace
simple egret
#

Yeah save the entire DateTime as string, and DateTime.Parse() it back when loading.
Then you can subtract two DateTime and it'll give you a TimeSpan object, from which you can access seconds, minutes, days, etc.

rigid island
#

^^this or save Ticks

tropic kiln
#

Heya, I'm trying to do some procedural world generation using noise and meshes etc. I've just been trying to implement LOD into it but my triangles seem to be weirdly messing up towards the end of the iterations. My code is pretty simple but here's the problem:

private int[] calculateTriangles() {
    // Generate triangles
    int[] triangles = new int[(WorldGeneration.chunk_vertex_length - 1) * (WorldGeneration.chunk_vertex_length - 1) * 6];
    
    int count = 0;

    for (int x = 0; x < 252; x++) { // Should be [x < WorldGeneration.chunk_vertex_length - 1] - its not atm just for debugging
        for (int z = 0; z < WorldGeneration.chunk_vertex_length - 1; z++) {
            int baseIndex = z + x * WorldGeneration.chunk_vertex_length;

            // Just some debug code here
            if(x == 251) {
                if (z == 15) Debug.Log(baseIndex);
                if (z > 15) continue;
            }

            // First triangle
            triangles[count] = baseIndex;
            triangles[count + 1] = baseIndex + 1;
            triangles[count + 2] = baseIndex + WorldGeneration.chunk_vertex_length;

            // Second triangle
            triangles[count + 3] = baseIndex + 1;
            triangles[count + 4] = baseIndex + WorldGeneration.chunk_vertex_length + 1;
            triangles[count + 5] = baseIndex + WorldGeneration.chunk_vertex_length;

            count += 6; // Move to the next set of triangles
        }
    }

    return triangles;
}

Thanks very much for any help ❤️ (this has been killing me all day)

latent latch
#

I could only guess some floating point precision problems. I'd try to log a list of position (probably easier to write to text) and compare values

spark flower
tropic kiln
simple egret
#

It produces a string like 2023-12-03T15:48:35

spark flower
#

i see

simple egret
#

Consider using a DateTimeOffset instead, so time zone information is preserved when saving/loading. In that case, use the "o" format string

spark flower
#

i see

#

works like a charm

#

thanks

latent latch
# tropic kiln Shouldn't be - `chunk_vertex_length` is an int

Oh, huh. Looks like what you have there is pretty standard otherwise.

  //Indices
  for (int x = 0; x < rows - 1; x++)
  {
      for (int z = 0; z < columns - 1; z++)
      {
          int offset = z + (x * columns);
          glm::vec3 tri1 = glm::vec3(offset, offset + columns, offset + columns + 1);

          render.indices.push_back(offset);
          render.indices.push_back(offset + columns);
          render.indices.push_back(offset + columns + 1);

          glm::vec3 tri2 = glm::vec3(offset, offset + 1, offset + columns + 1);

          render.indices.push_back(offset);
          render.indices.push_back(offset + 1);
          render.indices.push_back(offset + columns + 1);

          //std::cout << tri1.x << ", " << tri1.y << ", " << tri1.z << " ~~ " << tri2.x << ", " << tri2.y << ", " << tri2.z << std::endl;
      }
  }```
This is pretty much what I do in OpenGL
tropic kiln
#

Hmm that's really strange, it literally just gets to one point and then the triangles from there go back to (0,0) on the mesh

hexed pecan
#

I suggest using something like Handles.Label in OnDrawGizmos or in a custom editor to draw the vertex indices on screen

#

And maybe triangle indices (divided by 3) in the center of each triangle

tropic kiln
hexed pecan
#

I don't see you accounting for LOD anywhere but the vertex positions. Shouldn't it affect the vertex count too?

tropic kiln
#

chunk_vertex_length = (chunk_size + 1) * lod;

latent latch
#

rather, you're doing division to a float*

#

for a position so again with the precision problem of my previous post

tropic kiln
#

Even if there is a problem there it should only effect the position of the vertex slightly right? In that case it shouldn't make a difference for the triangles as I'm just referencing their indexes

latent latch
#

I'm just observing from the picture it feels less like an algorithm problem and more of a whoops the next value truncated into a wrong value

tropic kiln
#

That's true

hexed pecan
tropic kiln
#

I'll start with that thanks

brazen estuary
#

I need some help with my camera I have a camera that rotates around the player showed in the video but lets say i only want to rotate it behind the player and when it hits the side it stops. Rn it hits the side but then i cant move it anymore

dapper carbon
#

anyone know of a way to optimize onTriggerStay or some alternative? I only need to check for one collision between objects but objects sometimes get instantiated already in contact with others, so onTriggerEnter doesn't work, but onTrigger stay is way too unoptimized

tawny elkBOT
rigid island
#

also use mp4 for videos embed

rigid island
#

like overlap or alike

#

also you can use coroutine to make your own intervals if you don't want to do it every Update

dapper carbon
#

thanks! Figured there was some way in the engine to do what I wanted but didnt know what to look for.

rigid island
#

dang..I would use cinemachine orbital camera 🧈

#

though you'd still need code for the second part

brazen estuary
brazen estuary
rigid island
brazen estuary
rigid island
#

the limit is right there

#

value range

brazen estuary
#

oh thx

rancid frost
#

I had a 2d grid map, but it has no heights.
How can i make the map have hills just as these?

latent latch
#

Either prefab a custom mesh, or if you want to apply different vertex compositions then you need to modify them directly through their vertices

rancid frost
#

I see, I wanted to avoid adding extra vertices due to performanc reasons, is there really no other way?
I had considered tesseleation and height maps, but I combine meshes of similar materials together so that is a bit difficult to pull off

latent latch
#

no one says you have to add extra verts. Use what you got and move em around (well, assuming your hexagon mesh isnt composed of the absolute minimal verts)

rancid frost
#

I am using the right one, with 4 triangles

latent latch
rancid frost
#

how many verts would you recommend per hex?

latent latch
#

If you make yourself the script to create the meshes, your alg will adjust it via values so it comes down to testing what you want later on

rancid frost
#

ok

#

thanks for the advice

latent latch
#

That's usually how it goes for the most part anyway

#

would be odd to hard code vert values when it comes to primitives, but I guess you can argue that's exactly how'd you go about making a quad ;p

rancid frost
#

what are primitives?

latent latch
#

primitive shapes

rancid frost
#

ahh

latent latch
#

stuff that's usually easy to subdivide

rancid frost
#

lastly, is there a max vert count, I probably should go past?

latent latch
#

there is in unity, but it's per mesh and you're not likely to hit that unless you're doing chunks

#

(which is something else to consider)

rancid frost
#

I am using chunks right now, definetely increase performance since I can disable those that arent in view

simple egret
#

Seems like CustomNetworkManager.Singleton returns a value of type NetworkManager, not CustomNetworkManager

#

You'd need to modify the definition of the Singleton property, or cast the value every time you need to access members on CustomNetworkManager:

((CustomNetworkManager)CustomNetworkManager.Singleton).test();
native folio
#

Ah

simple egret
#

Prefer the first (modify the definition) if possible

native folio
#

Is there anyway I can modify the definition of the Singleton property without modifying the original NetworkManager?

simple egret
#

Good question, never used that. Probably not, since it's static

#

Overrides are out of the question

native folio
#

What if I just made a new singleton in my Custom class and called it something like Instance instead of singleton

spring creek
#

You could make a SEPARATE static variable probably?
Call it Instance to avoid... ah

native folio
#

Yup lol

simple egret
#

Yeah possible

#

Instance => (CustomNetworkManager)Singleton;

#

Or marking the property with new? Can you do that on static stuff?

native folio
simple egret
#

Probably not, if it already works without. This is a computed read-only property that just gets the value and casts it

simple egret
native folio
#

Dope

#

Tysm

steady moon
#

Hi all, I've got an abstract RuntimeSet<T>:ScriptableObject class, and a TeamableRuntimeSet:RuntimeSet<Teamable> class, where Teamable: MonoBehaviour
When I serialize a field of RuntimeSet<MonoBehaviour> I expect RuntimeSets of classes that extend Monobehaviour to show up, and the TeamableRuntimeSet scriptable objects do show up, but I can't drag/select them into the field, I couldn't really find anything on it so I was wondering if someone here knows about this issue

modern creek
#

My understanding is that unity doesn't support serialized abstract classes out of the box and you need to do some [SerializeRerefence] shenannies and do your own editor drawing

steady moon
#

oh great tysm I think that's it, going to do that now

simple egret
#

Reproduced your code architecture, it's not possible to do that in C# so Unity won't be able to do it eitther

#

Cannot implicitly convert type 'TeamableRuntimeSet' to 'RuntimeSet<MonoBehaviour>'

modern creek
#

his RuntimeSet<T> is abstract and inherits from SO fwiw

#

oh sorry, you were saying you were trying that in c#

simple egret
#

You'd have to dive into type parameter variance to achieve that, which involves using interfaces, and Unity doesn't support that either lol

modern creek
#

I'd utilize the adapter pattern if you're fixed on polymorphism of your underlying c# classes.. have your classes be their own thing (unrelated to MBs and SOs) and then have MBs and/or SOs to wrap them

#

I'm actually pretty far into a project that's doing the polymorphism thing and.. I keep the polymorphism away from unity

simple egret
#

Yeah it was not made for polymorphism, but more for composition and other design patterns

steady moon
#

ahhh gotcha, adapter seems pretty straightforward, ty!

modern creek
#

it's a tile based game.. but in unity i .. don't want to have the inspector/editor have to figure out too much, so I just manually have an initalize method that I call programmatically and pass it whatever, and it can figure out what to init/display accordingly

#

then all my behaviour management is stuff like "if tile is IMoveable, move it" or "if tile is IDestroyable, destroy it" or whatever

#

every specific tile inherits from the abstract parent class and just gets all the default behaviour (like a constructor that sets the id, location on the grid, etc) and it just implements the "tile-type specific" behaviour.. like maybe one tile moves erratically or not at all each turn, maybe another can only be destroyed by another certain tile type, etc

steady moon
#

a lot of the stuff I have already depends on serialized stuff i.e. an enemy has an Teamable:MonoBehaviour, ITeamable component plus a couple other to manage health/pathfinding/alerts so I'm not sure i could make it work without a bunch of refactoring but that sounds interesting, probably keep it in mind for after the semester

surreal geyser
#

I'm trying to make a slippery floor on one of my tilemaps so that everything placed by the tilemap should be slippery. It doesn't work, I've already tried to work with materials that have 0 friction, it doesn't work and I've already tried to code it with the help of the internet but no matter how I code it, either everything is slippery or it doesn't slip at all. Is there an example code I can use or a component I can use?

jagged snow
#

I want to have a transform stop moving when it hits a wall or something is in front of it, should i use a raycast or boxcast in this situation? It could be like a leaping dog.

vagrant blade
#

Either works. Depends what shape you want the cast to be. They both do the same thing after that.

rigid island
#

so you only deal with their collider/physics material separate

#

not sure anything else is code related

short osprey
#

https://pastebin.com/FZcuvqWp

Hi all. im a little confused. As far as i understand, animations triggers fire off, then get disabled until they're fired again. However, in this case that doesnt seem to happen:

  • it doesnt seem to transition through any of the triggers (i hooked the dash animations to any state wih the corresponding trigger param as their sole condition)
  • dash end seems to trigger 24/7 even hen not dashing

Does anyone know why?

rigid island
#

holy shit pastebin sucks ass

#

half the page is taken up by other people's scripts

short osprey
#

didnt wanna omit info that might be helpful lol..

surreal geyser
rigid island
short osprey
#

coming from regular software dev to this is surprisingly difficult, im not even rlly aware whats wrong

#

hmm maybe

rigid island
#

I would debug the animator first

#

select the object that has the animator in playmode you should be able to see if trigger stays on or not

short osprey
#

ye i did

#

it never turns on, even tho the message right above it does log

rigid island
short osprey
#

except dash end

#

i just saw the time tho, ill have to take time for it tmrw

#

its almost 2 am 💀

surreal geyser
surreal geyser
astral oriole
#

General question, is there a simple function to static batch objects that are instantiated? I have larger objects that spawn later and they aren't being batched

lean sail
#

Is there a nice way to get (deterministic) random points on a certain NavMeshSurface? Currently im using NavMesh.CalculateTriangulation();, then get a random vertex, and then NavMesh.SamplePosition. but it appears that the triangulation itself is not deterministic when there are multiple surfaces. It seems to just cycle between a few different possible lists.
I was thinking of some options:

  • generate the list once while only having 1 surface active, store that result on some script in every scene. This seems quite tedious though if i want to make changes
  • make a script on some GO which acts as spawn points, manually input some bounds, then randomly choose a point and sample the position onto the navmesh. Seems better but then ill have to make the sample position maxDistance large enough to account for any bounds.
    Just looking to see if anyone has thoughts about what I should do
surreal geyser
#

I tried different codes and they dont work. Im tryng to make a script that I add to my slipperyTile and Im tryng avoid to much change and adding of stuff in my player controls script. Can u help me make some code for the Slipperyeffect? (im new to unity and programming idk if I should have written this in Code beginner)

swift falcon
dull glade
#

I don't need to worry about Time.delta time when I'm using physics like: rb.AddForce(Vector2.up * ampSpeed, ForceMode2D.Force); right?

lean sail
surreal geyser
# swift falcon What player controller are you using?

I don’t know if player controller is the right name, I made the controls myself. I made like most probably do(with Tutorials/Internet) the controls with vector. I made that you only jump when there’s a ground under you and I added coyote jumping also(jump still possible for a short time after touching edge of platform) also I added with tutorials Jump higher function when u hold and shorter when u just tab quickly. I put also the animation and sounds in controls code. I also gave my player 0 friction bc I saw in a video it stops the player from getting stuck when u jump and run against a wall.

#

I don’t know if any of that stuff influences slippery tilemap I wanna add.

swift falcon
#

It depends on how your character moves already as there's many different ways.

surreal geyser
#

I copied those vector lines from tutorials I don’t fully understand it. Should I paste it in here?

swift falcon
#

You don't really want to conflate the methods

#

Yea

surreal geyser
#

Wait a min

#

private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");

 if (Input.GetButtonDown("Jump"))
 {
     jumpBufferCounter = jumpBufferTime;
 }
 else
 {
     jumpBufferCounter -= Time.deltaTime;
 }

 if (coyoteTimeCounter > 0f && Input.GetButtonDown("Jump"))
 {
     jumpSoundEffect.Play();
     rb.velocity = new Vector2(rb.velocity.x, jumpForce);
     coyoteTimeCounter = 0f;
     jumpBufferCounter = 0f;
 }

 if (IsGrounded())
 {
     coyoteTimeCounter = coyoteTime;
 }
 else
 {
     coyoteTimeCounter -= Time.deltaTime;
 }
 if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
 {
     rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
     coyoteTimeCounter = 0f;
 }

 UpdateAnimationState();
#

this are the controls and the next method is where the animations are handled

#

wanna see that too or is here maybe the root of the problem?

#

forgot this private bool IsGrounded()
{
return Physics2D.CapsuleCast(coll.bounds.center, coll.bounds.size, CapsuleDirection2D.Vertical, 0f, Vector2.down, .1f, jumpableGround);
}

swift falcon
#

So you have a rigidbody controller. These are perfect for physics interactions.

leaden ice
#

!code

tawny elkBOT
surreal geyser
surreal geyser
swift falcon
#

I see nothing that sets your X velocity

#

it's declared as dirX but I see no instances of it

#

I'm going to assume if physical materials don't work, that there's code somewhere that dictates if grounded + not "holding A or D" velocity is set to 0.

#

Ctrl+F and highlight everything that mentions "dirX" and have a look

#

This is where the fun of making something both slide and stop on slopes comes in

surreal geyser
#

Well I’m right now not home. Can we continue this conversation later? I will take look into my code when im back home. I may have made code that influence the material of the player maybe.

swift falcon
#

🤔

pseudo jungle
#

i cant ask for help?

swift falcon
#

help, yes.
pay someone to do it for you, 🤔

pseudo jungle
#

i can find a way to do it

#

i have been struggling for weeks and stressing and i gave up

dusk apex
pseudo jungle
#

the link doesnt do anything

dusk apex
#

!collab

tawny elkBOT
dusk apex
#

These are the links.

ebon apex
#

hey so im trying to check if the camera can see the player or not and i use a raycast. now even though the player is behind a wall the camera still returns true... is there something im doing wrong here?

swift falcon
#

You're casting the ray with playerMask

ebon apex
swift falcon
#

that means the ray will collide with only the player and not the walls

swift falcon
#

you'd need to add walls to the layermask and then a separate check for if the object it hits is the player

ebon apex
#

oh waIit so it will ignore the walls?

swift falcon
#

you can use this same strat to add glass to a separate layer that is not on the cameras layermask so the beam will ignore glass and detect you

astral blade
#

Can someone help with making a parallax? I'm trying to use Dani's tutorial, but i cant get the objects to reappear, once gone off the screen.

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

public class Parallex : MonoBehaviour {

    private float length, startPos;
    public GameObject cam;
    public float parallexEffect;

    void Start () {
        startPos = transform.position.x;
        length = GetComponent<SpriteRenderer>().bounds.size.x;
    }
    
    void FixedUpdate () {
        float temp = (cam.transform.position.x * (1-parallexEffect));
        float dist = (cam.transform.position.x*parallexEffect);

        transform.position = new Vector3(startPos + dist, transform.position.y, transform.position.z);

        if      (temp > startPos + length) startPos += length;
        else if (temp < startPos - length) startPos -= length;
    }
}

#

I think its because i dont have the object in the sprite renderer,

#

its like this instead

dull glade
#

Ok so this is what I got, I basically want the ship to play a different animation if it is moving perpendicular and in a certain direction from its current orientation as the digram shows. Not sure how to setup the math to get this working.

pale spindle
#

Good morning, hope all is well. Is there anyone who is good with the Slider control in the UI? I have 2, one for music, one for sfx. Audio Mixer works fine so the sounds are there but the sliders do not reflect the volumes. Not sure if anyone can assist in #📲┃ui-ux or not.

hexed pecan
#

For example, Vector3.Dot(transform.forward, rb.velocity.normalized)

#

Or Vector3.Angle

#

If it's 2D then you probably need to use transform.right/up instead of forward

#

With dot, moving sideways will give you 0

#

Backwards will give you -1, forwards is 1

late lion
pale spindle
#

I posted the entire thing in #📲┃ui-ux if you can check it out, I appreciate it.

#

Also its a 2d game so doesnt need crazy things

dawn nebula
#

What's the standard practice for teleporting a rigidbody with interpolation?

swift falcon
#

Interpolated teleporting?

#

So flying?

#

usually lerp timedeltatime if it's what i think you're asking

dawn nebula
#

I just want to teleport the object to some new location.

#

Effectively ignoring interpolation for that movement.

swift falcon
#

like Praetor said

dawn nebula
#

Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings.

#

But I don't want this.

#

Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.

#

alright then

swift falcon
#

I always thought that was readonly

#

🤯

dawn nebula
#

The transform will be updated after the next physics simulation step. That's kind of a pain.

#

Kinda wish setting the transform would just... disable interpolation for that frame.

hard viper
#

setting rigidbody position is very useful

#

it’s like moving the transform, but all the colliders and rb internals get updated

leaden ice
#

If you don't, then just use RB.position

hard viper
#

why can structs not inherit?

swift falcon
#

They go into detail here

#

It's essentially to do with value types in .NET

leaden ice
vapid condor
#

structs can inherit interfaces tough

leaden ice
#

implement, not inherit

vapid condor
#

yeah my bad

hard viper
#

i just imagine the compiler could just try to define a value type of a child struct by getting together all the methods/fields, and creating the structure for the child value type

#

but i guess that just isn’t how it works

leaden ice
#

No inheritance means the memory size of the struct is known at compile time

hard viper
#

that makes sense if you have a class inheritting from a struct, but if you have a struct inheritting from a struct, then the compiler should be able to figure out the size of a derived struct. it would be a compile-time const

steep herald
#

There's a version of physics2d.raycast that returns a raycasthit2d. How is this meant to be used in order to check whether or not there was an actual hit?

See if the transform contained is null?

hard viper
#

sizeof(Child) = sizeof(Parent) + sizeof(Child’s fields)

leaden ice
#

Which won't be possible

hard viper
steep herald
hard viper
#

you don’t usually want to use Raycast tho, imo. It is more common to use one of the nonalloc methods that grabs an array to populate a collection. this way you can sift through/filter results

#

those methods return an int as the number of hits

steep herald
#

are they ordered ?

hard viper
#

no

#

if you output to a list, you can sort the list based on whatever criterion

#

such as by distance

steep herald
#

ah hit.distance is exposed

#

Okay, sweet

#

thank you

hard viper
#

👍

hard viper
#

ty

hard viper
#

the cost for a single boxcollider .Cast is almost the same as a single Raycast call

vapid tinsel
#

Can someone explain this error?

#

For context, I'm trying to mod a game by replacing the player model

fervent furnace
#

We ask that you do not:
• Directly discuss modding or decompiling.
read the community conduct

hybrid quarry
#

Hello - I have a game published to Android + iOS but for some reason my iOS version makes users restore purchases each time they open the app. I'm trying to figure out why this is and would love some feedback on my In App Purchases (IAP) layout. There's only one IAP which is a full game upgrade. Thank you!

hard viper
#

this isn’t a coding question

radiant marten
#

I have a world that I'm trying to render in isometric, blending 3D and 2D. I found using the camera at an isometric angle introduces a lot of pixel jitter and other subpixel issues due to the math of the camera being rotated. One solution I have found is rotating the world itself fixes every single issue I have, keeping all the objects on a nice, aligned, 2D plane for the final render. The only concern with this is that it makes workflow pretty unintuitive since the engine is obviously not designed for worlds to be rotated. What would be the best way to rotate the entire world(in this case a nest of GameObjects all under a single "Terrain" parent object) in a way that is only visual, during runtime? Methods I've tried:

  • RenderPipelineManager.beginCameraRendering and rotating the gameObject during render and then undoing the rotation at RenderPipelineManager.endCameraRendering. This has gameplay implications though as it rotates the entities around they don't always end up in the same position in the world as their pre-rotated counterpart. Using a navmesh for example, a character may be at the top of the stairs in the editor but during runtime as the object tries to find itself among the navmesh, snaps it to the bottom of the stairs.
  • Shaders. I know shaders don't have any effect on things at a gameplay level, but I'm not sure how to rotate an entire nest of objects on the same pivot(aka keeping the whole world together as it rotates) since all the objects will just rotate around their own pivot instead of their parents.
    Any advice would be greatly appreciated
polar marten
radiant marten
#

2d pixel art in a 3d isometric world

polar marten
#

there is an asset called Ultimate Isometric Toolkit which includes a simple sprite material to orient the sprites towards the camera and pixel-align them

#

which is all you need. you should definitely lay out your world naturalistically in the xz plane, and orient your camera in the projection you need (isometric, although you probably mean dimetric 2 x 1)

radiant marten
#

I have the sprites orienting fine, but if the camera is not perpendicular to an axis it introduces a ton of jitter that I have not found any asset able to resolve

polar marten
#

are you trying to use the pixel perfect 2d script from unity?

#

the asset i am discussing resolves pixel alignment issues in the absence of pixel perfect 2d, which you cannot use

#

for a non-orthonormal projection

radiant marten
#

I've tried the pixel perfect camera, I've tried a few assets that are supposed to do it. While they all alleviate the jitter to a degree it's never to the precision I need

polar marten
#

i am saying you cannot use it

radiant marten
#

I said I've tried it, not that I'm using it

polar marten
#

gotchya

#

well that's all you have to do. the asset is $30. you shouldn't do any of the stuff you are discussing, although you could try authoring the shader it uses

radiant marten
polar marten
#

this is coming from someone who makes a dimetric pixel art game

radiant marten
#

and it helps, but it's still there, just less so

polar marten
#

do you have a screenshot of you game?

radiant marten
#

unfortunately under an NDA so I can't post much about it

polar marten
#

the problem you are describing cannot be solved in a general way

#

which is perhaps valuable to know

#

however, you don't need jitter at all

radiant marten
#

well like I said, rotating the world solves everything. I just can't figure out how to rotate it in a way that does not effect the game

polar marten
#

because you don't need to enforce alignment

#

you know, go ahead and do that then

#

I just can't figure out how to rotate it in a way that does not effect the game
so you see what i mean by not general

radiant marten
#

shaders seem like the go to but I can't seem to rotate entire nests of game objects around a single pivot

polar marten
#

can you show me an example of a commercial shipping isometric pixel art game built in unity that lays out the world naturalistically in 3d and attempts to align every art pixel exactly to a canvas pixel?

#

you will not be able to find one

#

my suggestion is to not do that, because no one will notice

radiant marten
polar marten
#

it cannot be done in a general way. however, the ultimate isometric toolkit does it 95%

radiant marten
#

I'll get a screenshot once I swap out sprites

#

annoying unity gets hung up in the package manager all the time now

polar marten
#

so let me explain why this cannot be solved in a general way

#

for starters, this can't be solved in a general way with an ordinary orthonormal pixel art game either

#

the problem is just a lot less pronounced

#

as long as you want to do something in floating point and that's moving, like physics, a general approach has to have an answer for how to align a piece of art to the screen in a way that interacts correctly with another piece of art. if things can have non-integral speeds with respect to screen space, which is always for dimetric projections and frequent for ordinary orthonormal projections, you will have one of jitter, stretching, or irregular pacing

#

you don't see pixel alignment issues in retro games, but they have all painstakingly eliminating movement pacing issues, primarily by not using naturalistic physics at all

#

you can't have no issues because, you know, the rules for Ideal Pixel Art world can't be reconciled with naturalistic physics

#

do you know what i mean by irregular pacing? like characters have to move an integral amount every frame to appear to be moving smoothly with constant velocity, but with naturalistic physics, a speed of 2.5 pixels per frame means sometimes it moves 2 pixels, and sometimes it moves 3. it's just that with a dimetric project, it is always moving a non-integer number of pixel art canvas pixels per frame, whereas with ordinary 2d projection, you can control it

radiant marten
#

the issue is that in 2D you can easily round floating values for precision. But because of the math involved with a rotated camera you can't just round stuff. As you walk around, sprites get rounded at different alignments to your character/camera due to depth/rotational math etc

polar marten
#

what people do is they do not align to the pixel art canvas while objects are moving, which includes when the camera is moving, so the answer is sort of that they don't stress too much about alignment at all

#

yeah i agree with you there is no general way

radiant marten
#

so even snapping things into position in screen space doesn't really matter because things like this:

polar marten
#

you should not try to align generally

radiant marten
polar marten
#

i think this looks good

radiant marten
#

it doesn't look good though, none of the pixels are aligned and as you move, due to this, everything wiggles

polar marten
#

don't try to align while things move

radiant marten
#

that's why rotating the world works so well, I just need to find a way to rotate it with a shader

polar marten
#

which means don't try to align

swift falcon
#

teenage mutant ninja turtles 🐢 the game

polar marten
polar marten
radiant marten
#

well I've been messing with this for half a year

#

here is a view with the camera rotated

polar marten
#

yes, that is what i mean by movement pacing issues

#

it doesn't matter how the world is rotated

#

if you rotate your world, as you're describing

#

and in order to not have movement pacing

#

you will have to use different physics altogether

#

you will still have these problems with 2d sprite physics

#

because the underlying issue is that there's no general way to reconcile a non-integral amount of motion per frame with an aligned pixel art canvas

#

you have to choose your demon: either you have movement pacing, jitter or non-natural physics

#

imo, do not align

#

you don't need to align

#

nobody notices alignment issues

radiant marten
#

this is very noticable

swift falcon
#

even Ubisoft releases games with animations jumping between 30 and 60 fps

radiant marten
#

here is the world rotated

swift falcon
radiant marten
#

and here is the final render

swift falcon
#

it's the same with every artist and their work. it's the drive for perfection

#

perfection is not ascertainable

polar marten