#archived-code-general

1 messages Β· Page 23 of 1

main shuttle
#

Nothing changes the position of the camera? Why would you think it moves?

atomic wasp
#

if the camera is a child of the player, try rotating the player first

grim marlin
#

The camera follows the player, it's not a child

#
void LateUpdate()
    {
        if (isFirstPerson)
        {
            currentOffset = Vector3.Lerp(currentOffset, firstPersonOffset, smoothSpeed);
        }
        else
        {
            currentOffset = Vector3.Lerp(currentOffset, thirdPersonOffset, smoothSpeed);
            target.rotation = Quaternion.Euler(transform.rotation.x + thirdPersonXRotationAngle, transform.rotation.y, transform.rotation.z);
        }
        transform.position = target.position + currentOffset;
    }

Got this second script on the container of the camera

main shuttle
#

So you are already moving the camera by code. Then you need to add logic there that it orbits the player.

grim marlin
#

exactly

#

But I don't see how to do that

fiery oracle
#

related more to coding, when the lady keeps saying we are "loading" in the Firewatch open world video, does she just mean setting objects active / inactive?

atomic wasp
# grim marlin exactly

I would calculate the ideal camera position in player transform space, and then lerp the camera there

swift falcon
#

Can I make prefab Variants from/of prefab variants?

atomic wasp
main shuttle
grim marlin
main shuttle
grim marlin
#

I'll start with that thanks !

shut sky
#

while executing the task wont go further than first Log, no exceptions or anything

leaden ice
#

with no log/error/etc

#

in this case - calling GetComponent is your crime.

shut sky
#
            Debug.Log($"Message received: {e.Data}");
            var resp = ServerStatusResponse.CreateFromJSON(e.Data);
            Debug.Log($"[{resp.packetType}] [{resp.body.status}]");
            if(resp.body.status == "OK"){
                Debug.Log(resp.packetType);
                Debug.Log(resp.body.status);
            } else {
                Debug.Log("Failed to check");
                await ShowFailText();
            }
        };

how should I implement this feature then, I've found out that coroutines do not work either in event calls

leaden ice
#

what is ws?

shut sky
#

WebSocket from WebSocketSharp

leaden ice
#

Signal the main thread from here

#

and have the main thread show the error message

#

Easily done if using UniTask for example, or easily hacked together with a ConcurrentQueue

shut sky
#

if I use UniTask and call its methods from event call it will handle everything for me in main thread?

fiery oracle
#

as long as you don't use threading in the main thread

#

unity is not thread safe, so you can't make any calls to the unity api from threads other than the main thread

leaden ice
#

I don't remember what it's called exactly

shut sky
#

await UniTask.SwitchToMainThread(); thx, I'll try

leaden ice
#

yeah that thing

karmic bloom
#

Not sure if this is the right area or not, if not please point me to it.

I have a menu prefab that holds some scripts, well I’m carrying through scenes using DontDestroyOnLoad except with it being a menu prefab it has to be enabled at all times in the inspector or the other scripts in the new scene trying to use it can’t reference to it. Is there a way for me to SetActive vs SetActive to false and still be able to reference it to?

The simple solution I can think of is to just make another script that I can attach to the objects in the new scene that just calls functions from the prefab.

(I may also be wording this poorly) please let me know. Thanks

leaden ice
#

rather than using FindWithTag or whatever you're doing

karmic bloom
#

Okay.That’s what I figured is the best solution

#

Thanks

shut sky
rustic ember
#

How do I get a Quaternion rotation that is pointing in the direction of a vector?

leaden ice
rustic ember
leaden ice
#

Assuming myVector is a direction vector and not a position vector

heavy nexus
#

how can I rotate a gameobject along its axis

leaden ice
heavy nexus
#

z

leaden ice
#

and do you mean around an axis?

heavy nexus
#
        {

            Ship.transform.position += Vector3.right * 10 * Time.deltaTime;

            

            
            float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
            float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;

            Quaternion target = Quaternion.Euler(tiltAroundZ, 0, 0);


            transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
            

        }```
#

yea

#

I have that, it nearly works though

leaden ice
#

Quaternion.Euler(tiltAroundZ, 0, 0); the first argument here is the X axis

#

not Z

heavy nexus
#

ahhh

leaden ice
#

x y z

#

note these are global axes too

#

the way you're doing it

heavy nexus
#

ah

#

how can I make them not global

leaden ice
#

what are you trying to achieve here

heavy nexus
#

when I press A, rotate the gameobject left a lil

leaden ice
#

"rotate left" is meaningless

#

you can only rotate around an axis

heavy nexus
#

barrel roll left

#

roll left around the x axis

leaden ice
#

transform.Rotate(0, 0, degreesToRotate);

#

x or z figure it out

heavy nexus
#

okay that works better

#

is there a way I can limit it to degrees to rotate or smth

ebon steeple
#

How would I enter a variable that with a type of "Type" (confusing πŸ˜… ) here?

    {
        if (itemType.IsSubclassOf(typeof(ItemFramework)) && !itemType.IsAbstract)
        {
            go.AddComponent<typeof(itemType)>();
        }
        else throw new Exception("Given Type is not a subclass of ItemFramework or is abstract.");
    }```

Specific code snippet: 
```go.AddComponent<typeof(itemType)>();```
simple egret
#

Don't cross-post

#

Use the overload of AddComponent that takes in a Type as a parameter

jaunty needle
#

Why isn't this working

ebon steeple
simple egret
#

go.AddComponent(itemType)

ebon steeple
#

thanks!

#

yep works, again thanks!

potent sleet
simple egret
potent sleet
#

the resultof v2 distance is float

earnest meteor
#

Can someone explain me pls why 11 line is not working. I chose necessary layer in script and set the same layer for gameObject.

simple egret
jaunty needle
#

Ok so I have this piece of code that I want to calculate a direction and a force based on the distance of an arrow that the player chooses and I want the distance to determine the magnitude of the force but I'm pretty sure I shouldn't be multiplying by distance here...

                Vector2 direction = (mousePos - (Vector2)transform.position).normalized;
                float distance = Vector2.Distance(planet.transform.position, mousePos);
                Vector2 setVelocity = direction * distance;

                planet.GetComponent<CelestialBody>().initialVelocity = setVelocity;
#

Visualization

earnest meteor
simple egret
rustic ember
#

Basically I need to rotate the rotation around the blue arrow until the green arrow is straight up. I have no idea how though.

rustic ember
#

Afterwards multiply by a speed parameter

#

Not sure I understand your question

jaunty needle
#

Basically the player can control the length of the arrow above

rustic ember
jaunty needle
#

and the length determines how much the planet will be launched by

rustic ember
#

Oh I see. Then multiply

#

No problem there

#

If mousePos is in world coordinates of course

jaunty needle
#

it is

#

wait

#

yeah it is

proven plume
#

You may want an extra multiplication factor (or even a curve to evaluate against) if you want to have more control over how the distance affects the velocity. It depends on what you want the relationship between distance and launch velocity to be.

jaunty needle
#

the problem is the force isn't noticeable

rustic ember
#

A float value

jaunty needle
#

Alrighty imma try that

#

Yeah for some reason it's straight up not applying

atomic wasp
#

For anyone wondering, I have fixed my problem with modifying skinned mesh in runtime. In order to avoid changes to source asset you have to do this Mesh projectMesh = _skinnedMeshRenderer.sharedMesh; meshInstance = new Mesh(); meshInstance = Instantiate(projectMesh); _skinnedMeshRenderer.sharedMesh = meshInstance;

rustic ember
rustic ember
jaunty needle
rustic ember
#

We have 5 "shared servers" lol

jaunty needle
# rustic ember Can you send a screenshot of the complete script?
jaunty needle
#

I think there is an issue with the celestial body script cuz the initial velocity in the inspector is appearing but it's not getting applied

rustic ember
#

or UpdatePosition

jaunty needle
#

Oh yeah that's being called in a different script dw

rustic ember
#

Try making them serialize fields

jaunty needle
#

Alrighty I fixed it

rustic ember
#

What was the issue?

jaunty needle
#
    {
        currentVelocity = initialVelocity;
    }
#

I just call this function from my planetspawner script

#

and it sets the velocity

rustic ember
#

Oh you just never applied the initial velocity?

#

The rest works?

jaunty needle
#

Yup, except there is some wonkiness with the direction when the arrow is too close idk what's up with that

#

I'll send a video

#

acc nvm my pc is dying rn

rustic ember
#

Ahah ok

#

How do I make sure that the red red arrow is always pointing strictly to the side while the blue arrow still faces the blue sphere? I am assuming that this is what causes the whole flying off into space bug

#

Currently I am using Quaternion.LookDirection(blueSpherePos - yellowSpherePos)

#

I will just use a workaround instead I think

olive berry
#

how do I rotate a lowercase q quaternion 90 degrees in one x y or z direction?

#

okay off to my job at the scientific research lab, Thanks everyone ahead of time for thinking of trying to answer.

jaunty needle
#

For some reason the direction works half of the time

leaden ice
wide burrow
leaden ice
#

well yeah Unity.Mathematics is modeled after HLSL

#

so it's mul(q1, q2)

#

which is how you do it in hlsl

wide burrow
# leaden ice so it's mul(q1, q2)

Which is stupid imo.
mult(q,q)
q.mult(q)
q * q

Are all functionally equivalent. Back then it was a case of language restrictions and optimization. That isn't the issue today

leaden ice
#

They wanted to make it comfortable for shader programmers to use

wide burrow
#

They still should allow both options

leaden ice
#

Β―_(ツ)_/Β―

wide burrow
#

But I am glad they added swivel support

rustic ember
jaunty needle
wide burrow
# jaunty needle This is what I was talking about

My guess is that you aren't properly setting your initial movement vector.

Since directionVec = pos_final - pos_initial I bet you are using the wrong position. Like maybe your previously created object? That or you are making your movement vector based on some local rotation

jaunty needle
wide burrow
#

Or maybe some wrong rotation vector math?
Heavens know I've messed up way too much vector math in unity

jaunty needle
#

I don't touch rotation though

wide burrow
#

Oh didn't see the script. Lemme check

#

I would recommend using more variables for clarity.
Like:

//after mouseclick
var finalPosition= ...;

Anyways I think line 89 looks wrong. I don't know why you are taking transform.position, since that's the position of the script object

jaunty needle
#

I have done this exact single mistake 3 times now

wide burrow
#

Good variables names help

jaunty needle
wide burrow
#

Just takes practice. I've made the same mistake too many times myself

#

To be more specific, I like to define the names of all the variables I think I'll need at the start (even if I don't how how to calculate their value) and then work with setting them

jaunty needle
#

Oh yup, for me sometimes I don't even know what those are so I'm still working stuff out lol

#

Anyways thanks a lot!

rugged canyon
#

Hey! I want to learn how to build a chunk system but i dont know how it does work in unity - so my thoughts about that were that every time the player moves into a new chunk there will be a foreach() loop and forech chunk which is not in a certain distance to the player it will be setActive = false -> my question now is: is this how you do it or is there a more performant way of chunk loading because if there are like 10000 chunk objects i think it could be very inperformant - thanks for your replies

leaden ice
#

there's no reason at all to loop over 10000 things

#

also SetActive is not really the relevant thing. Your chunks should not be in the scene at all until you get close enough

faint scroll
#

Can someone tell me why this is happening? Its always when its pointed to the right and has positive angle velocity, i am rotating it with rb.AddTorque()

rugged canyon
leaden ice
#

you can store generated chunks however you wish - as long as it's not in memory

#

throw them in a file

#

or a database

#

or whatever

rugged canyon
leaden ice
wanton obsidian
#

Player slows down when facing down

somber nacelle
#

because you are moving based on the camera's transform.forward rather than the player body's transform.forward so you are smashing your player into the ground since your camera is pointing at the ground as opposed to moving forward

#

also you need to configure your IDE because there is a suspicious lack of highlighting for unity types and methods

#

!ide

tawny elkBOT
wanton obsidian
#

Ive tried doing those, they still dont fix anything ;-;

#

Thank you though!

somber nacelle
#

tried doing what, moving based on the player's transform.forward instead of the camera's? because that will work provided you didn't do something silly like make the player a child of the camera

thick socket
#

I've got no clue why it isn't working

wanton obsidian
#

Ahh, no I meant the IDE stuff. But it worked when I look down the player moves but it also doesnt actually go the way its meant to. XD

somber nacelle
dapper schooner
#

Can anyone point me in the direction of some tutorials or info on blend shapes in unity? But not with faces, I am trying to have a sphere morph into different shapes. The sphere and the shapes will come from 3ds max models

thick socket
#

Daily reminder to not be dumb and put repeating coroutines into start and not update 😭

plush sentinel
#

Any chance to get unity employees to look at the PR's? Or is there a replacement maybe?

thick gale
#

"Update about the state of the project: This project is based on Unity 2018.3 and no longer being actively maintained." from your link

#

Unity has a lot of projects, and is always working on something, when they release newer versions of unity, there are lots of changes that would need to be made to all previous projects to keep them up to date.

digital meadow
#

Does anybody know a easy way to implement air strafing?

leaden ice
plush sentinel
#

Found the FPSSample very interesting because of the included netcode, anyone have a recommendation where to find something similar that is... Easier to compile and run?

balmy schooner
#

Does anyone know how to make a fane object appear to fade away, I feel like you'd use its alpha value but I don't know how to code it to decrease it gradually

balmy schooner
#

Thankyou very much

ancient cloak
#

i've got a question regarding AotHelper, i'm trying to write a system that will basically enforce AoT compilation of types that i try to deserialize so that way we don't need some convention solution in order to hack around it

#
// Relevant code portion
string json;// has some value
List<Foo> deserializedList = JsonConvert.DeserializeObject<List<Foo>>(json);
// this would cause the Aot compiler to strip List<string> unless it's specified elsewhere
AotHelper.EnsureType<List<string>>();
AotHelper.EnsureList<Foo>();
// Would these achieve the same goal, or would not using EnsureList be a problem?
#

i know ensurelist does multiple ensures under the hood, that's not the question though

#

for them to have different code they have to be different scripts

#

is that really your question? how can i have two things with different code?

safe quiver
#

Why can I change Name in the inspector but not code?

pearl radish
#

If you're trying to change it in GlassPistol, you need to write the code inside a method

safe quiver
#

Thanks!

left narwhal
#

anyone got experience with a* algorithm?

unreal notch
#

Hey, working on a 2D metroidvania
I want to make some collectible coins that are physics enabled, that get sucked towards the player when they are close enough.

I can think of a couple ways to do this, such as doing a circle raycast to check if the player is in range, but doing that on every spawned coin seems inefficient/potentially lag inducing... is there a cleaner way to do this?

vivid wind
#

I have a Class with a List<ObjectModel> , is there any way to reference an existing model via the Unity editor? I only see an option to Add a new element and then I have to fill it out by hand.

left narwhal
#

thanks for referencing a website that i have no use for

somber nacelle
#

yes, that's the point

somber nacelle
somber nacelle
left narwhal
#

bro

somber nacelle
#

just fucking ask your question jesus

left narwhal
#

fuck off

#

anyway

vivid wind
#

Basically the Scriptable object with a list<Gems>. But the editor UI only lets me add a new element to list and edit the values manually. Is there a way to reference existing scriptable objects rather than assemble new ones in the editor interface for the list?

unreal notch
# left narwhal i havent asked my question yet though

the problem is by asking if anyone is familiar with a*, you are asking someone to engage and commit to answering your question before even knowing what it is. Just ask your question, if someone is familiar with a* AND has an answer to your question, they will answer

#

adding me to friends to potentially get an answer from me is exactly the thing you should NOT do

somber nacelle
#

the irony about them getting pissy about being told to just ask the question instead of asking for someone familiar with a* is that i actually am familiar with it lmao

left narwhal
unreal notch
#

well then guess you'll never get an answer from me πŸ˜›

#

in any case

left narwhal
unreal notch
#

now hes assuming my skill based on a question i asked πŸ˜›

#

I know a few ways to do what I asked, I'm asking how to optimize it to be efficient

#

I am admittedly not super familiar with the capabilities of unity's built in physics because I dont use it for much, I wrote my own simple physics for player and enemy movement

vivid wind
unreal notch
#

oh yea, thats how to collect the object, thats no issue though

#

oh wait, you're suggesting using a collider in place of a circleCast I see

#

yea, that'd probably work

#

on enter, trigger some change in the physics that causes it to attract to my players hitbox

vivid wind
#

Yes, so, you could have one collider and just check vector diff (distance) to see if it's close enough yet to pickup, otherwise move a bit closer to player.

somber nacelle
#

honestly i'd just overlapcircle from the player so the player detects the objects and applies any force to them rather than relying on collision/trigger messages

vivid wind
#

something like that.

unreal notch
#

I'll give that a try

#

thanks

somber nacelle
#

make that its own component and you can enable/disable the behaviour as needed too

unreal notch
#

that makes it easy to adjust the suction range too

left narwhal
#

I'm using A* for finding the most efficient path between two points. I have a situation where the G cost causes it to be inefficient (needing 10 to 20x more checks than setting the G cost to 0). In the image the red square is the start and the green square is the goal. As visible in the picture the F cost is now unnecessarily high. The code is all functioning as per the algorithm, using euclidean distance for G cost and manhattan for H cost.

vivid wind
unreal notch
fluid lily
#

Wait can I not make a wrapper of MonoBehavior? Like have a class inherit a class that inherits MonoBehavior?

#

I know for a fact I have done that in the past, but currently I am getting an error when trying this.

#

Wait nevermind, I had a class below the MonoBehavior class in the same file.

olive berry
wide burrow
olive berry
#

But I looove the snark in old scientists... Hamilton made em after he did his good stuff, like they're rock stars terrible sequel album

#

And makes a dig at Maxwell's Equations,lol.

olive berry
wide burrow
#

Sometimes I think mathematicians live in their own little world...
One of planar geometry and quadratics

olive berry
#

See we all go to school to learn how to do math.

steady moat
olive berry
#

But only a Mathemetician can PROVE 1+1 =2

wide burrow
#

If math is so complicated, why is it only built on top of like 2 assumptions?

olive berry
#

take care, I'm out, so much appreciated

#

can has appreciation so doge

mental rover
jagged pilot
#

Hi guys, I have two videos here. The first video, which you should start watching at 15 seconds, shows the movement I'm trying to make for each character. The second video, which you should start at 17 seconds, shows the movement I've created so far.
The movement I created assigns a direction for each instantiated character to move in, when instead I want to make all of the characters that are from the same prefab move in the same direction. Any ideas on how to do this?
The movement in the second video is choppy because I'm recording, it's not normally choppy.
Here's the code for the movement: https://gdl.space/apaxolujof.cpp

swift falcon
#

I am using unity fps microgame. No matter if I enable/disable invert y axis, it is still inverted. I do not know why. Even if I remove the invert code completely, it is still inverted. Any ideas?

                float i = isGamepad ? Input.GetAxis(stickInputName) : Input.GetAxisRaw(mouseInputName);
                // handle inverting vertical input
                if (InvertYAxis)
                    i *= -1f;
leaden ice
#

or you are not properly enabling/disabling InvertYAxis

solemn raven
#

hi , does anyone knows what that error means ?

leaden ice
#

access static things with the class/type name

#

not an instance reference

#

you are doing:
someParticularCat.Meow(); when you should be doing Cat.Meow();

solemn raven
#

@leaden ice Thanks :D, I tried few things and I think I could just make the delegate public instead of static, Im still testing but If it didnt work I'll use ur advice πŸ™‚

leaden ice
wild nebula
#

I have a ParallelForTransform job that simply make a transform follow another transform

#

But it seems to be lagging behind for some reason (Especially 2nd, and 3rd follower)

#

I'm not sure what went wrong

#

It only happened for like a frame

swift falcon
#

is this code bad

#

chunk loading

somber nacelle
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

pseudo isle
#

If I had two script components, is it always the case that their Awake methods would be called before their Start methods? Like

A Awake -> B Awake -> A Start -> B Start

#

Whichever comes first between A and B doesn't really matter, since I'm aware there's no set order between component executionβ€”what matters more for my assumed use-case is that Awakes are all batched together

leaden ice
#

In reality though all Awakes are not batched together

#

you will get e.g.:
A Awake A OnEnable B Awake B OnEnable

#

all of this will happen long before any Starts are run though

pseudo isle
swift falcon
#

chunk loading code

#

how can I make it better?

solemn iron
#

I need advice On how to proceed With CreateAssetWhenReady
I want to be able to call the constructor and have the values populated via the function inside.
but I get errors saying I am running the function while unity is Updating.
How would I Run the CreateConnectedAsset function when that finishes (arguments included)
https://pastebin.com/xTRcFBAJ

rain minnow
ancient cloak
#

this is why Start exists

#

if your script depents on the initialization of another script, you should run that dependent code on Start. Start runs after every script in the scene completes their calls to Awake()

rain minnow
main shuttle
#

And some guy said that the ones in the same grey box can switch in order sometimes.

ancient cloak
#

^

#

essentially treat OnEnable the same as Awake unless you're manually toggling the gameobjects

#

or if you're doing event registration because you want to unsubscribe on onDisable

somber nacelle
#

really the only time you can be absolutely sure that one object's Awake and/or OnEnable has run before another object's is when you Instantiate them in code because Awake and OnEnable are both called immediately upon instantiation

ancient cloak
#

or if you set an explicit script execution order

#

which is a bad hack, don't do it

rain minnow
#

never had an issue with it until that moment . . .

ancient cloak
#

they run arbitrarily. i believe the initialization code runs through scripts in execution order, calls awake, which enables the game object and triggers onenable

#

it's not like everything runs awake -> everything run onenable

#

not to beat a dead horse but that really is exactly why start exists

#

to guarantee initialization

main shuttle
#

I also didn't know the ones in the same grey box could switch, but it was one of the smart people here that said that, so I assumed it was true.

somber nacelle
#

self initialization in Awake, initialization of anything that relies on other objects in Start

ancient cloak
#

yeah i just think of Awake like initialization and start as linking

rain minnow
#

yeah, i know, but it depended on activation OnEnable/OnDisable, not a one time boot like Start . . .

ancient cloak
#

then you have what we call highly coupled code

#

and you should probably refactor it to not need to do that

#

but you could always set a flag in start and if onenable is called before the flag then it no-ops, but then you'd have to do whatever you wanted to do in onenable ALSO in start

#

and it's just gross

rain minnow
ancient cloak
#

what is the specific issue

#

so you have a stat script and a stat TRACKER script?

#

i feel you tho. i'm just curious

vague tundra
#

What's the appropriate way to rotate an object with a CharacterController component?

rain minnow
# ancient cloak i feel you tho. i'm just curious

tryna figure out how to explain it with this setup. prolly easier from the gun/turret i just finished playing around with

there's no issue, it was moreso testing. i was just thinking of different ways to build and architect a system or mechanic, test it, and see if it could work. the idea was making stats for an object; instead of placing them as a field on a script, like Player, Enemy, etc., i made a separate script for them. then i wondered about referencing those stats to use in other systems and mechanics. StatTracker<T> is a test to track a Stat for use in a base mechanic

i'm creating β€” yet another β€” HealthSystem to see if i like how it's setup. e.g., a Heal mechanic or a Damage mechanic would derive from StatTracker or StatTracker<T> and are fields referenced in the HealthSystem. The Heal mechanic will have a HealthService module(s), a ScriptableObject that you can drag n' drop to change how the heal(ing) occurs. the same applies to the Damage mechanic along with its DamageService module(s)

i was debating if the mechanics should be coupled with health system or not and if i wanted them to update the value of their Stat when and if the object is disable or enabled . . .

vestal crest
#

Hi, lets think i have 5 gameobject attached same script and in this script i have a static int which is someIndex. If i call MyScript.someIndex how do i know which one is it? or because of it is static theres only one someIndex?

#

Im not really good with statics and im currently working on it and i have this question

somber nacelle
#

static means it is owned by the class rather than the instance. so each instance of that script would share the same value for that static variable because that's literally what static does

vestal crest
#

its actually one someIndex i guess then?

somber nacelle
#

the entire purpose of static is that it is not tied to any instance

rain minnow
vestal crest
#

okay got it thanks

#

Any statics (class, variable) initialize when program loads? before everything like awake- start?

vestal crest
#

thanks

somber nacelle
#

static members are initialized before you access them, yes

vestal crest
#

thanks a lot

robust spire
#

Anyone have a suggestion for how I could determine whether a collision is occurring "inside" an edge collider (orange) vs. occurring "outside" an edge collider (blue)? I first thought of checking the dot to the collision normal, but the normals of an edge collider orient in both directions (green)

plucky inlet
robust spire
plucky inlet
#

You could also check the points the edge has been created of and see, if the next point is to the left or to the right. In those cases to the left would be outside and to the right would be inside.

robust spire
shell scarab
#

so... is this a bug or something? What am I missing?

public void OnBeforeSerialize()
        {
            if (rotation == new Quaternion(0f, 0f, 0f, 0f))
            {
                Debug.Log("why won't it get here?");
                rotation = Quaternion.identity;
            }
            Debug.Log(rotation);
        }
mellow sigil
#

You can't compare quaternions directly

shell scarab
#

how small of a number would you suggest?

#

like a little bit above float.epsilon small?

#

besides, I want to check if it's EXACTLY 0 anyways, because I'm getting an error that the quaternion is invalid because all its elements are set to 0 when I create an item in a list, which is very annoying, and that is what I'm trying to solve.

mellow sigil
#

then check if x, y, z and w are all 0

shell scarab
#

okay

#

thank you

rigid island
#

Hello, looking for a way to get data from light or how much light is hitting a certain mesh material ? ( like a sphere.)
Need a way to determine if sphere is in the shadows or not.
would much appreciate any suggestions on this matter

main shuttle
#

Quaternion.identity is 0, 0, 0, 1 isn't it? A Quaternion doesn't allow all 4 values to be 0 afaik, it always points somewhere. You could check the eulerAngles if those are all 0.

abstract portal
#

So in Test Framework 2.0.1 we can use Build Configs for playmode tests in a build. I'm wondering if there is any way to trigger this via command line? I checked the docs but there's nothing there. I feel like it would be strange if the only available option was to go via the Unity GUI...? When testing otherwise is fine through commandline with -runTests.

thin aurora
#

Hence why you should get something that you can compare with, such as the angle

plucky inlet
woeful leaf
vague tundra
#

Do CharacterControllers not collide flush with other objects?

woeful leaf
#

Elaborate?

vague tundra
woeful leaf
#

Your hitboxes are wonky

#

That isn't the CharacterControllers fault

#

You can adjust the hitboxes

vague tundra
#

They are not, good sir

woeful leaf
#

Proof?

vague tundra
#

This is just the capsule collider that comes with the CharacterController

woeful leaf
#

And the hitbox of the plane?

vague tundra
#

Uno momento

woeful leaf
#

Of the plane

vague tundra
#

Mmm the plane's collider isnt really obvious from a screenshot like this

#

Anyway, same problem occurs if its any object

#

Do you know if character controllers are supposed to move flush with objects? Even if the Move I am providing it would send it further than where it should stop?

woeful leaf
#

Try with a new plane?

#

Assuming it's a plane

vague tundra
#

Tis all colliders it cannot approach

#

controller.collisionFlags == CollisionFlags.Below

This however resolves to true when on ground

woeful leaf
#

Is it a problem?

vague tundra
#

For my game? yes

In general? Yes. Especially if it isn't supposed to function this way

vague tundra
#

Lmk if anyone knows what the issue is here

frank kayak
#

Good morning everyone! Just joined in, I've been developing a videogame for the past two months, but yesterday I found myself struggling on something I think it's quite stupid.

I have a mini puzzle game (something like the Operation board game, you have to drag an object without touching a labyrinth collider) inserted in a 2D sidescroll exploration level. For reasons regarding the labyrinth collider, I couldn't code this in UI, cause I couldn't find a way to give the correct collider to the labyrinth image, I suppose because collision in UI are not handled in the same way as the scene.

So I made a scene object with the images needed for the Labyrinth to be played. It has the correct collider and I spawn a small object cursor on top that the player can click and drag across the puzzle game.

In the background I have a Tilemap with the background tiles (I'm using the preview package Tilemap 2D extras for autotiling).

So at this point comes the issue: the Tilemap Collider attached to the grid in the background, prevents me from clicking on the object cursor and start the drag function, like they were on the same layer of collision. I don't really understand how is that possible. The grid is on a certain sorting and collision layer, the puzzle game is on different ones. I also set up the collision Matrix to prevent the two chosen layers to collide with each other (I did it both on 2D and 3D collision matrix even if I'm working only in 2D, I'm desperate!) but the grid still prevents me from clicking the object on top.

I don't have the project in my hands right now, but I can post some images later, if it helps.
Thanks a lot and sorry if this breaks the rules in any way! In that case, tell me straight away and I'll reformat the request in a proper way.

woeful leaf
frank kayak
#

With IDragHandler interfaces

#

Drag, BeginDrag and EndDrag

#

if I deactivate the grid, the whole thing works! So i know it's that collider interfering

woeful leaf
#

Crappy way to do it is disabling the top collider whenever you do the Drag thing

frank kayak
#

do you mean to disable the Tilemap collider while I'm playing the puzzle?

woeful leaf
#

The one that's preventing you from interacting what is below it

frank kayak
#

That's the problem, the grid collider is BELOW the puzzle object

frank kayak
#

I'll have a look

woeful leaf
woeful leaf
vague tundra
#

Yeah, should be able to send out a raycast from the mouse into the screen and have a look at exactly what the cast colliders with. Can go from there

frank kayak
#

There must be some stupid stuff going on with the raycast, thanks guys!

vague tundra
#

Have a crack and absolutely come back and ask more stuff if needed(:

frank kayak
#

already loving this server

woeful leaf
#

Not often people do it the right way right away kek

plucky inlet
#

Quick question, can you use deltaTime in async calls? I barely touch async voids most of the time so I am wondering how to wait for a value like in a coroutine.

public async void AnimateScale(RectTransform rectTransform, AnimationCurve3D animationCurve, float duration, int delay)
        {
            Debug.Log("Startanimation");

            rectTransform.localScale = Vector3.zero;

            await Task.Delay(delay * 1000);

            Debug.Log("Delayed");

            float timeElapsed = 0;

            while (timeElapsed < duration && rectTransform)
            {
                timeElapsed += Time.deltaTime;
            }
        }
plucky inlet
woeful leaf
#

I see

plucky inlet
#

I guess I have to use await Task.Yield();

woeful leaf
#

I'd not know, a Coroutine is usually a nice solution

plucky inlet
#

There we go, await Task.Yield(); is the equivalent to good ol yield return null; inside coroutine πŸ˜„

woeful leaf
#

Ah

dense herald
#

hi, how would you get the vector3 from transform.lookat without actually using transform.lookat?

woeful leaf
#

What

dense herald
#

like

#

transform.lookat changes the rotation

#

but how would you get that rotation without actually using lookat

#

if i'm not being clear i'll elaborate

woeful leaf
#

Why do you want it?

dense herald
#

it's for directional subtitles

#

i've been making the object use lookat but that kinda messes with the rotation of the gameobject itself so i've been wondering if it's possible

dense herald
#

thanks!

fading yew
#

Hey guys, I have an issue with Addressable Bundles and it's driving me nuts πŸ₯œ
I have an addressable folder containing 2000 images for one of my scenes. But it's included (sometimes multiple times) in builds for my other scenes (which do not use these images anywhere)

How do I stop it from including all my adressables? I started using these instead of the resource folder for this reason πŸ₯Ή Please help πŸ™

main shuttle
fading yew
#

sorry didn't see that thread! thanks!

jaunty needle
#

Hello guys, so I have this piece of code that zooms the camera according to if I scroll forwards or backwards but it's always centered, how do I make it so that it follows the position of my mouse?

    {
        if (Input.mouseScrollDelta.y < 0f)
        {
            cam.orthographicSize += 0.1f * sensitivity;
        }
        else if (Input.mouseScrollDelta.y > 0f)
        {
            cam.orthographicSize -= 0.1f * sensitivity;
        }

        cam.orthographicSize = Mathf.Clamp(cam.orthographicSize, 1f, 100f);

        GameManager.orthoSize = cam.orthographicSize;

    }
fading yew
#

doesn't seem to be very active over there haha rip

fading yew
main shuttle
#

Yeah, that's true, coding channels are very active compared to the fringe channels. But addressable's are something you need to have played with to be able to give an answer, and I for one never used them in 12 years.

jaunty needle
fading yew
# main shuttle Yeah, that's true, coding channels are very active compared to the fringe channe...

I can see why ^^' they are confusing. maybe I should rephrase my question haha, I have 2000 images I need to load. What's the most efficent way to do that? Resouces.load would be nice but then its in every scene (and of course I don't want that)
drag and dropping the 2000 images in an array in the inspector could be the trick but I don't remember why I switched to a different way of doing it haha so any suggestions?

fading yew
jaunty needle
jaunty needle
#

I'm gonna implement following and panning later on too

fading yew
#

aaaaah

#

okay you want it to zoon but towards where your cursor?

jaunty needle
#

yupp

fading yew
#

πŸ€”

#

You could use the magnitude of the vector from the center of your screen to where your pointer is on the screen (world to screen point) and use this vector to translate your camera in this direction ?

#

so you essentially zoom but also translate the camera some amount (you'll have to tweak this amount to make it feel good) in that direction

jaunty needle
#

hmm that could work

fading yew
#

so if center v1=0,0

#

your mouse is v2=-0.5,0.5 (mid top left) your angle would be v2-v1 (and here don't normalize the vector if you want to use the mag of this result as your amount to move the cam)

jaunty needle
#

ooh ok don't normalize it

main shuttle
fading yew
main shuttle
#

But it's a problem i have never needed to solve, so maybe other people can help you better.

fading yew
#

so it should feel a bit better to keep this not-normalize

fading yew
#

so I have a slider (with 2000 points) that shows the image like pangea[slider.value] basically

#

I could load them as needed but I'm not sure how to do this and I think it would feel janky if the user moves the slider super quick

#

so what I did is I have a small loading before they get to play around with it that loads those 2000 images in memory and then ofc it's smooth as butter

#

so addressable seemed perfect for this. but for some reason they appear in all my builds no matter whether the scene loads them or not as a bundle and it's 700MB 😒

#

so essentially they work just like the resource folder, only I have an extra loading screen haha which is terrible...

#

Thanks @main shuttle for the help though, google has been rubbish

main shuttle
fading yew
#

so I moved them to a group of it's own and un-ticked "include in build" which works and effectly stops including it in all my builds (already good) but then I have to tick it again for the one scene I want it for. Seems a little odd to have to do this, I really feel like I'm using this all wrong

fading yew
#

Yeah I clicked the "fix all rules", not sure what it did or why I would have to manually click such a hidden thing haha but let's see if it changed anything. It doesn't seem to show what asset is used where yet

#

I'll keep you in the loop!

#

thanks for the help

jaunty needle
#

How do I make this smoother?

    void Pan()
    {
        
        Vector2 mousePos = Input.mousePosition;

        print(mousePos);

        if (mousePos.y >= Screen.height * percentageOfBoundry/100f)
        {
            transform.Translate(Vector3.up * Time.deltaTime * panSpeed, Space.World);
        }else if(mousePos.x >= Screen.width * percentageOfBoundry / 100f)
        {
            transform.Translate(Vector3.right * Time.deltaTime * panSpeed, Space.World);
        }
        else if (mousePos.y <= Screen.height * (100f-percentageOfBoundry)/100f)
        {
            transform.Translate(Vector3.down * Time.deltaTime * panSpeed, Space.World);

        }
        else if (mousePos.x <= Screen.width * (100f - percentageOfBoundry) / 100f)
        {
            transform.Translate(Vector3.left * Time.deltaTime * panSpeed, Space.World);

        }

    }
#

As in lerp it somehow

jaunty needle
#

Anyone?

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
jaunty needle
woeful leaf
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mighty ivy
#

Hello! I'm building a json object using json linq. I need to serialize a list (made of a custom struct that has two strings). Does anyone knows how to do it?

#

Obv this doesn't work since "properties" is a List<Property> type and it's not possible to convert it

woeful leaf
leaden ice
#

Note good possibility you're handling the others incorrectly too

mighty ivy
#

No, they work

mighty ivy
#

how do I parse that back to a list?

leaden ice
#

Just with ToString()

thin aurora
# mighty ivy

Why are you building a JObject when you can serialize/dezerialise the data into a class?

#

JObject/JArray/JToken types are usually used if you don't know what you get, or the data varies. This does not look like it

mighty ivy
#

short answer: because I need it

leaden ice
thin aurora
#

You need a JArray by the way, to work with a list. Json only has 1 collection type

leaden ice
#

JObject is the final destination

thin aurora
mighty ivy
#

I used jsonUtility for most of my projects, but now I need to use a more "free" json solution

mighty ivy
#

to convert data directly into a class

thin aurora
leaden ice
#

JsonConvert is part of newtonsoft as well

#

You don't need to use JObject

thin aurora
mighty ivy
#

no, I use it because I need to build a json object without knowing its variables

leaden ice
#

Wdym without knowing variables

#

You clearly know the variables here

mighty ivy
#

here

#

not in all the objects

thin aurora
mighty ivy
#

that's my solution to have a saving solution not linked to a dataclass per object

thin aurora
#

If you mean that a variable might be null, then know that Newtonsoft can serialize that fine, unlike JsonUtility, so that's not a reason to use JObject

mighty ivy
#

I'm building a survival, so tons of objects needs to be created

thin aurora
#

That's not something you use JObject for

mighty ivy
#

e.g. with my solution I don't need a TreeData class, I don't need a RockData, FlowerData, CraftingTableData etc, I just need to implement "ISaveable" interface and everything works

thin aurora
#

You create a list for that

mighty ivy
#

a list of saveable objects, yes

thin aurora
#

But those are all the same types

mighty ivy
#

exactly

#

same type with different variables

thin aurora
#

You can use a list of a set type there, not a JObject or JArray???

mighty ivy
#

"set type"?

thin aurora
#

Also, you can serialize/deserialize your interface if you make it a class

#

Another reason why JObject is overcomplication

leaden ice
mighty ivy
#

if I make it a class I need to make one per object

thin aurora
#

This whole setup is so confusing

#

You really don't need JObject/JArray/JToken here

mighty ivy
#

this whole setup is the only solution that's working that I thought of, and nor google nor this discord helped me when I asked what was the best solution

thin aurora
#

Maybe I'm confused on what exactly you're doing

mighty ivy
#

look:

thin aurora
#

I would love to fix it for you πŸ˜„

mighty ivy
thin aurora
#

These look like settings nvm I'm dumb

mighty ivy
#

"savedObject" is the list of all the JObjects, a.k.a. one JObject per object

thin aurora
#

But every instance has the same set of data in them

mighty ivy
#

you got transforms there (p*/r*s* is position, rotation and scale), and the ID

thin aurora
#

So you can make a class/record and specify the properties in there to deserialize in

#

Not?

thin aurora
#

You can't deserialize in an interface

mighty ivy
#

WAIIIT

#

ahahahah

#

lemme explain

#

this is the grass objects

#

it has no custom properties apart from the basic one

#

you add that to every object spawned in a scene and the object is saved and loaded, forever

#

wanna add a custom variable?

thin aurora
#
public class saveObject
{
  [JsonProperty("px")]
  public float positionX { get; set; }

  // put the rest here
}

Your class would be this, and you then have a list var @list = new List<saveObject>()?

mighty ivy
#

do something like this (hits in this case represent the times a rock has been "mined", hit by the pickaxe)

thin aurora
#

Alright but you basically have a save system you need supporting

mighty ivy
#

what if I have trees, rocks, grass, the player, enemies etc.?

swift falcon
#

Hi, how can I reference some β€œglobal” parameters between scenes (without using playerprefs or gameobjects with dontdestroyonload)? I thought about static classes but I dont know how to do it. I tried with something like this but it doesnt work:

public static class Parameters
{
   public static int gamemode;
}  ```

and then from another class
``` Parameters.gamemode =  1;  ```
mighty ivy
#

and you have custom vbariables for every one of them? like, a dropped item has to contain the ID of the dropped item, the tree has to know how much it has grown and when it was planted, a bush if it has berries in it etc.

#

solution if you convert a whole class: you can't, you need to create a class per object

mighty ivy
#

OR, you create a JObject per object and load it with every variable that you need, base case is transform only, but you can add every other variable that you want

swift falcon
thin aurora
woeful leaf
thin aurora
#

So you would have the saveObject I mentioned, with a "custom properties" dictionary

mighty ivy
woeful leaf
thin aurora
#

JObject works fine

#

It's just complex for what it achieves

mighty ivy
#

where should I add it? I'm not sure I'm understanding what you mean

#

savedObject is a list

#

like that

#

it's only used when you need to save/load a chunk

thin aurora
#

You can't deserialize an interface, right?

#

It needs to be a class

mighty ivy
#

you just run through all the savedObjects and load the savedObjectFinalList with that

mighty ivy
#

but the interface has this:

#

you have to implement the Save method

#

so for example that-s the save method of a tree

swift falcon
mighty ivy
#

like that

rain minnow
woeful leaf
swift falcon
#

I cant

woeful leaf
swift falcon
#

ok, that was the problem thank you. I had a coroutine with a while inside without yield return null.

leaden mural
#

Hello. Was wondering if someone could help me. Have an issue where my bullet object isn't destroying my enemy object. The enemy is the trigger, and I'm using OnTriggerEnter2D(Collider2D other), which is working because when I don't have any extra parameters, the enemies are destroyed when they spawn in because they touch the ground. But when I use CompareTag to reference the bullet tag on the bullet object, it doesn't work. Any idea why this is? I'll gladly send screenshots of my inspector if needed.

mighty ivy
rain minnow
mighty ivy
#

will it parse back to a list automatically?

#

or an array?

thin aurora
#

Well you need a JArray to begin with

rain minnow
leaden mural
#

Wait, I think I found the issue. Might be an issue with the sorting layers in the Sprite Renderer

thin aurora
leaden mural
#

Nevermind, that was not the issue. Will send screenshots in a sec

thin aurora
#

What is jsondata?

mighty ivy
#

it's my JObject saved object

thin aurora
#

I don't remember how to change a JToken to a JArray, but you can try this

mighty ivy
#

literally one of the "savedObjects" of the screen that I sent before

#

in this case, due to the id, it's 100% a dropped item (so it's a JObject of a dropped item class)

thin aurora
#

But you can also just convert a JArray to a List<Property> without adding the loop

mighty ivy
#

uh, any easy way to do it?

leaden mural
mighty ivy
woeful leaf
leaden mural
woeful leaf
leaden mural
woeful leaf
#

One of them at least, yes

rain minnow
woeful leaf
leaden mural
#

Added a rb 2d to both and its still not working for some reason

mighty ivy
#

@thin aurora it doesn't work 😦

thin aurora
mighty ivy
#

do I have to do it like that?

#

so not using the .parse

thin aurora
#

If you can't use JArray.Parse with a JToken, and are forced to make it a string, casting it aint gonna work πŸ˜„

thin aurora
woeful leaf
woeful leaf
terse venture
#

Hi, im trying to save my settings menu across my scenes. Ive researched about PlayerPrefs, so im trying to use that. The slider just resets to 0 everytime. I have it so volumechange is whatever the slider value is (also updates some text from this). Then when you click Back, it should save "volume" as the volumechange value and in the start method (when the next scene loads up) it should theoretically set the slider value and text to the volume amount which was saved. This is not working.

leaden mural
woeful leaf
craggy nova
#

Hello,
Does anyone know how they usually program input commands in fighting games?

craggy nova
#

I tried to look for the source code for some games but the only ones I could find were for the really old games on ROM

woeful leaf
#

Input.GetKey()

terse venture
woeful leaf
woeful leaf
tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
craggy nova
craggy nova
#

sorry, should have said motion inputs

woeful leaf
#

Define motion inputs

craggy nova
#

do you know how hadouken in Street Fighter works?

leaden mural
terse venture
craggy nova
woeful leaf
woeful leaf
terse venture
#

Wumpie, would you go with PlayerPrefs or a more complicated saving system. I cant seem to get PlayerPrefs working however i know how to get normal saving working.

woeful leaf
#

PlayerPrefs isn't hard to get working, but be mindful of typo's in strings

terse venture
#

It just wont work though!

woeful leaf
#

I've tried to build my own system around it but I've not yet to succeed with it, don't have the time for it

terse venture
woeful leaf
#

Oof

terse venture
#

Im probably just gonna make a duplicate of my other save system

#

probs not optimised at all

rain minnow
leaden mural
woeful leaf
#

Code?

craggy nova
leaden mural
tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
woeful leaf
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rain minnow
#

put cs on its own line . . .

leaden mural
#
public class KillZombie : MonoBehaviour
{
    private void OnCollisionEnter2D(Collider2D col)
    {
        if (col.CompareTag("Bullet"))
        {
            Debug.Log("working");
           // Destroy(gameObject);
        }
    }
}```
leaden mural
woeful leaf
rain minnow
#

you could've edited your previous message. just delete it now . . .

woeful leaf
leaden mural
woeful leaf
woeful leaf
leaden mural
#

Fixed code to get rid of unused member error, but still the same issue.

leaden mural
woeful leaf
#

The latter, yes

leaden mural
woeful leaf
#

That should be fine

#

Do you've errors?

leaden mural
woeful leaf
#

Yes.

leaden mural
#
public class KillZombie : MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D collider)
    {
        if (collider.gameObject.CompareTag("Bullet"))
        {
            Debug.Log("working");
           // Destroy(gameObject);
        }
    }
}```
terse venture
static matrix
#

when I'm lerping EulerAngles, I get this thing where it jolts around when it goes from negative to positive, any fix?

rain minnow
static matrix
#

nvm I figured it out

#

oh hey its you

wheat bramble
#

Im trying to find the magnitude offset/distance/angle of 2 rotations (quaternions) im saving, but it seems like Quaternion.Angle returns a wrong number even when the rotations are equal (per example for an Euler representation of, {0,0,0} and {0,0,0} it returns 180 (debugged to ensure the values)

#

How can i find the distance between 2 quaternions then?

#

or should i instead make a custom euler esque?

#

i know this is prone to gimbal lock, but sigh*

jade heart
#

Hi everyone, I have this weird bug, not sure if it is caused by scripts on this project or something external. But as you may see the camera game object does not move with the transform component, may someone help me with this?

plucky inlet
main shuttle
jade heart
#

Oh damn I'm dumb

#

So it is code related

plucky inlet
#

What is code related, there is no issue πŸ˜„

main shuttle
#

No clue what the actual problem is to be honest. That you don't fly into the clouds?

jade heart
#

What I'd expect is to get the camera move trough the clouds

plucky inlet
#

What are the clouds?

#

Particles, Post Process, Shader on sphere? explain abit

jade heart
#

They are C#/shader based clouds that use perlin/curl noise combined with a base texture in order to render them in-game

plucky inlet
jade heart
plucky inlet
#

As long as it is no custom volumetric cloud script, I guess, you just can not fly through it?

main shuttle
#

I agree with that, or it will look completely janky.

jade heart
#

Thing is that it was working fine yesterday

plucky inlet
#

On the same scene and camera?

jade heart
#

Not the same scene

plucky inlet
#

Well, you might be missing some settings you need to set so your camera gets the right information

plucky inlet
#

You mean the event/function to ask if a path is valid and reachable?

#

nice talk tho πŸ˜„

jade heart
#

Thanks!

wicked river
#

But when I remove the 5 lines of code, no errors

viscid kite
#

question what's the order of the start functions being called for the scene? Is it topmost object all the way to the bottom most object? The reverse? All parents first then going down each child level in a similar sweep?

wicked river
#

That is a very good question. I will have to double check that.

thin aurora
wicked river
#

2 sec

thin aurora
#

Also, probably related, but please get rid of all the Find calls you have in the script. It's unreliable, a code smell, and most likely going to give you problems in the future

#

You should create a better way to get related transforms

wicked river
#
ArgumentNullException: Value cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[TKey,TValue].FindEntry (TKey key) (at <d6232873609549b8a045fa15811a5bd3>:0)
System.Collections.Generic.Dictionary`2[TKey,TValue].ContainsKey (TKey key) (at <d6232873609549b8a045fa15811a5bd3>:0)
_1_Scripts.GameManagers.InventoryManager.Add (_1_Scripts.Utilities.ScriptableObjects.Item itemCollected) (at Assets/1_Scripts/GameManagers/InventoryManager.cs:43)
_1_Scripts.GameManagers.EventManager.RaiseOnItemPickup (_1_Scripts.Utilities.ScriptableObjects.Item item) (at Assets/1_Scripts/GameManagers/EventManager.cs:26)
_1_Scripts.General.ItemPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/1_Scripts/General/ItemPickup.cs:17)

wicked river
plucky inlet
wicked river
#

sure but the key is not null if I remove the instantiation code. SO that is why I am confused

plucky inlet
#

From what I see in your stacktrace, it is not talking about the script you gave us tho

#

what is Assets/1_Scripts/GameManagers/InventoryManager.cs:43) doing?

thin aurora
#

ItemPickup, not ItemSlotActionHandlers which you gave

#

Correction, it's in InventoryManager

wicked river
#

I am aware yes. however the issue I am trying to figure out why when I add

 var itemPrefab = (itemScriptableObject as Item)?.itemPrefab;
                var instantiatedItem = Instantiate(itemPrefab, GameObject.Find("Hand.R").transform, true);
                instantiatedItem.transform.localPosition = Vector3.zero;                                                 //<--- Problem area
                instantiatedItem.transform.localRotation = Quaternion.identity;

I get the issues of the dictionary value can not be null. I am just trying to add the prefab attached to the scriptable object to the world.

But the Inventory manager handles the adding and removing of scriptable objects and inventory item slots into the dictionary

https://gdl.space/ovitupuxey.cpp

stable musk
wicked river
#

correct

#
    public abstract class Item : ScriptableObject
    {
        public string itemName;
        public string itemDescription;
        public Sprite itemIcon;
        public ItemTag itemTag;
        public GameObject itemPrefab;
        public bool isStackable;
        public bool isHoldable;


        public enum ItemTag { TACTICAL, UTILITY,CONSUMABLE,THROWABLE };
    }
}
thin aurora
#

You should debug it.

plucky inlet
#

I am not sure you can store a SO file in a dictionary. Just thinking loud here

wicked river
#

It all works, just not instantiating the prefab

plucky inlet
#

Oh okay, my bad then

#

So of your pasted code, line 60?

thin aurora
#

Which doesn't happen because itemCollected is null, in Add.

plucky inlet
#

Hey I need some help please The code for

jaunty needle
#

Guys why does the position where I spawn get offseted here?

#

I'm using cinemachine to implement the following but it gets offsetted somehow

stable musk
jaunty needle
#

Also these are the two lines that instantiate the prefab:

        GameObject planet = Instantiate(planetPrefab, spawnPos, Quaternion.identity);
jaunty needle
#

Reread it carefully

stable musk
#

Alright

jaunty needle
#

Acc now that I think about it this is expected behaviour

plucky inlet
jaunty needle
#

There is no bug it's just normal behaviour

sweet island
#

How can i pick a random point on the navmesh that i can move navmeshagent to (it would be nice if after the agent gets there he gets another point in a loop)

royal spire
#

not sure if this is the correct place, but I get the following error:

#

What should I do?

plucky inlet
royal spire
royal spire
plucky inlet
royal spire
#

wait wait I didn't provide full context

#

breakpoint doesn't work

#

🀦🏻

#

@plucky inlet

#

sorry

#

it just doesn't trigger

#

I'm trying to debug it

#

some array doesn't assign correctly

#

this happens

#

and I'm really outta options to solve it w/o debug

plucky inlet
#

Just debug log everythign you can, my suggestion, otherwise it will just be guessing from my side

royal spire
#

I think it's something related to the new chunks system

#

I think the tiles aren't ordered correctly

#

ARRRRR

#

stupid debug no work

royal spire
#

I have no idea what's messed up

#

it should work perfectly

#

in code, it does

#

but it doesn't actually work

#

AND NOW DEBUG.LOG DOESN'T WORK EITHER

#

HOW FUN

#

I'm done with unity

#

deubgger doesn't work

#

console doesn;t work

#

my code doesn't work for no fricking reason I can't find out w/o all the other things THAT DON'T WORK

#

I'm fricking done

woeful leaf
royal spire
woeful leaf
#

Oh nvm then

#

The lines look like VSC and the debugger is unsupported in VSC

#

But if it's Rider/VS then the debugger should work

royal spire
#

but it doesn't

barren kelp
#

How can I make my enemy move upright on the navMesh instead of moving around on his back like he is doing now

viscid sleet
#

any idea why the slider value isnt changing? the min and max values chang tho

thick socket
#

my brain is fried, I need major help 😭

#

I do Equip(StoreItemsVE) on an item, and its putting it back into my itemList.Add space instead of addTo.Add space

#
Dictionary<ItemType, StoreItemsVE> equippedList = new()
        {
            { ItemType.Armor, null },
            { ItemType.Weapon, null },
            { ItemType.Jewelry, null },
            { ItemType.Undefined, null }
        };```
#

EquippedList is not null in these cases, each ItemType has an item

lucid valley
thick socket
lucid valley
#

whats your issue then?

thick socket
#

I click Equip
(which calls equip)

shut ridge
#

how r u supposed to make two objects in particular not collide, but activate each other's triggers

lucid valley
shut ridge
#

like OnTrigger proccs, but OnCollide does too

#

how do i make just ontrigger proc

thick socket
#

it puts item into arrow on right(itemlist.add) instead of the left like it should(addTo.add)

hexed pecan
lucid valley
#

Using the debugger tools is really helpful for issues with no errors

shut ridge
lucid valley
#

You can step through code and see what variables contain as the game runs using breakpoints

shut ridge
#

dunno how that would work

#

wait

#

ok that might work

#

thx

thick socket
worn wyvern
#

Is this possible in C# without using 100 lines?

#

Here if type is not found in the dictionary, it crashes

leaden solstice
worn wyvern
#

My IDE says it does not exist D:

leaden solstice
#

It's in System.Collections.Generic

worn wyvern
#

Damn I can't find it

thick socket
#

alright

#

can yall explain how this works

#
if (equippedList[itemType] == null)
        {
            Equip2(tmpStore, itemType);
        }
else if (equippedList[ItemType.Undefined] == null && itemType==ItemType.Jewelry) 
        {
            Equip2(tmpStore, ItemType.Undefined);
        }
else
        {
            equippedList[itemType].equipped = false;
            itemList.Add(equippedList[itemType].root);
            itemsList.Add(equippedList[itemType]);
            Equip2(tmpStore, itemType);
        }```
#

the 2nd else statement is true and it executes
then third else becomes true and executes(since equippedList[itemType] != null anymore)
Shouldn't it have already evaluated the expression and whatever I do in Equip2 not effect the if/else statement?

worn wyvern
leaden solstice
#

Which would be (0, 0, 0)

worn wyvern
#

Yeah, so that's fine I guess

#

Perfect, thanks πŸ™‚

lucid valley
thick socket
#

could be possible

#

it requires a button click...but the menu should go away after its being clicked once

#

is there a way to do like break; in an if statement?

leaden ice
thick socket
#

since throwing in a return statement didn't fix it inside the if/else

thick socket
shut ridge
hexed pecan
#

Not 100% sure if it works for your use case but it should

shut ridge
#

im using the layer version of it

#

and no

#

it doesn't work for my case

hexed pecan
shut ridge
#

bc its a multiplayer game

shut ridge
hexed pecan
#

It's not another "version"

#

Why dont you use IgnoreCollision like I suggested?

shut ridge
#

players all have their own individual colliders

#

i can't get and set them all to ignore this one object

#

well i could, but its incredibly inefficient im sure

#

there has to be some better way

hexed pecan
#

It lets you give 2 colliders

shut ridge
#

yes

#

that would only work if i had one player

hexed pecan
#

You need to manually call IgnoreCollision for every pair of players, yes

#

Or put the trigger on a separate child object, and have that on a different layer. Then you can ignore by layer

shut ridge
#

ok that might work

#

ty

#

gimme a sec

hexed pecan
#

Lemme know if it works

shut ridge
#

aight

dusky spear
#

Can I edit the shape of a freeform 2d light using a c# script?

reef crater
#

I have this error when running on android:

#

unity ads initialization failed: internal_error - unity ads sdk failed to initialize due to environment check failed

#

this only occurs on android

potent ridge
#

I have a question regarding the Line Renderer. I use the Line Renderer for a Power Indicator, to show how much power you're applying atm by multiplying the length of the Line Renderer. Though, this issues a problem, since sometimes if I am too close to a wall, and I try to shoot to the left, the indicator would go through the wall. This is not what should happend. How can I manipulate it so, the line is visible at all times, without it going through walls?

#

Im not sure, but I know its called something where you manipulate the view of the line or something

royal spire
#

like there's a UI layer

#

and objects layer

#

so make another one

potent ridge
#

yh, ive done this

#

still going through the wall

dawn dock
# potent ridge

There may be a setting called order in layers further down but I’m a noob and idk exactly where. You can adjust the number to adjust what you can see first

potent ridge
#

hm

#

yeah ill try find it but this is everything there is on the tags & layers inspector

#

ahhhh

#

wait

#

its in the line renderer

#

okay so Ive made background layer and foreground layer

#

and I assigned the line renderer to the foreground layer

#

but its still going through the wall

#

im not able to assign a sorting layer for the walls

lament epoch
#

I am trying to make a space game. Is there a way to get infinite space in the scene? Because of the floating point limit the meshes start bugging when you get further then 100.000 away from 0|0. I have thought that I could move the planets around the spacecraft so that the physics of the spacecraft don't get effected.

leaden ice
#

you should read up about how Kerbal Space Program does it

lament epoch
thick socket
#

added a breakpoint to this if statement...is there a way to see what it evaluates to before step over/step into?

#

dont see it on any of the windows what the statement is

somber nacelle
#

you have to step over for it to evaluate

simple egret
#

Mouse over the == should display the result

#

Or use the Immediate window to evaluate it

thick socket
#

is there a way so I only debug one script and when I do like stepover it doesn't jump to over scripts running update() code?

simple egret
#

Unity does not use multithreading so this can't happen, only one LOC executes at once

leaden ice
plush grove
#

I have a prefab "button" (Actually a gameobject that has 3 buttons inside of it /w label) that I am dynamically trying to add to a ScrollView's Content object during runtime. It is fine if I set the parent to anything else it works as expected, but setting it to the scrollview it never shows up.

leaden ice
#

drag and drop the prefab into scene view as a child of the scroll view content

#

see how it ends up looking

#

once you get that working properly you'll have it set up correctly to be instantiated at runtime

simple egret
#

Also for your Instantiate call make sure you use one of the overloads where you can provide a parent Tranform directly. Without that, your UI element will be instantiated in world space first, which might cause issues (RectTransform might not like being used outside of UI)

thick socket
#
if (tmpStore.equipped)
        {
            popupRoot.Q<Button>("equipButton").clicked += () => UnEquip(tmpStore);
            popupRoot.Q<Button>("equipButton").clicked += ClosePopup;
            popupRoot.Q<Label>("equipText").text = "Unequip";
        }
        else
        {
            popupRoot.Q<Button>("equipButton").clicked += () => Equip(tmpStore);
            popupRoot.Q<Button>("equipButton").clicked += ClosePopup;
            popupRoot.Q<Label>("equipText").text = "Equip";
        }
void ClosePopup()
    {
        popupRoot.pickingMode = PickingMode.Ignore;
        popupRoot.style.display = DisplayStyle.None;
        root.pickingMode = PickingMode.Position;
    }```
#

right after ClosePopup() executes it re-runs Equip()

#

any ideas either why or how to fix that?

#

(I stepped through it it went and found the root, last line of the ClosePopup)

public VisualElement root { get; private set; }

then immediately jumped back to the

popupRoot.Q<Button>("equipButton").clicked += () => Equip(tmpStore);

and ran it again

simple egret
#

You might want to unsubscribe your handlers from these two events, it's never good to leave dangling event handlers especially if you'll reuse the element. Note that you cannot use lambdas if you want to unsubscribe later on, use full methods.

#

(the same method subscribed twice will get run twice if the event is invoked once)

thick socket
#

where should I unsubscribe at

#

(Ima go throw all my subscribe stuff into start so I make sure it only subs once)

simple egret
#

You usually subscribe in OnEnable and OnDisable, but if you don't plan on enabling/disabling, just destroying, you can do in Start + OnDestroy

thick socket
#

awesome thanks!

thick socket
#

or do I need -= for each handler

simple egret
#

Depends, what's the type of .clicked? UnityEvent, or plain old C# event?

thick socket
#
public event Action clicked

from UnityEngine.UIElements

finite sonnet
#

I have a generated mesh collider which changes each frame (shows what the player can see by shooting lots of ray casts from a point near the cam and making a mesh between the collisions (2D implementation of https://www.youtube.com/watch?v=73Dc5JTCmKI)) (shown in img 1) (Code : https://gdl.space/yenuqazato.cs )

I want to use this to shrink any particles colliding with it in a script, originally I had polygon collider which was a trigger and used the trigger section of the particle system. However, when I make the mesh collider convex it breaks the collider (shown in img 2), from what I can see it needs to be convex to be a trigger.

(here is the working code for the polygon collider trigger based version

[SerializeField] private float shrinkRate = 3f;

ParticleSystem ps;
List<ParticleSystem.Particle> inside = new List<ParticleSystem.Particle>();

void OnEnable()
{
    //get darkness partical system when scene loads
    ps = GetComponent<ParticleSystem>();
    collisionEvents = new List<ParticleCollisionEvent>();
}

private void OnParticleTrigger()
{
    //fetch all the particals which collide with a light collider
    int numInside = ps.GetTriggerParticles(ParticleSystemTriggerEventType.Inside, inside);
    //
    //iterate through the particals, shrinking them and if they have a very small ammount of life or they are very small removing them
    for (int i=0; i < numInside; i++)
    {
        ParticleSystem.Particle p = inside[i];
        p.startSize -= shrinkRate * Time.deltaTime;
    //
        if (p.startSize <= 0f || p.startLifetime <= 0.001f)
        {
            p.startLifetime = 0f;
        }
        
        //setting the partical in the list to the modified instance of the partical
        inside[i] = p;
    }
    //
    //re-asigning the particals to the partical system
    ps.SetTriggerParticles(ParticleSystemTriggerEventType.Inside, inside);
}```
#

I have tried using a much bigger trigger which gets all the particles that the mesh could possibly collide with to find out whether the particle location is within the mesh bounds through a verity of means but couldn't get it to properly work, I would think this is a good solution but am not sure how to work out whether a position of a particle is within the bounds of the mesh.

Is there a way to do this, or a work around such as making it a trigger without breaking the mesh, using a ParticleCollisionEvent or something else?

thick socket
#

so Im guessing basic c#?

simple egret
#

So good old C# event. You'll have to -= for each handler you subscribed

thick socket
#

fun

#

thanks πŸ™‚

#

gosh you are a lifesaver @simple egret

#

would have taken me a super long time to realize I shouldn't do += inside a callable function πŸ™‚

thick socket
#

would I need to declare an actual method that just declares the something method?

simple egret
#

Yeah exactly

thick socket
#

fun

#

what would be the reason to unsubscribe my handlers if the script/objects and whatnot are destroyed when scene switches?

simple egret
#

In this case you don't need to, but it's good practice, just in case one day you need to persist the object through scene changes and wonder why you get duplicate calls.
Or if you have the subscription in OnEnable and turn the object on/off a lot, you'll get dupes too

thick socket
#

wont this return null if it doesn't find the key?

rain minnow
thick socket
#

πŸ€”

simple egret
#

The key is a value type (from the coloring, enum maybe?)

#

Value types cannot be null, ever

rain minnow
#

oh, you'rereturning something different than an actual key from a dict . . .

thick socket
#

right

#

basically want to check dict if there is a value in it

#

if there is, change that value to null

rain minnow
#

if key is a value type (struct), it cannot be null . . .

#

therefore, it will always return true . . .

thick socket
#

it freaks out from my foreach loop as the list its foreaching is modified in the loop

#

thus, I need another method :/

simple egret
#

There's dict.ContainsKey() that returns bool whether the key is present or not

thick socket
simple egret
#

Then you're using the dict backwards :)

rain minnow
#

then check the value instead . . .

thick socket