#archived-code-general

1 messages ¡ Page 248 of 1

latent latch
#

floats then truncate it

upper pilot
#
    public int Defense
    {
        get { return (int)((CharacterSO.BaseDefense + _Defense) * (Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f)); }
        internal set { _Defense = value; }
    }

Like this?

#

I do calculations on floats, then return an int

latent latch
#

thing is if you have like % modifiers you're not always going to get an int, so you need to either decide to round up or down

upper pilot
#

It automatically rounds down right?

latent latch
#

however you want to do it

upper pilot
#

At most I lose 1

#

so its fine I think

#

wait I dont need to store them as floats

#

if I multiply float * int it returns a float right?

#
    public int Defense
    {
        get { return (int)((Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f) * (CharacterSO.BaseDefense + _Defense)); }
        internal set { _Defense = value; }
    }
latent latch
#

right, but sometimes you may want to have float values like attack speed

upper pilot
#

yes those will be done differently I think

#

This is for attributes, tho we dont even have attack speed so its fine.

latent latch
#

I've got a lot of my stats in a dict so having them all as a single type is easier to deal with

upper pilot
#

all attributes are integers in our game so far.

#

do you store them using enums?

latent latch
#

enum to ref

upper pilot
#

I think you did show this a while ago to me

#

like years ago 😄

latent latch
#

it works pretty well for a simple implementation

upper pilot
#

This is how I do it atm

#

I will just add extra calculations inside and call it a day

#

probably not the best, but each stat has different formula

mellow sigil
#

Having the setter set a base value but getter return a modified value is often a bad idea

upper pilot
#

BaseHit cannot be changed, but Hit can.
I was thinking of having a separate getter like "DefenseTotal"

#

Not sure if necessary tho

#

I only want to change "_Speed" and return a modified "total speed"

#

i.e. when character levels up they gain +2 speed

mellow sigil
#

but if you do Speed += 2 it won't do what you'd expect it to do

upper pilot
#

I can imagine this being an issue when saving or loading

#

or even when displaying value on the UI(full value without modifiers)

#

That makes sense, I might need to separate those

#

I suppose this might work better

    public int Defense { get; internal set; }
    public int TotalDefense
    {
        get { return (int)((Character.HasStatus(StatusEffect.Restrained) ? 0.5f : 1f) * (CharacterSO.BaseDefense + Defense)); }
    }
#

I set Defense on level up

#

I keep the getter in case I want to get base value, but its not ideal already as I should also have BaseDefense there.
Perhaps I will get rid of it and do it on level up from lvl 0 to lvl 1

latent latch
#

I've done something similar in the past. Though, I think you may want to figure out a way to cache values a bit more instead of recalculating them if your game becomes a bit more complex later on.

#

I do something similar such that I listen onto stats that become dirty instead of directly recalculating values everytime I am attack or attacked.

#

funny thing too is that I want to rid of all my events and just make my own subscription model since they generate so much garbage

#

specifically for stuff like my abilities and gameobjects where I've a lot of pooling going on.

upper pilot
#

Makes sense, I just like the idea of properties as VS will show me "references" which I find useful.
If a need arises I will look into optimizing it, definitely will be using UnityEvent to update UI when a value changes.
Which won't be easy to do as some values depend on buffs/debuffs.

teal inlet
#

Hi! Does anyone know how can I put a little menu in the game view? Like for displaying fps, or player speed/state, buttons, switches etc.

fervent furnace
#

by making an ui

teal inlet
#

Like this one

fervent furnace
#

this is on gui iirc

teal inlet
#

Ah okay :D

hard viper
#

My mistake. it should have been ClassExtends, not TypeExtends. TypeReferences has various different constraint attributes to work with.

#

ClassTypeRefrence holds a refrence to the type as an object of type Type (and can be implicitly cast to a Type). In this case you want to make an actual instance of the type like this:

private MyStrategyBaseClass strat;
...// Whenever powerup state changes...
strat = Activator.CreateInstance(myScriptableObject.myStrategyField) as MyStrategyBaseClass;```
Here, the Activator makes a new instance of that type (as type object), and then we cast the object to a type that we know it extends.
Fyi, if you needed to do this with a class that extends MonoBehaviour, AddComponent can take an argument of type Type as well. Example:
```TileMonobehaviour tileMono = tileGameObject.AddComponent((Type)mySO.tileMonoTypeRef) as TileMonobehaviour;```
sonic notch
#

I'm super confused at how any research papers are able to compare two crowd simulation algorithms against eachother in terms of actual speed it takes for the agents to reach certain goals (basically evaluate how well they move about and dont get deadlocked). Speed of agents is not standardized among various algorithms so you can't just say "put the same speed for the agents on both algorithms". And also, complexity of the algorithm also slows down the speed of the agents.

fresh hazel
#

Hey,
I'm trying to use Unity ECS system for the first time using the example with the spawner but I'm a bit confused on how things work
I tried to make a player that have a Scriptable Object with its info

public struct Player : IComponentData
{
    public PlayerInfo Info;
}

public class PlayerAuthoring : MonoBehaviour
{
    public PlayerInfo Info;
}

public class PlayerBaker : Baker<PlayerAuthoring>
{
    public override void Bake(PlayerAuthoring authoring)
    {
        var entity = GetEntity(TransformUsageFlags.None);
        AddComponent(entity, new Component.Player
        {
            Info = authoring.Info,
        });
    }
}

But I'm getting this error:
CS8377 : The type 'Player' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'IBaker.AddComponent<T>(Entity, in T)'

Would someone please know what it means, and optionally is there some other good examples available online (that aren't too complex)?

hard viper
#

i’m not sure how well versed you are in reading journal articles, but this should be relatively simple

fervent furnace
fresh hazel
#

Will do thanks

drifting crest
#

Hey guys I am making a quiz game in unity which , when a user selects the correct answer it makes the option green and then question changes but when the user selects the wrong option it gets wrong and the right answer gets green then there is a delay and after which it changes the question , So i was thinking how can I produce this kind of behaviour

grizzled ferry
frozen fjord
#

What's a go-to noise library? I'm making a minecraft clone

hard viper
#

there's one on UPM

#

for shaders

normal quest
#

hey guys, I'm designing my mobile game's UI and I wonder which is the lowest screen resolution I should design for? I've been working on 800x400 portrait (yes, it's forced to be portrait) provided by unity, but when arranging some stuff they simply don't fit into the screen (with other game components) or they are too small for larger screen resolutions. I already know about canvas scaler and configured it to my needs, but the problem persists so I wonder if people actually use 800x400 phones

hard viper
#

if you work with phones, do research on aspect ratios

#

i’d focus on aspect ratio first. then common resolutions, and look for greatest common denominator

normal quest
#

good hint, thanks

hard viper
#

it just sucks to not use full space on tiny phone screen because an app was made for a different aspect ratio

#

so you get the black bars

static matrix
#

Im trying to get my camera to smoothly lag behind the player a little bit, but when I lerp (and slerp) the positions like so:
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, new Vector3(transform.position.x, transform.position.y, -10), 0.2f);
I get a jitter:
how can I get the camera to lerp and not just be hardclamped?

hard viper
#

i gave my camera a kinematic rigidbody, and use MovePosition

#

i let physics system take care of the interpolation

static matrix
#

hmmm
ok

hard viper
#

you still need to lerp, but MovePosition will take care of the in between frames better

static matrix
#

ah

#

wait

heady iris
#

how does the player move?

static matrix
#

Camera.main.GetComponent<Rigidbody2D>().MovePosition(new Vector3(transform.position.x, transform.position.y, -10));
like this?

hard viper
#

my camera also has like 6 different collider objects on it, so it makes sense

normal quest
#

answered to wrong message

static matrix
#

b-but I love re-inventing the wheel...

normal quest
hard viper
#

my camera has a solid hitbox so player can get crushed by autoscroll, death hitbox if the player falls off screen, spawn hitbox to trigger spawns, visible hitbox to trigger things when they become visible, and despawn hitbox to despawn things when far

#

my game is a 2D sidescroller, so this makes sense for me. does not make sense for 3D

static matrix
#

it is still jittering with this code, I tried with both having and not having the lerp

hard viper
#

are you doing this in fixed update?

#

moveposition only makes sense in fixed update

static matrix
#

oh

hard viper
#

and moveposition should also operate on the rigibdody

static matrix
#

yes

hard viper
#

is rigidbody set to interpolate?

static matrix
#

hmm that just makes it instant
when you say "you still need to lerp it" what exactly does that mean?

#

hmm?
ill check

#

ah it isnt

#

that just makes it jitter again

hard viper
#

actually, interpolation probably only matters if you have colliders

static matrix
#

yeah no colliders

hard viper
#

every fixed frame, MovePosition should go to Lerp(currentPosition, targetPosition, lerpValue)

static matrix
#

ohhh

maiden fractal
hard viper
#

i forget which interpolation mode it is. Continuous detection is the one that actually casts the rb colliders to check collision, as opposed to smoothing movement

#

i don’t recall which setting is which

#

but one controls that, and one controls the other

static matrix
#

yup,, got it to work

maiden fractal
hard viper
#

ah, right. getting mixed up

#

interpolation must be on

#

collision detection mode is irrelevant without colliders

maiden fractal
#

Yeah

static matrix
#

interpolation doesn't seem to need to be on

hard viper
#

either way, all is well that ends well

indigo hound
hard viper
#

that’s weird. do you not have the ClassConstraints file from TypeReferences?

#

eg did you import the package, or did you find a single .cs file and add it to your project?

indigo hound
#

I added it via the package manager through git url

#

I followed the little tutorial on the link you sent me yesterday

hard viper
#

look for a file called ClassConstraints or something.

#

if you Ctrl shift R on the TypeReferences namespace, it should show you all lines of code using it in your project

indigo hound
#

ClassConstraints doesn' appear to be in the package

hard viper
#

I wonder if I maybe have a different version of the package? If your Inherits attribute works, then that should be it

indigo hound
#

Yeah Inherite doesnt give any errors

hard viper
#

ok, it must be a version difference

indigo hound
#

Yeah

hard viper
#

because I don’t have the Inherits attribute

#

does it work for you otherwise?

indigo hound
#

I hope I can make it work

hard viper
#

given the type of game you are making, I can say with confidence that this exact pattern is almost guaranteed to appear again

#

i also see that my version of ClassTypeReferences is the old inactive one. the one I linked you forked from it, and is currently maintained

indigo hound
#

Nice

indigo hound
#

Ah nevermind I got it, but just like before, the HandleMovement script gets called, but my character still doesnt move somehow

#

So instead of adding up the velocity here, it just sets it to the first value the entire time and stays that way:

velocity.x += inputDir * physicsConstants.initXAccel * 2;

This sets it to 0.75 and stays the same value UnityChanHuh notlikethis

Here is the debug in the console:

#

Any ideas why?

leaden ice
indigo hound
#

Nevermind I got it 🙂

fresh hazel
#

Hey, let's say I have 2 tilemaps, "WallMap" which defined floor and wall where the player can collide with and "TrapMap" that contains traps which when the player collide with, loose
I'm using RuleTile to place my walls and it's working well, but I would like to do the same for my traps (which are on the TrapMap) but for them to depend of "WallMap" for rules
Like in my screenshot I want the trap sprite to use the "down" version since on the "WallMap" there is some floor there

Is it possible to do that?

hard viper
hard viper
#

you need to define a custom ruletile class, where in the neighbor check function it gives you the coordinate being checked

#

and you need a way for your custom ruletile to get a reference to the map you want to check

#

i can send you code in a bit. it was obnoxious af that Unity’s custom ruletiles don’t automatically pass you the coordinate

fresh hazel
#

That would be nice of you if you could, thanks :)

hard viper
#

give me like half an hour

indigo hound
hard viper
#

ah. you were modifying a copy of velocity

indigo hound
#

Yeah that was pretty dumb of me lol, but I’m glad it finally works now. Thanks for all the help btw!

hard viper
#

sure

#

one last thing before you go: I recommend seeing if you would rather make your PlayerMovementStrategy an interface instead of abstract class.

#

interface gives no default implementation, but allows it to be tacked on to other classes involved in other things

indigo hound
#

Hmm yeah I was thinking about changing it already. It’s probably better with an interface

hard viper
#

main benefit of abstract class is having a default implementation (eg standard Jump()) that all children inherit by default.
benefit of interface is allowing class to be held by PowerupManager and engage in different things beyond player movement from one class.

eg FireMario : PowerUp, ICustomRunButton, IPlayerMovementStrategy, and then that class might contain logic for both playermovement and throwing fireballs

#

you might also consider composition:

public PlayerMovementStrategy strat;
…}
public class PlayerMovementStrategy {…}
public class FireMario : PowerUp {…}
public class FrogMario : PowerUp{
public class FrogMovementStrat : PlayerMovementStrat {…}
…}
hard viper
fresh hazel
hard viper
#

ok, so, here is how I did it. There are 3 main classes

#

CustRuleTileStatic has references to things that are important for evaluating the ruletile that only exist during runtime. Example: References to Tilemaps

leaden yew
#

Hi! How can I load and save a file in unity cloud form cloud code?

hard viper
#

CustRuleTileBase<TNeighbor> contains a VERY important override to the CheckRuleTile method that gives us the coordinate being checked. This class ALSO gets ALL rule logic. Every single rule that you can include in a custom ruletile goes here

#

do NOT define actual logic for a type of rule outside of this class, and you'll see why next

#

I just committed with the important 3rd class: CustRuleTile : CustRuleTileBase<CustRuleTile.Neighbor>

raven basalt
#

Why does my elixer sprite not show up in my game view, even though it exists in the scene view?

leaden ice
#

meaning it's there - it's just way up and to the right

hard viper
#

CustRuleTile has it's own neighbor class which just contains constants for different neighbor rules. CustRuleTile : CustRuleTileBase<CustRuleTile.Neighbor> so that the rule tile methods know to use this neighbor rule

leaden ice
#

SpriteRenderer is not a UI element

raven basalt
leaden ice
#

it's not in veiw of the camera

hard viper
#

AND it has public override bool RuleMatchCoordinate(int neighbor, Vector3Int currentTileCoord, Vector3Int targetTileCoord) {....
which is the function that funnels different rules to different logic via switch case

leaden ice
#

not a SpriteRenderer

fresh hazel
raven basalt
hard viper
fresh hazel
#

Thanks a lot

normal quest
#

Zirk

hard viper
#

sure. I just modified again. it was clearly not super ready to share lol

round violet
#
RaycastHit hit;
Physics.Raycast(_groundChecker.position, transform.TransformDirection(Vector3.up), out hit, -100, _groundLayerMask);
Debug.DrawRay(_groundChecker.position, transform.TransformDirection(Vector3.up) * -100, Color.yellow, 10);
groundDistance = hit.distance;
Debug.Log(hit.distance);

why does this always give me 0 ?

#

the black plane has the Ground Layer, which is assigned in the inspector to _groundLayerMask

leaden ice
round violet
#

oh

leaden ice
#

instead of transform.TransformDirection(Vector3.up) use -transform.up

#

and use a positive number

round violet
#

how do i tell to go to the opposite of up then ?

round violet
#

sorry didnt saw

crystal sky
#

hi

#

How to change that Motion variable using c#

leaden ice
harsh coyote
#

Anyone knows how to do sliding properly? I tried the line below, but that just teleports the player forward, I tried setting the drag to zero and all other modes in ForceMode.

rb.AddForce(bodyRef.forward * slideStrength, ForceMode.Force);
hard viper
#

AddForce should never teleport

#

Force mode AddForce gets used to calculate next velocity, which is then used to translate a rigidbody

#

Is unity’s standard object pool any good? or is it better to just do it myself?

leaden ice
#

so you're basically adding a huge force, getting up to a high speed, moving quickly for one frame, then next frame your velocity is being set back to some reasonable number elsewhere

rigid island
leaden ice
visual fjord
#

Hi

Exist a function similar of "KeyDown" in the new input system?

visual fjord
#

Ok

hard viper
#

i just ask since Unity’s example on there page only uses it once

indigo hound
#

Is there a way to Hide a full class in the inspector without having to put [HideInInspector] in front of all variables?

hard viper
#

i rarely have to use HideInInspector because I usually use automatic properties

hard viper
#

I rarely use;
public int myValue;
in favor of
public int myValue {get; private set; }

leaden ice
#

HideInspector is generally a bad idea

#

unless you have a really good reason

#

because it will be serialized without you realizing it

#

you want to either:

  • make it private
  • use [NonSerialized]
indigo hound
#

Oh okay I see, thanks guys

leaden ice
#

or use a class that's not serializable in the first place

hard viper
#

by default, anything that I set in inspector has either:
[field: SerializeField] public int myVal {get; private set; }
[SerializeField] private int myOtherVal;
Because once I set it, I do not want any other classes to modify it

harsh coyote
hard viper
#

public int myVal {get; private set;} does not get serialized because it is an autoproperty. So it won’t be serialized unless you explicitly ask.

indigo hound
#

Okay thanks! Makes sense 🙂

hard viper
#

oh, and once you fix these things as we described to be non-serialized, you’ll probably see several things in your game suddenly break. This is because they were relying on old values that were saved that should not have been saved. That’s okay because those were things that were going to break in the final build anyway.

indigo hound
#

Oh right because those values were adjustable in the inspector

#

Or?

hard viper
#

Suppose isGrounded is serialized when it isn’t supposed to be (and you just used HideInInspector). Then I start my game with isGrounded pulling from a saved old value of false. That might not be what it is supposed to have started at.

#

or you’ll find you never initialized isGrounded, and program now complains isGrounded is not initialized. This wasn’t happening before because isGrounded was initialized because it was grabbing some old garbage value from a previous session

indigo hound
#

Oh right I think I get it 🙂

#

Thanks

shrewd hound
#

Need help right now as i just cant figure out why, the problem im having right now is that i just set up my jumping code and if i try it out and i jump and then land on the ground, my canJump variable isnt set to true immideately but takes some time, eventually after pressing space about 20 times again it finnaly set to true again and i can jump
'''cs // Handle jumping
if (canJump)
{
canDoubleJump = false;
}
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
moveInput.y = jumpPower;

        canDoubleJump = true;
    }
    else if (canDoubleJump && Input.GetKeyDown(KeyCode.Space))
    {
        moveInput.y = jumpPower;

        canDoubleJump = false;
    }



    if (Input.GetKeyDown(KeyCode.Space))
    {
        Debug.Log("Jump:" + canJump);
        Debug.Log("DoubleJump:" + canDoubleJump);
    }
    CharacterController.Move(moveInput * Time.deltaTime); 

'''

hard viper
#

i would not make can jump a variable

#

that should be a function of many other potential things going on

#

isGrounded, numberOfMidairJumpsLeft, timeLastJumped, touchingLeftWall… these should all be variables

#

i would also include public enum PlayerMoveState { Neutral, Jumping, Sliding, Ducking…}

#

then CanJump() should give you a result based on those variables

shrewd hound
#

First of all, i have pretty much no idea what an enum is and secon im following a tutorial(udemy course) to learn unity so if possible id like to stay as close to the original as possible

hard viper
#

learn enums

#

they are very useful for states that are mutually exclusive

#

otherwise you will find yourself with a player script with a bunch of bools, and you will never ever find your way through

#

second, if you are following a tutorial, and their’s works, but your’s doesn’t, then you didn’t follow closely enough

shrewd hound
#

It probably because im not using the same version of unity as in the tutorial unity 2019 is used

hard viper
#

i doubt that

#

remember your code can be the same, and settings in Unity can be different

spring creek
shrewd hound
#

ill just download the final project and see if i have the same code or not

hard viper
#

one simple thing that can mess everything up is just one random setting. one little checkbox

#

rigidbody simulated off.
collider size = 0;
layer overrides flipped…

thin meteor
#

Is this good to do, performance wise?

#

The "=>"

simple egret
#

It's the same as having the method with braces { }

#

It's a compiler shortcut that gets applied at compile-time, not at run-time

shrewd hound
#

!code

tawny elkBOT
hard viper
#

I have a saving question. I want to make an abstract class (should be singleton), where one method returns a class that is 1) unique to the derived class, 2) is serializable, 3) must be saved in a common serializable save file object. How do I connect the dots?

public abstract TSaveType MakeSaveData();
public abstract void ParseSaveData(TSaveType data);
}```
Let’s say I have a list of these singletons, and each one is ready to have MakeSaveData called, or ParseSaveData called

how do I get all of these into a serializable class, so I don’t have to modify my level load, level save, and save file code every time i add a new one of these?
candid peak
#

So, I got this problem with my movement/surface alignment.
Whenever my character is walking on a ground that is "diagonal" or something it is supposed to "snap on the ground" so the character has the same angle as the ground.
But in my current script it only sticks to the ground if he is standing still, not when he is walking which I wanna fix.
I tried like 1,000 versions that all went buggy/didn't look well (multiplying Quaternions, multiplying y, x, z or w and much else, it often got worse than now).
I just want my character to stick to the angle of the ground and have a smooth movement on the y-axis.
It looks bad when the character is crouching since it clips through the ground. (screenshot)
Here is the code snippet which is one of those thousand versions I tried: https://gdl.space/boqamikiqo.cs

How can I code my script properly? I don't know if the Quaternion.RotateTowards line is the problem.

hard viper
#

i want to end with something like:
[Serializable] public class LevelData {
public List<SerializableInterfaceOrAbstractClass> myList;
}

#

and I would be able to parse from there

simple egret
tawdry jasper
#

I'm already using layers for something and now I'd like my prefabs to have a "material " attached to them to determine collision sounds. Is there a standard unity feature for this? Tags seem natural choice but I have a fear of string comparisons for performance reasons.

somber nacelle
#

i would personally just use a component instead of relying on a material

tawdry jasper
#

But that would mean on every collision handler, I'd have to do a collider.getcomponent(mymaterialproperties) and I also trained myself to avoid getcomponent at runtime? Is this the famous premature optimization? 😉 I just wanted to ask if theres an established standard

#

I was also thinking the rigid bodies physics material? Every body has one and I could use them for this?

#

(but then again no everything a player or an objects bumps into needs to have a rigidbody)

heady iris
#

it's reasonable to use GetComponent in a collision method

#

you avoid using GetComponent when there's a much better alternative

#

TryGetComponent is nice for this kind of situation

verbal gate
#

Can someone help me, i have a game object where i have attached a script that has a "Dontdestroyonload" but for some reason, when i move to the next scene, it's being destroyed :(

heady iris
#

look at the hierarchy

verbal gate
#

nope

#

it isn't

heady iris
#

then look at the console

latent latch
#

Not really much of an alternative to GetComponent beyond tags

verbal gate
#

like on the second scene

heady iris
#

you are probably getting an error about using DontDestroyOnLoad wrongly

#

or the code isn't running at all

verbal gate
#

interesting

#

ok i'll check, thanks

latent latch
#

Would be nice if the unity tag system was more fleshed out

tawdry jasper
#

It would be nice if I didn't need an extension method to check a layer against a layer mask 😉

heady iris
#

yeah

#

unity pls

#

it's rather awkward

worldly cape
#

How can aou do it like when a player touches the water he will reset to the last spot he left and jumped in the water. So he respawns where he jmped of in the water. Pls ping me thanks

verbal gate
#

im finally getting somewhere with the issue i was having after a few days

tawdry jasper
worldly cape
#

okay makes sense. You mesn in the player prefs? Or somewhere else?

candid peak
verbal gate
worldly cape
verbal gate
#

do you have a code editor

#

like visual studio?

worldly cape
#

vs yes

#

and vs code both

hard viper
pastel cosmos
spring creek
verbal gate
tawdry jasper
spring creek
#

Infinite patience and infinite wrong answers

hard viper
#

keep asking it if it's sure lmao

#

"Give me legal cases"
ChatGPT: "Here you go"
"Are these real cases?"
ChatGPT: "Yes"
"Are you sure?"
ChatGPT: "Yes"
=> gets sanctioned for citing non-existent cases in a lawsuit

tawdry jasper
#

I work as a software engineer in a different language and field and I don't really need it there, but for my beginner csharp and unity and learning anything at a beginner level it's pretty good.

hard viper
#

but, hear me out: it's not

#

you can't learn from a teacher who knows nothing. that is the blind leading the blind

obtuse relic
#

I've made a custom Matrix data type for a tile system I am working on for a 3D game - currently I can generate a mesh made up of cubes in the Matrix cells that match a predicate, but even after merging vertices there still are way more verts and tris than I would like. How would I go about grouping the cells into the least amount of quads possible like in the this image?

hard viper
#

is grey supposed to be solid or empty?

obtuse relic
#

solid

tawdry jasper
hard viper
# obtuse relic solid

this might be naive, but my first thought is to go to every box, and strike out vertices that are already counted

#

I'm not super familiar with meshes since I work in 2D

spring creek
normal quest
spring creek
hard viper
lean sail
normal quest
hard viper
#

and if you ask ChatGPT about the made up cards, it will tell you something that sounds like a real card, with the right syntax. but is not legal. does not exist

tawdry jasper
hard viper
#

ask chatGPT for help in pokemon. It will recommend pokemon with abilities they do not get, and moves that they do not learn.

spring creek
lean sail
hard viper
#

with combos that don't make sense

obtuse relic
#

not only messing up the UV maps, but I also might as well just be back at square one since I have no way of calculating the least amount of faces needed to fill in the top portion

obtuse relic
hard viper
obtuse relic
#

I don't have a search algorithm, that's what I need help with lol

hard viper
#

loop through each coordinate, and check each of 8 verices to see if neighboring spaces are filled or not

tawdry jasper
hard viper
#

bam. algorithm

#

foreach coordinate {
if (coordinate is empty) continue;
validVertices = new();
foreach vertex at coordinate {
if ShouldInclude(vertex) validVertices.Add}
FindTris(validVertices)
}

#

I would hold the vertices on a single spot as a flag enum

obtuse relic
#

So each time I remove a vertex I would regenerate the tris and then move onto the next vertex?

hard viper
#

no

tawdry jasper
#

Sorry just checked and I ended up duplicating some vertices because I needed different uvs for neighboring faces.

hard viper
#

you loop through every filled block
you find the valid vertices on that block.
then make tris based on which vertices (for that block) are valid

#

it will not be optimized because vertices in multiple tris get counted separately, but unity might be smart enough idk

#

but it should be the basic idea

obtuse relic
#

How does that group the cells into the largest possible quads?

#

If I understand you correctly that that would just give each filled cell two tris

hard viper
#

oh, you're trying to make big quads

hard viper
tawdry jasper
#

Idsay it's not worth it in your case if this is the scale of your levels unless you want to run on some retro machines.

hard viper
#

actually, maybe make a struct for a Quad

obtuse relic
#

This is where I am at right now, I was just hoping to minimize the number of tris

hard viper
#

that's an ok start

#

List<Quad> qList = new();
foreach coordinate {
if (coordinate is empty) continue;
validVertices = new();
foreach vertex at coordinate {
if ShouldInclude(vertex) validVertices.Add}
qList.AddRange(FindQuads(validVertices));
}

#

then, afterwards, you loop through the list of quads, and simplify

#

first, quads should have one of 6 orientations (+x, -x, +y...)

#

and the quad should also store the coordinate for the center of the face

#

now take your list of quads, and sort/split by orientation

#

then sort inside based on the orientation

#

so for all the faces with +x orientation, sort by x. Any sets of +x quads definitely do NOT get combined, right?

#

so now we take that slice of just quads that have +x orientation, and are all at the same x coordinate.

#

then we need to do a 2D search in there for quads that are actually contiguous

obtuse relic
#

I'm not sure I understand what the orientations are for, do you mean the quad's normal?

hard viper
#

yes

#

normal stored as an enum

#

because we don't want to do all this math with continuous vectors when it isn't necessary

#

two quads with different normals/orientations can never be fused

#

so for a set of quads in +x, that have the same x coordinate, we iterate through, and depthfirst search or breadth first search to get continuous sets of quads

#

these are quads that are all connected

#

do you follow so far?

obtuse relic
#

Yes

hard viper
#

ok, now we have individual collections of quads that are connected to each other

#

so now we're going to go iterate through, and figure out which vertices do not need to exist

#

or just log the ones that do

#

ok, next, let's get all the vertices for all the quads in that collection into a list as Vector2Int. Sort by y, then z. Now we're going to look for vertices that have duplicates

#

if vertex is unique, it is a corner, and must be included.
if we have exactly 4 duplicates of that vertex, then it is interior, and must be removed.
if we have exactly 3 duplicates, then it is an interior corner, and must be included
if we have exactly 2 duplicates, then we need to check if it is a straight line, or a weird connection between two diagonally connected quads

#

idk this is getting involved, but this is the general idea

#

I've at least reduced the problem to a 2D problem on a connected collection of quads, which should be way easier to handle

unborn flame
#

Hey guys so im trying to make a game like kirby strato patrol eos, which looks like this: https://www.youtube.com/watch?v=8NBCl0MqTts. I have 2 problems so far while making this game. 1st problem is the movement as you can see in my video of my game the ai movement is not smooth, they sort of just do what they want they are so suspose to follow the kirbys like in the video. Here is my mouse following script https://hatebin.com/lkedvatnci and my clone follower script: https://hatebin.com/vaehuqrryb The next issue is that when the clone gets hit they should just disappear, but as you can see in the video when they get hit the game ends. The game should only end if the last player/clone gets hit. Here is my code for that in the gamemanager script: https://hatebin.com/lfpbcqhyys and player script, https://hatebin.com/keadfcrbdo. Please let me know if you see any issues! Thank you in advance!

This video shows all bosses in the Strato Patrol EOS sub-game from Kirby Mass Attack for the Nintendo DS. This also includes the final boss and ending.

00:00 Whispy Woods
00:46 Kracko
01:32 Mr. Shine & Mr. Bright
02:09 Meta-Knights
04:25 Meta Knight
05:45 Nightmare

▶ Play video
latent latch
#

The AI seems correct to me, a bit slow, but seems adjustable.

#

as for the gameover condition, you should debug your counter to make sure you're appending incrementing values correctly.

strange scarab
#

c# how to pass an anonymous function as a parameter?

lean sail
untold quail
#

It was not a fun challenge :(

#

I am very stuck on this

gleaming tundra
#

I'm having some trouble with iterating through the directories in the resources folder. I know the folder doesn't exist at run time, but I want to get the file path of each scriptable object I'm loading with the LoadAll. Is there an easy way to do that?

#

I was hoping to create a dictionary of full file path as the value and the actual object as a key for the sake of serializing the file path in a save and reloading it later

opaque harbor
#

Can anyone help me with making the camera follow a car asset in my game I can't find anything on the topic.

spring creek
latent latch
#

or just use Load with a list of paths to iterate over

opaque harbor
spring creek
spring creek
opaque harbor
spring creek
# opaque harbor I dragged my asset from the Hierarchy

Ok, it isn't an asset in the hierarchy, it's an instance. But good.
How about showing some screenshots?
The whole editor with the cinemachine virtual camera selected.

You do have a cinemachine brain on the actual camera object, right?

opaque harbor
#

yea i do

gleaming tundra
# latent latch Could probably store the path on the SO itself

It's difficult to itterate over a list of paths because I can't figure out how to get the list of directories in the resources folder at runtime. I tried the following:
Directory.GetDirectories(Application.dataPath+ "/Resources/", "*", SearchOption.AllDirectories);
When ever I use Directory.GetDirectories(), it does't return any of the folders in resources

gleaming tundra
#

I don't know what that means?

opaque harbor
spring creek
#

Please do not

opaque harbor
#

Ok mb

spring creek
#

Wow....

opaque harbor
#

but im mad that nothing is working in unity

gleaming tundra
#

<@&502884371011731486> is it cool to tag y'all on this?

#

Uhhh... Sorry if it's a pain in the ass

vagrant blade
#

@opaque harbor Don't be fucking weird, mind your own business.

opaque harbor
#

Alr

spring creek
latent latch
#

assuming you've all known paths before loading

gleaming tundra
#

I uhhh... don't know all the paths. We aren't keeping the porject organized by asset type, but rather have scriptable objects in many differnt folders based on what scenes they are used in

#

Plus... we have stuff get moved around and reorganized and if I manually set a property that tracks the file path on each scriptable object, it's gonna be a pain to find if we move something

latent latch
#

then storing the path in the object itself could be the idea. Iterate over the list of objects from LoadAll, if it's a type of SO then read defined path and store in specific dict.

#

OnValidate to set path

craggy veldt
latent latch
#

Yeah, AssetID is ideal

craggy veldt
#

note it's custom editor stuff

gleaming tundra
#

I'll try this

gleaming tundra
latent latch
#
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);

// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);```
gleaming tundra
#

Thanks so much y'all

#

Oh wait... Does this only work in the Editor? I think I skipped over the asset data base class doing research cause of that, but I guess I was mistaken?

latent latch
#

meaning you'd instead serialize by the GUID instead of the path

rugged storm
#
    void SpawnUnit()
    {
        nextSpawn = Time.time + spawnDelaySeconds;
        Vector3 playerPos = Player.Instance.transform.position;
        float xOff = Random.Range(0f, 360f);
        float yOff = Random.Range(0f, 360f);
        Vector2 directionToSpawn = new Vector2(xOff, yOff);
        directionToSpawn.Normalize();
        float distanceAwayToSpawn = Random.Range(20f,30f);
        directionToSpawn *= distanceAwayToSpawn;
        Vector3 spawnPos = new Vector3(playerPos.x+ directionToSpawn.x, playerPos.y, playerPos.z+ directionToSpawn.y);
        Instantiate(EnemyPrefab,spawnPos, Quaternion.identity);
    }```
is this a good way to go about spawning an enemy in a range specifically 20-30 units around the player?
latent latch
#

add the minimum to xOff and yOff otherwise looks good

#

or rather I'm not understanding those offsets that you then clamp it with another value

gleaming tundra
#

are x and y off supposed to be in degrees?

rugged storm
#

OH oh actually i just realized yeah, the idea was basically making a random vector to deside the direction they were spawning in, then picking the lenth of that vector but i just realized a better way to do it

#
    void SpawnUnit()
    {
        nextSpawn = Time.time + spawnDelaySeconds;
        Vector3 playerPos = Player.Instance.transform.position;
        float xOff = Random.Range(0f, 10f)+20;
        float zOff = Random.Range(0f, 10f)+20;
        Vector3 spawnPos = new Vector3(playerPos.x+xOff, playerPos.y, playerPos.z+ zOff);
        Instantiate(EnemyPrefab,spawnPos, Quaternion.identity);
    }```
#

i had that before but i was having trouble figuring out how give it a minimum range and i just realized i can just lower the random range and add the minimum to the offsets

latent latch
#

oh it's 3D now im confused haha

#

but basically if you're in the middle and you want stuff to spawn around you by position, then you also have negative values if your character is the pivot

rugged storm
#

i was about to say yeah how can i do negatives...

gleaming tundra
#

If you want the values to be even around a circle, I recomend randomizing the angle and distance

rugged storm
#

basically im making vampire survivor but 3d so i want to spawn enemies all around the player

latent latch
#

circle is actually easier now that I think about it

rugged storm
#

yeah how do i do that tho? like make a vector with a random angle

latent latch
#

random direction + distance

rugged storm
#

thats basically what i thought i was doing in the first snippit i sent

gleaming tundra
#

UnityEngine.Random.insideUnitCircle

rugged storm
#

Oh thats a thing?

somber nacelle
gleaming tundra
#

Then you make sure the y is equal to the Y of the ground at that point

rugged storm
#

yeah the ground is flat atm so i just have it set to player hight as a place holder

gleaming tundra
#

Cool

latent latch
#

yeah, doing direct position around requires a bit more conditional logic

rugged storm
#

Random.insideUnitCircle helps tho

latent latch
#

I think I've tried something like that previously

gleaming tundra
#

alternatively, if you do change the height to vary, you could raycast from (x,arbitrarilly high,z) straight down and get the y of the terrain of on the hit

#

just a thought

rugged storm
#
    void SpawnUnit()
    {
        nextSpawn = Time.time + spawnDelaySeconds;
        Vector3 playerPos = Player.Instance.transform.position;
        //Make vector with random angle
        Vector2 directionToSpawn = Random.insideUnitCircle;
        directionToSpawn.Normalize();
        //Pick distance
        float distanceAwayToSpawn = Random.Range(20f, 30f);
        directionToSpawn *= distanceAwayToSpawn;
        //Spawn Enemy
        Vector3 spawnPos = new Vector3(playerPos.x + directionToSpawn.x, playerPos.y, playerPos.z + directionToSpawn.y);
        Instantiate(EnemyPrefab, spawnPos, Quaternion.identity);
    }```
gleaming tundra
#

Don't need to normalize it

rugged storm
#

this is my final code works well playtesting

#

does it always equal 1 already?

gleaming tundra
#

yep!

#

that's what unit means in unit circle

rugged storm
#

i just checked and that does not appear to be the case, it gets a random point within a unit circle not only along its edge

gleaming tundra
#

oh. my bad

#

sorry

rugged storm
#

were here to learn are we not? 🙂

gleaming tundra
#

indeed!

spring creek
latent latch
# rugged storm ```cs void SpawnUnit() { nextSpawn = Time.time + spawnDelaySecon...
#

vampires has some more detailed spawns beyond just random sampling

gleaming tundra
somber nacelle
#

insideUnitCircle needs to be normalized because it can be anywhere within the circle. onUnitSphere does not because it gets a point on the edge of the sphere so it is already normalized

#

sadly there is no onUnitCircle, but just normalizing the result of insideUnitCircle would be the same

gleaming tundra
#

unless it's (0,0), which is a one in a million error, lol

#

or... more than that, but still

somber nacelle
#

yeah it is very unlikely to get 0,0 since it just uses Random.value for each of the axes

#

though it is technically possible

latent latch
#

just add 0.001 to the values

#

I have a habit of just adding some extra offset values to stuff like directions just to make sure it never zeros out ;)

spring creek
gleaming tundra
#

It would make sense though

rugged storm
#

does normalizing a 00 vector error or just return a 00 vector?

somber nacelle
#

returns 0,0

rugged storm
#

oh kk so i can just check for that cool

somber nacelle
#

don't crosspost

raven basalt
#

How to make the volume louder? I already have the volume to its max, 1, but I still don't think its loud enough.

somber nacelle
spring creek
keen imp
#

Hi again i have a few problem with my tilesmap I don't know if anyone did this but i need to retrieve the tiles that has collider or not is it possible ?

#

the water are my colliders

#

i have two different tilemap the green one is a walkable one the water is nonwalkable and have a tilemapcollider2d

obtuse spruce
#

guys I needed to make a datamanager script for the game and asked chatgpt to generate it , it made me playerprefs script but after asking for secure method I gave me binary method something, and saved the file as data.dat

is it ok to save the progress and resources of player in a strategy game?

somber nacelle
#

i think their question was more along the lines of "is this a good method of saving progress"

spring creek
spring creek
gleaming tundra
#

Hey y'all. My project isn't building because I was usinbg stuff from the unity editor namespace, but I've cut it down to just the OnValidate method of my Scriptable Objects. Is that still a no go?

spring creek
gleaming tundra
#

Thanks

#

Welp, I guess all the SO assets are going into the resources folder after all lol

gleaming tundra
#

Don't use a chat bot to code for you

#

Use it to explain concepts and keep asking it until it explains them in terms you understand

swift falcon
#
//storing rotation in a vector2
private Vector2 currentOrbit = Vector2.zero;
private Vector2 destination;

void Update() {
        //getting the directional vector 
        Vector2 path = currentOrbit - destination;
        path.Normalize();
        
        //using directional vector to get to the destination
        currentOrbit -= path * speed * Time.deltaTime;

        //Clamping values
        currentOrbit.x = Mathf.Clamp(currentOrbit.x, minVerticalAngle, maxVerticalAngle); //clamp orbit angles
        if (currentOrbit.y < 0f) { //maintain that rotation stays between 0-360
            currentOrbit.y += 360f;
        } else if (currentOrbit.y >= 360f) {
            currentOrbit.y -= 360f;
        }
        
        //using currentOrbit to set rotation and location 
        Quaternion lookRotation = Quaternion.Euler(currentOrbit);
        Vector3 lookDirection = lookRotation * Vector3.forward;
        Vector3 lookPosition = target.position - lookDirection * distance; //distance between camera and point
        transform.SetPositionAndRotation(lookPosition, lookRotation);

    }

Hey people, so in the code included I am trying to move my gameobject around a sphere.
This is working so far as I can get the directional vector between my current orbit and destination and adding that vector to my current orbit

Now the problem comes when I am trying to move across the 0-360 line, instead the path is wrapping around the long way to get there

#

here is a (ok) diagram to explain

#

now the path is just a directional vector to clarify

#

so maybe that term is misleading

#

the red line is the 0/360 angle

#

on the y axis

fervent furnace
#
if (currentOrbit.y < 0f) { //maintain that rotation stays between 0-360
    currentOrbit.y += 360f;
} 
```eg if destination rotation is 350 and current is 10, you want rotation of -20 degree on x-z plane, but you clamp the angle so the rotation is 340 degree now
swift falcon
#

Here's a different diagram to explain
note blue is still current orbit and both green dots are the same destination

#

to restate, moving within the black box (representing the vector2 of the sphere, the sphere unwrapped flat) is perfectly fine its just when going through the 0-360 line, it takes the long way to get there

#

please tell me if im not making sense or for any clarification

fervent furnace
#

i know, that is the reuslt, you restrict the angle range from 0 to 360 but it should be -180 to 180 instead

swift falcon
fervent furnace
#

i didnt say anything on the reference frame
imagine your clock, what is the fastest way (or angle) to rotate a hour hand to 12 if it currently is pointing to 3, assume clockwise direction is positive

swift falcon
#

it would be the negative angle in that case

fervent furnace
#

yes

#

so you know why the range of rotation is -180 to 180 now?

#

what ever you start count the clock starting angle from 12 1 2 3.... , the rotation angle is always -90deg

teal delta
#

hey there, can someone point me into the right direction? Im trying to make simple game in wich i need enemies to wonder around and sometimes attack each other or player. By attack i mean throw player into spikes. How can I make enemy like calculate the right angle to push player into his death?

latent latch
#

you'll want to start at a step of the time and first figure out your method of AI and pathfinding

rain minnow
#

crossposting or asking people from other channels for help is not warranted . . .

tawdry pulsar
rain minnow
#

it may take more than 5 minutes for someone to respond. people will help and answer if they know how. also, it's before dawn for most of the active users on a weekend; not the best time . . .

next salmon
#

i have a problem, but first, an example..
an object can have a layer, selected from a list of layers. only one! not several!
a layermask however, can have several layers, selected from a list of layers

im trying to make this sort of thing, but with enums.
i have a AI_Factions enum, that is a multi choice enum:

[System.Flags]
public enum AI_Factions
{
    Resistance = 0,
    Combine = 1,
    Monsters = 2,
    NoTarget = 4,
}

now, i want the class, AI_Target to have this enum, but be able to only select one option from it, just like how you can only select one layer for a game object, orrrr, like a normal enum that isnt multi choice
but i want another class, AI_TargetingSystem to have this enum and be multi choice, just like layer masks or a normal multi choice enum

so how can i make this enum be multi choice in one script, but single choice in another?

latent latch
#

hard to chop up the constraints like if you're passing these enums in a namespace other than the scripts themselves

#

so the answer is either use two different enums, or just stick to the multi and not set multiple types

next salmon
lean sail
lean sail
# next salmon thanks 👍

i dont think you even need to use flags here tbh

AI_TargetingSystem to have this enum and be multi choice
you could also just have a list of the enum

#

not as efficient but 🤷‍♂️ saves you this hassle of trying to enforce this sometimes single, sometimes multi select enum

latent latch
#

problem with list of enums is that you can select multiples of the same enum

#

but it's another thing where you can just "not" set it

next salmon
#

ill just add several bools. this isn't worth the trouble

latent latch
#

really, most of these problems are more editor related than code

#

which can be fixed via custom editor or on validate

frozen fjord
#

I sorta want a translucent object, which channel would be best for that?

latent latch
lean sail
# next salmon ill just add several bools. this isn't worth the trouble

i think out of all the options, adding several bools is probably the most tedious solution since whatever this is checking might cause issues down the line.
Really the solution is either just dont set multiple values (you could use some OnValidate thing to ensure only 1 is checked)
or
do what i said with a list and keep in mind what Mao said about not selecting multiple of the same enum. This wouldnt even be an issue realistically as it would just run a check against 1 extra entry

rain minnow
fervent furnace
#

bitwise and

bitter oar
#

how do i rotate an Image in a canvas with code?
i tried to make the scale negativebut the image just show nothing when i do that

rain minnow
bitter oar
#

what do you mean?

#

oh sorry

#

but can you help me?

rain minnow
bitter oar
#

ye i know

rain minnow
#

nah, it's almost 5 am; i work at 8 am. need sleep . . . 😫

bitter oar
#

okay no problem

lime gazelle
#

why cant i just say "E" anymore?

fervent furnace
#

what E, is it even related to unity

lime gazelle
#

idk

#

i was just testing

hidden parrot
#

"Please use complete sentences with full context. You can also edit your previous messages."

lime gazelle
#

k thanks (tbh i meant to say it in another server)

naive heron
#

is there a way i can make the transition duration from the idle state to the run state cancel if my shoot state gets triggered???? it looks really weird because my shoot animation only plays after the transition duration finishes so it looks really messed up... ive been trying to fix this all day by just making it so you cant shoot for a second after you start sprinting but it never worked

trim rivet
#

baffled by this issue... why isn't it 0.5 ?

fervent furnace
#

ofc integer division

trim rivet
#

I don't understand, it's 0 because I'm passing integers ?

#

i guess it rounds it down ?

fervent furnace
#

if positive=>floor
if negative=>ceil

trim rivet
#

🤔 interesting

fervent furnace
#

not always round down, btw beginner stuff

soft shard
fervent furnace
#

not the type of denominator
int/float or float/int return float because int is casted to float

soft shard
#

Oh really? I remember doing some type-math outside of Unity before, and wouldnt always get consistent results unless the denominator was cast to the type I wanted, didnt know you could also cast the numerator for the same result

trim rivet
#

thank you guys for the quick help!

#

really appreciate it

cold egret
#

- If i have an editor-only methods for monobehaviour (related to validating components presence as an example) that are both placed in the preprocessor directive and given a conditional attribute, will the project build without failing and without compiling either the methods nor the calls to them?

teal lantern
#

I used the input field for this kind of chat, but when i build to android and use google play pc emulator for testing keyboard, i can not use Enter key to execute the ok button, anyone know the piece of code, reference?

heady iris
simple egret
heady iris
#

this makes the conditional attribute a bit pointless, since any attempt to call the method in a build will produce an error anyway

simple egret
#

What you can try to do if it's used everywhere is make the class partial and declare the methods without a body, so when it compiles it just compiles the partial class that's empty

cold egret
heady iris
#

The method doesn't exist at all

#

neither does the conditional attribute

#

it's all gone

simple egret
#

Yes provided that you put it everywhere

heady iris
#
#if UNITY_EDITOR
[Conditional("UNITY_EDITOR")]
public void Foo() { }
#endif
#

If UNITY_EDITOR is not defined and I try to call Foo(), none of that code exists at all

simple egret
#

Assuming "attribute" as the #if preprocessor directive instead of a C# attribute like [SerializeField]

simple egret
#

Who uses that lol

heady iris
#

it tells the compiler to ignore method calls

#

I think the idea is to prevent major parts of your program from appearing and disappearing depending on build settings

heady iris
#

Neither does the Conditional attribute.

cold egret
#

- I see. Exactly what i was not certain about. Damn, it'd be so cool to have a way not to exclude methods automatically, without keeping in mind that every single call has to be wrapped in the directive, but sigh

heady iris
#

you could put the entire body in an #if directive and then make the method conditional, I guess

#

or just make it conditional

heady iris
cold egret
raven orbit
#

I have messed with every setting under the sun and my GithubAction using Game-CI will just always take 1000s to render out these 432 variants

cosmic wasp
#

I have a function named IsGrounded(), when I call it, it returns true or false.

Is it possible to call this function in a if-statement?
I tried this but it didn't work:

        if (IsGrounded())
        {
            // code
        }
cosmic wasp
knotty sun
#

then IsGrounded does not return bool

hard viper
#

I'd like to ask a question about assemblies. If I understand correctly, if I make an assembly, Unity auto-adds every .cs in that folder to the assembly. Then unity compiles these assemblies, and if file1 depends on file2, then... how do I make it depend correctly

#

also, can I add a file from one folder to an assembly in a different folder?

#

I'm just trying to figure out how to add assemblies without breaking everything, as I learn this tool

round violet
#

when using GetComponentInChildren, it will loop in all direct childs until it founds the component or null if all childs were scanned ?

hard viper
round violet
#

okay ty

hard viper
#

remember it WILL check self! very important

round violet
#

regarding your question about dependencies

lets says you have a folder Player, with your script(s), and a AD
and a folder game elements with your script(s), and a AD

if inside a script in Player you want something that was (for i.e) declared in game elements, Unity will not find it and you will get a error in VS (like "class not found"), you will have to add in your Player AD a dependency to game elements AD

knotty sun
round violet
hard viper
#

ok, so let's say I am adding assemblies now to my project, and I have a rough idea of like a graph in my head of how the dependencies go

#

I have some files just in the standard C# assembly, but they depend on something that is now in a different assembly. How do I get around this?

knotty sun
#

usually by using namespaces, all asm def.s have Assembly-CSharp as a dependency

#

generally I just cut out the crap middle man and make .dlls outside of Unity and add them to a plugins folder

hard viper
#

I'm just trying to link things in a non stupid way right now, without breaking all of my code, as I have not been using namespaces, but I want to start bringing things in

#

and it will be very hard for me to add this if I can't know if something works until after I go through a giant project

knotty sun
#

namespaces are a must when splitting code over multiple .dlls

verbal grail
#

I have a class that has method which starts a co routine. If I instantiate that class, save it to a private variable, execute the method that starts co routine. Then assign the variable that hold that instance to null, will the co routine continue till finished or will GC flush it down the drain?

knotty sun
#

if you want to test stuff and have all the code for an assembly inside one folder just make a dll project in VS, add the code to it and the correct Unity references and see if it builds

leaden ice
hard viper
#

I'm just confused right now because I have all these files in folders that are not split up by dependencies

verbal grail
#

Thx

hard viper
#

I split them up in a different way. is there maybe a plugin to make custom DLLs easily?

knotty sun
#

no plugin required, it is standard VS

hard viper
#

how about to find how my classes depend on each other, so I can more quickly see how I might want to split DLLs

knotty sun
#

you wrote the code, you should know that already

rancid frost
#

I am making a 2d hex mesh grid.
How do i layer my mesh ontop one another?
For example, when highlighting, I will simply add a highlight mesh ontop of the base mesh, and increase is y offset.
Is there a better way to go about this?

hard viper
#

so.... is the first order of business to put everything into namespaces by the DLL I want them to be in?

#

or is there a way to do this without starting with all the namespaces

knotty sun
#

yes and by putting them into namespaces this will highlight the dependencies

#

this is why we design code before writing it, so we dont get this kind of shit

hard viper
#

I didn't fully understand making my own namespaces before hand. Never worked on a project so big before

simple egret
#

Unity developer moment
In regular C# app you get 1 namespace per physical folder, along with the root namespace named the same as your project

foggy sentinel
#

Does someone know a better way I could retain the momentum of the player between walking jumping state. I am using a state machine for player movement. I coded the jumping state so that the player stops moving in the air when the horizontal axis is 0. But doing this stops the player when they jump already moving. I coded it so that if the player is moving it wont allow change in direction until one of the Horizontal buttons are pressed but that has problems as if the player presses the same direction they are moving in they just stop.
https://hatebin.com/vdgiqqqgwo

knotty sun
simple egret
#

I didn't say otherwise

#

I just said that, in apps out of Unity, namespaces will be pre-generated according to the folder structure

#

Whereas in Unity by default it just crams it all into the global namespace

#

So it's just funny that C# devs that only used Unity have never been introduced to namespaces as soon as "others"

knotty sun
#

and yet they use namespaces all the time in using statements, meaning that they didn't learn very well

steel silo
#

hello guys do somone have time to help me with simple script? its gonna take max 5-10 min if u are not begginer like me

knotty sun
hard viper
#

how do you check if the information in an object of type Type is valid or not?

#

eg points to an actual type

simple egret
#

Not null?

cold parrot
hard viper
#

won't that return an error?

cold parrot
knotty sun
heady iris
#

I don't think you can construct a bogus Type object

#

is would be relevant if you were checking if an object is a certain type. that's not what is going on here

outer brook
#

Hi, so I made it so that the player has a 'do not destroy on load' enabled and that works fine however I have an issue with UI image for the health bar which I tried slapping 'do not destroy on load' but it didn't seem to like it, not sure how else I could do it other than have the health bar images be inserted into the player rather then on the canvas which might have it's own issues

heady iris
#

what do you mean "doesn't seem to like it"

#

do you mean you got an error because you didn't call it on a root game object?

outer brook
#

maybe remove 'more than one'

heady iris
#

You won’t be modifying the visual scripting code

#

Sounds like you’re not supposed to mess with the object that’s holding the VS variables. Not sure how you’ve got this set up..

outer brook
#

hmmm I see, well thanks anyway it just means I have to push it aside for now

dapper hinge
#

Need some help with figuring out the problem.

This is my walljump code:

private void WallJump(RaycastHit2D rightRaycast, RaycastHit2D leftRaycast)
    {
        // Calculate wall jump direction
        float wallJumpDirection = 0;
        
        if (rightRaycast.collider != null)
        {
            wallJumpDirection = -1f;
        }
        else if (leftRaycast.collider != null)
        {
            wallJumpDirection = 1f;
        }
        
        // Reset velocity
        rb.velocity = new Vector2(0f, 0f);
        
        // Apply wall jump force
        rb.AddForce(new Vector2(wallJumpHorizontalForce * wallJumpDirection, wallJumpForce), ForceMode2D.Impulse);
        isJumping = true;
        isWallJumping = true;
    }

I have confirmed that the raycasts passed are correctly set, as such, the walljumpdirection is also set properly. In this case its -1

I reset the velocity of the player to 0 on both axis, then add a force up and to the direction the fall is facing.

For some reason even though the walljump is detected, and the force gets applied, it is doing so inconsistently and I don't know why

fading swan
#

I have such a problem, created a territory unity 3d, but when I want to add more height, nothing comes out and it does not change (Same problem with downsizing)

brisk reef
#

you want it to push the ball away from the wall

#

or else it either makes you be able to wall jump infinitely

#

or bugs out

#

also, define weird movement

#

it being moved away from the wall is weird?

proper ridge
#

I made this simple auto tiling script and I wonder can I somehow do that these values could update in editor instead when game starts?

hard viper
#

lets say I have an instance of MyClass?, and I want to make an extension of it where, if the instance is null, we get a specific result. eg : public static bool IsValid(this MyClass? inst). How do I make this work?

proper ridge
#

So when I change scale of the transform in editor it would show me how textures look before I played game

rugged storm
#

is there a way to make a corutine run in paralell with fixed update? like would this work?

    IEnumerator SeekPlayer()
    {
        while (true)
        {

            yield return new WaitForFixedUpdate();
        }
    }```
somber nacelle
#

that would make it yield until a FixedUpdate frame, so yes it will run in time with FixedUpdate. do note that it will finish yielding after FixedUpdate has run that frame though

dapper hinge
dapper hinge
#

I'm pushing the player to the side and also up

#

so it should act like a diagnol jump but its not

#

and it doesn't always do this. That's what is bugging me the most

hard viper
#

is there a way for me to automatically try to make assemblies that obey namespaces?

#

like, I now have several classes and files where basically everything in the file is in a given namespace. is there a simple way to… put them together in a .dll by namespace, and let the computer try to figure out dependencies in a way that is not shit?

#

also, is an assembly a function of the class or the file?

somber nacelle
#

sort of the file, i guess. in a normal project your different projects are each their own assembly. in unity you can use assembly definitions to break your code up into multiple assemblies

hard viper
#

I see. but asmdef are all immediately a function of the folder, correct?

somber nacelle
#

well yes, but if you have classes that should be in separate assemblies why would they be in the same exact folder?

hard viper
#

i have more of the opposie problem, of files that I want in one assembly in separate folders

normal quest
#

Hey guys

Short question: How do I detect whether if an scene has been loaded because the application started or because another scene loaded it?

Long question: I have opening and closing animations for scene transitions. The main scene is the Main Menu, which is the first scene to be loaded when the game starts, but you can also reach it by returning from the game. In order for animations to work properly I need to check if the Main Menu scene was loaded because the application started or if it was loaded by returning from the game scene

hard viper
#

you can use a singleton that is don't destroy on load to be notified of whatever happens

somber nacelle
#

or just a static variable that is only changed after the first time the scene is loaded

normal quest
#

yeah, i was thinking about a dirty solution like that

somber nacelle
#

is that really a dirty solution though? 🤔

normal quest
#

a more elegant solution would be if unity had a tool that can check it for u

#

anyways, there is no need of a headache for something that simple lmao

hard viper
#

yeah, don't go static

#

make a singleton

somber nacelle
#

but that is also static . . .

normal quest
#

xD

hard viper
#

but it feels better

normal quest
#

i already have a "GameInfo" static class so i'll use that

somber nacelle
#

why though? a single bool being static and kept in memory versus an entire object kept in memory for the duration of the game

hard viper
#

it's a lot easier to manage a single singleton class implementation, which manages its own private static instance

#

maybe static is just the way to do it, tbh. use it or lose it

#

realistically, you probably do want a singleton, because you will probably keep more than one bool. A singleton could help manage general interscene data transfer.

#

because later it'll grow from a bool, to a bool, an enum, a list, another enum, and 5 more bools

somber nacelle
#
private static bool hasLoaded;
private void Awake()
{
    if(!hasLoaded)
    {
        DoInitialLoadStuff();
        hasLoaded = true;
    }
}

is literally all that is needed

normal quest
lean sail
#

static bool is definitely just fine here, singleton doesnt make sense here unless you actually need an instance. At that point you might be doing too much with one script. Any other "clean" solution is just going to be unnecessary for the sake of feeling like you're doing it properly

somber nacelle
#

remember the KISS principle

normal quest
#

keep it simple stupid 🤣

#

love that

#

btw no mean to offense @hard viper

quartz folio
#

Also remember to selectively apply DWW and WGAS, two terms I just made up
(do what works, and who gives a shit)

hard viper
#

I have a Singelton<T> : MonoBehaviour class that I downloaded, so all I need to do to make a block of code a singleton is make it: public class MyClass : Singleton<MyClass>

normal quest
#

yeah I know, I also like doing stuff properly, but when you are one week before launching your game... anything works

hard viper
#

I downloaded my singleton implementation lol

heady iris
#

do you even GLRT

quartz folio
#

good luck, really terrible

heady iris
#

sometimes i look at blog posts about OOP jargon

#

and I wonder if these people ever actually write code

quartz folio
#

yeah, the "is this aggregation, composition, or neither" question yesterday really did me a number

hard viper
#

every time I add an asmdef to my unity project, the scripts in that folder can no longer find things from the rest of my project. How do I allow code from one assembly to access the main C# assembly? or is that not correct?

quartz folio
hard viper
#

i figured I was doing it backwards somehow

heady iris
heady iris
#

Could you just throw an asmdef into the Assets folder to put everything into a "default" assembly?

#

I haven't thought about how that'd behave

quartz folio
#

Yes, as long as you handle all the Editor folders

hard viper
#

I keep looking at that page, but I don't understand the flow, since I have many files outside of assemblies, and in the default assembly

heady iris
#

those suddenly don't work anymore

quartz folio
#

The "default assembly" is Assembly-CSharp

heady iris
#

(and no file can be "outside" of an assembly)

#

the scripts merely aren't covered by an asmdef

hard viper
#

yeah, but that means they are in the default C# assembly

heady iris
#

you can imagine there's an asmdef in the root of your project that slurps everything into Assembly-CSharp

#

(except for Editor folders, as vertx mentioned)

quartz folio
#

(which are Assembly-CSharp-Editor)

heady iris
#

this reminds me of something, actually

#

Several parts of my codebase could currently be put into an assembly very easily

#

like my settings system, which doesn't care about anything else in the project

lean sail
heady iris
#

...actually, nevermind, just answered my own question lol

#

I can just asmdef the "core" of that system and then extend it outside of the assembly if I want something to be able to see the rest of the project

#

just like how you'd extend a third party library by creating scripts that aren't in its assembly, assuming you don't need internal access

hard viper
#

ok, so let's say I have: Class1.cs (everything in project needs), Class2.cs (needs Class1), Class3.cs (needs Class2)... How do I set this up? does my folder structure need to match this?

heady iris
#

Assembly Definition Reference assets let you include another folder in an existing assembly

quartz folio
#

folders only matter if there's assembly defs in them controlling the assemblies

hard viper
#

sorry, I've just never worked with assemblies before

heady iris
#

an actual example might be more useful

#

suppose you have 100 scripts that implement some self-contained feature

#

like a graph library. it has classes for nodes and edges and lots of graph algorithms

#

it doesn't need to see the rest of your project. it can stand entirely on its own

#

this is a good candidate for an assembly definition

#

you'd put all of those scripts into a folder (or into a subfolder) and stick an asmdef asset in it

hard viper
#

so... do I start by putting one asmdef at the root of my project, which would then include everything, then give subfolders their own asmdefs?

heady iris
#

hang on, finish this example first

#

does it make sense to you?

#

The motivation here is that you no longer need to recompile that giant pile of scripts every time you make a change to your game

hard viper
#

ok, so an assembly should be self-contained

heady iris
#

In this simple case, yes.

#

it's the most obvious way to use 'em

#

Now suppose you've got a second library. It depends on the graph library.

#

But it's otherwise self-contained.

#

You could shove it into the graph library's assembly

#

Or you could make a second assembly definition for the second library.

#

When you do this, you will get a truckload of errors.

#

The second assembly cannot see the graph assembly.

#

That's where these references come in.

hard viper
#

so the second needs to ref the first?

heady iris
#

You can reference the graph assembly from the second assembly.

#

Exactly.

#

These references must be explicit because...

#

"auto referenced" applies just to the pre-defined assemblies

#

Manually defined assemblies only see things in their list of references

#

So Assembly-CSharp.dll automatically sees both of these assemblies, unless you untick that box

#

The assemblies form a directed graph.

#

critically, you can't have cycles in this graph

#

if A references B, B can't reference A.

#

because how would you compile them? they need each other

hard viper
#

i got that. I just don't know how to split

heady iris
#

okay, good

heady iris
#

you usually make the "main" assembly -- the default Assembly-CSharp.dll one -- reference all of your other assemblies

#

(that's what auto-referencing does)

hard viper
#

so let's say I have 100 scripts all in one default asembly. I now identify a group of 10 scripts that depend on each other, depend on the other 90, but none of the other 90 depend on them

#

how do I split this off (so I can slowly make my way to splitting everything)

heady iris
#

The other 90 would need to be placed in folders with either an Assembly Definition asset (which actually...defines the assembly) or Assembly Definition Reference assets (which include more folders in the same assembly).

#

the 10 scripts would remain in the default assembly

hard viper
#

so for this, can I put one asmdef in the root folder that contains all 100, then put another asmdef in a subfolder with those 10 which I identified

heady iris
#

I suppose you could, yes.

#

It does feel awkward, though.

hard viper
#

and then slowly work my way back

#

i just need to break up this problem into smaller problems that I can chip at until it' s all done

#

but if I don't take the first step, I'll never make any progress

quartz folio
#

I have my scripts set up like:

Scripts
├── Editor
│   ├── MyEditorExample.asmdef
│   └── EditorScriptExample.cs
└── Runtime
    ├── MyRuntimeExample.asmdef
    └── RuntimeScriptExample.cs
hard viper
#

and I think that makes sense

quartz folio
#

and then any rando asset store assets:

External
└── AssetStoreAsset
    ├── AssetStoreAsset.asmdef
    └── Editor
        └── AssetStoreAssetEditor.asmdef
heady iris
#

Yeah, I've started doing that with large packages that wound up in Assets

hard viper
#

but then how does runtime code see AssetStore code

quartz folio
#

it references it in the asmdef

heady iris
#

also note that the "Editor" asmdefs need to be set so they don't get included in non-editor platforms

quartz folio
grizzled ferry
#

Hey, I'm having some trouble when working with a dinamically made Texture2D in my project.

Context: I'm working on an asset with my mate @tranquil canopy. We use this method in order to generate a blur texture, and then apply it to a button in one of our custom editors... But only my teammate sees the button with its correct texture... Not me or any user who downloads the asset.

private static Texture2D MakeText(int width, int height)
{
    Color[] pix = new Color[width * height];
    Texture2D result = new Texture2D(width, height);
    result.SetPixels(pix);
    result.Apply();

    return result;
}```

Here goes the crazy thing: If my partner uses a white texture (``Texture.white``) instead of the method I've shown, he still **does** see the button with the correct texture... What might be wrong with his Unity project?

This is how I and other users see the buttons:
#

And @tranquil canopy can you show how the buttons should be seen? (How you see them)

hard viper
#

I just put one .asmdef in my main root assets folder. I now got this error:

error CS0006: Metadata file 'Assets/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll' could not be found```
How would I resolve this sort of error?
#

I do have the .dlls, and can find them in a subfolder covered by the asmdef

quartz folio
grizzled ferry
quartz folio
quartz folio
hard viper
#

you mean my asmdef should reference the dotween dll?

quartz folio
#

Yes

quartz folio
grizzled ferry
#

Then that style is passed to GUI buttons as a parameter

quartz folio
#

well, you generate a 2x2 transparent texture and assign it to a button, so it should just hide the button

grizzled ferry
tranquil canopy
#

yeah... i see this with the same unity version and the same unity proyect...

#

and the same code...

quartz folio
#

can't you just set the background to null? Why even generate a texture?

safe comet
#

ah my bad

tranquil canopy
grizzled ferry
hard viper
#

without even splitting them up, I'm just trying to see if I can get them to see each other

quartz folio
hard viper
#

ok. I thought I was still doing something wrong. crtical step

quartz folio
#

EditorStyles has a bunch of stuff

hard viper
#

ok, now none of my scripts can see anything covered by anything in the plugin assembly, which I think is correct?

#

because my plugin folder with asmdef is a subfolder of an asmdef with everything

#

so if I understand correctly, I need to get that into a separate folder, so my own scripts can have an asmdef that depends on external asmdef

#

then unity will automatically make the assembly for external, make assembly for my scripts, and make my scripts depend on the external. right?

grizzled ferry
normal quest
#

How can I "unlink" child rotation from parent rotation? I need a gameObject to follow another one so I made it its child, but I dont want the child object to rotate with the parent object, can I achieve this?

somber nacelle
#

don't make it a child. use a position constraint to make it follow the object instead

hard viper
#

idk everything in my project is just totally broken now. I need to step away from this

misty blade
#

Where should default values for a game be stored and loaded from? For example, if I have a class handling the picking up of objects and want to play a pickup sound that will be the same for all of these objects, then where should this class look for its sound? My first idea was to serialize the audio clip, but then I would need to manually set all clips in all pickable objects. Then I thought of creating a 'DefaultValues' MonoBehaviour with a static instance that would store all 'default' values, but I'm not sure if that's the right way.

normal quest
#

Well I made a static class and put a lot of public info on it, but it depends on what you want to achieve, maybe for you it is better to use unity events and handle everything inside an Audio Manager gameobject

misty blade
#

might also do it with a static class

normal quest
misty blade
#

i meant a script that is attached to pickable objects

normal quest
#

and what if you have a prefab of a pickable object and just use OOP to customize them?

misty blade
misty blade
normal quest
normal quest
misty blade
#

right

#

and your right about encapsulation, but it helps me organize the code and when I comeback to it after sometime it's easier to understand

shrewd mulch
#

how can i make it so when a object is childed in code the object scale doesn't change

lean sail
lean sail
shrewd mulch
#

because i want it to also move with rotation

lean sail
shrewd mulch
#

but do you know a way to make the scale not change

lean sail
shrewd mulch
#

alright

rugged storm
#

im trying to make a vampire survivors like game but as an fps and I'm not sure how to go about replicating the endless map, the player should intheory be able to hold w for hours and never reach an edge

#

should i implement it like procedural generation? creating new level chunks once a player nears an edge?

lean sail
spring creek
elder flax
#

Hey I'm trying to remake an old python game of mine, in it i had a window that was exactly 1366x768, the 'camera' was the entire screen

#

the unity orthographic camera doesn't seem to follow that exactly though, i can't make it fit a 1366x768 scaled up square sprite exactly

#

I can only get it to match the width or height, not both

rigid island
dense rock
#

Hey, is there a way to have an variable of type enum? Like a variable that stores an enum type

quartz folio
#

Does that work 🤔

spring creek
#

It would be the Enum types type

quartz folio
#

Enums are backed by a number of types, so just use that type, like int

fervent furnace
#

Enum is a type and variable declaration is <type name> <name>

#

I think he doesn’t mean store the “type“ of enum

quartz folio
#

I am unsure of the value of storing an enum in Enum (boxing, etc), but it does seem possible

dense rock
#

i want to have an enum in inspector, which is dynamic and set via code

quartz folio
#

I would use int

dense rock
#

how would I reach that goal with that?

quartz folio
#

or whatever the backing type is, and wrap it in a struct or something

#

enums are backed by an int by default, so just treat the int the same you would the enum

spring creek
dense rock
#

yess

#

the first one

fervent furnace
#

Flags

quartz folio
#

I don't think it's enum flags is it? Can you describe what the purpose is

fervent furnace
#

Like layermask you can choose multiple value? If yes then flags

quartz folio
#

They didn't agree to multiple values, they agreed to multiple Enum types

#

They need to clarify what this is for

spring creek
# fervent furnace Flags

I think they mean like they have a couple enums, like
enum EnemyType {
Goblin,
Dragon
}

enum ArmorType {
Heavy,
Light
}

And have a field that could be either of those enums

My examples are obviously probably way off

dense rock
spring creek
#

That would certainly be best haha.
XY problem

fervent furnace
#

Even if it is possible then how you can differentiate the value in your code, as vertx says they are int

quartz folio
#

Presumably they would need to declare another field next to the int that describes the type

dense rock
#

okay its a little complicated and im tired so my head cant wrap around it.
I have a dialog class which stores a string and a List of Options.
Each option now has multiple Conditions. A condition references an SO, which stores just a value and checks it against another value of the same type with an operator chosen from an enum.

#

So i have a generic scriptable object with value of type T, and I'd like to have one generic condition class which can manage all the different operators that the types would use to compare to one another

latent latch
#

what values are being compared here

dense rock
#

ints, bools, classes, pretty much everything

latent latch
#

I can think of some terrible ways to do it on the editor, but usually you need the known type so it can be serialized

dense rock
#

I was trying to do some easily expandable way, but maybe its just no good to try

latent latch
#

meaning that compare value field needs a specific type to probably show up in the editor

dense rock
#

I can also just make 2 more scripts for each type i want to compare

latent latch
#

So, I'd relate the field to the type of script like you have here. If we know it's containing an int to compare then you need to show a compare value field of int

dense rock
#

thats the problem, I want to assign the SO (Value) first, then check its type and then choose the operator and compare value

latent latch
#

so conditions or w/e this script you're using to display in the editor should contain all methods of comparison and change (what's displayed on the editor) depending on script type

#

which requires custom editor / showif hideif attributes

dense rock
#

So I have one member for each operator enum i have?

latent latch
#

Yeah, declare values but don't instantiate them if you're not using

#

or rather you have a value for each type that you want to compare

#

probably need to make different enum types depending if it's a bool or value type too

#

(or maybe a way to restrict what's displayed on the editor on the enums, but that sounds like more work)

still stag
#

Is it possible to open a mobile devices keyboard by tapping on an input field in a webgl build? I'm running 2022.3.

latent latch
#

I think the keyboard does automatically open through active input fields

still stag
#

That's what I thought. But after publishing my build it didn't open on my phone or my wife's. Might be missing a setting or something.

latent latch
#

there is methods to request the keyboard from the device, but I don't think I've used them

#

I usually prefer to develop an in-game keyboard anyway because some device keyboards are too large

still stag
#

If it was a larger project I would make my own. It's just a small project to keep me busy over winter break and mobile was an after thought tbh. If it's not going to be a quick thing I'm just going to cut it. Thank you for the help.

hidden flicker
#

How do I reference a point relative to another object? Basically, "move object to 1 meter in front of this other object"

latent latch
#

object's position + object's forward direction * units

fervent furnace
hidden flicker
#

ty

#

that's what i suspected but it seemed off

fervent furnace
#

you cant reference a "point" (value type) at least impossible in managed language

hidden flicker
#

i meant a position

fervent furnace
#

so calculate it immediately when you need it (then cache it if the value is immutable)

hidden flicker
#

yeah

#

that's what i was planning on 👍

hidden flicker
latent latch
#

could you clarify what you mean and what should it be doing

hidden flicker
# latent latch could you clarify what you mean and what should it be doing

When I move right, the shotgun should move right. When I move forward, the shotgun should move forward etc. Currently, it does that just fine... until I rotate and everything messes up.
The weapon's movement relative to me changes depending on my player's rotation in worldspace, which I don't want.

latent latch
#

is the gun a child of the player

hidden flicker
#

An indirect one, yes

latent latch
#

as in not child on the hierarchy?

hidden flicker
#

It is on the hierarchy, just some layers down

latent latch
#

so the player's rotation is affecting the children, yes

latent latch
#

well, it does make sense to keep it a child

#

but if the local rotation values are messing up how you want it then make the gun a sibling to the player and just update the position directly through the script.

hidden flicker
#

I would prefer not to do that... is it possible to fix the problem while keeping the gun a child of the player?

latent latch
#

im not exactly sure of the precedence of setting the rotation with the local rotation also setting it, but you can try that, otherwise there's things like animation constraints which is some unity component

hidden flicker
#

I'm not sure how that would help

#

All I want is for the weapon to move with the player's velocity

latent latch
#

can't really make out what's wrong with the rotation on the weapon in the video and how rotating is affecting the gun, but if the gun is a child to the player it'll always move with the player, so perhaps some additional logic for how far the gun can extend from the camera depending on the velocity is my guess (via local coordinates)

latent latch
# hidden flicker

Oh, I see what you're talking about now. It's a little subtle but I'm not sure why you've got rotation affecting it. It should just sway in the direction of the velocity, or direction the player is moving in.

hidden flicker
#

Yes, thank you

latent latch
#

well, velocity implies direction ;p

hidden flicker
latent latch
hidden flicker
#

Isn't that what I wrote in the code?

latent latch
#

slerp is spherical rotational interpolation

#

I actually didn't see your code there, my bad.

hidden flicker
#

Nah it's ok

#

Slerp was not the issue

rigid island
#

lerp looks wrong too btw

hidden flicker
#

It really doesn't seem like that would be causing the issue, though

#

What should I use

rigid island
#

the value of t for lerps is 0-1

#

you're putting some arbitrary high number

hidden flicker
#

I'm putting 0.001

rigid island
#

swayspeed is 0.001?

hidden flicker
#

Yes

#

I guarantee you that is not the problem

rigid island
#

not saying it was but still wrong

hidden flicker
#

It's a direction issue, not a magnitude one'

rigid island
#

you're missing a steady increase/decrease timerate

#

your fps will affect it rn

hidden flicker
rigid island
junior wind
#

In a 3D project, is there any way to make vector arithmetic work with transform.position in 2D?

example Vector2 direction = vCenter + vAvoid - transform.position;
operator '-' is ambiguous on operands of type vector2 and vector3

#

or is my solution to break it up into x,y components each time

fervent furnace
#

cast the vector3 to vector2

latent latch
#

probably better to upcast to a vector3

#

then discard or not use the z values

fervent furnace
#

No if the z value will be discarded then dont waste time to compute it (if not involved in calculation)

junior wind
#

yeah not worried about the Z in this case. Just trying not to rewrite a half dozen of vector operations as adding components

hidden flicker
frosty cargo
#

There's a scene + assets in my project that's loaded with addressables. I am reading that I have to convert any prefab loads via resources to addressables in that scene? Is that right? Couldn't I just take those prefabs and put them in the scene itself to bypass having to do that?

astral relic
#

hello im a bit confused about unity's matrix.
this gives me (0, 1, 0)

var mat = Matrix4x4.TRS(new(0,1,0), new(0.7071068f, 0,0, 0.7071068f), new (1,1,1));
print(mat.GetPosition());```
while the same code in System.Numerics gives me (0, 0, 1)
```csharp
var scaleMatrix = System.Numerics.Matrix4x4.CreateScale(new(1,1,1));
var rotationMatrix = System.Numerics.Matrix4x4.CreateFromQuaternion(new(0.7071068f, 0,0, 0.7071068f));
var translationMatrix = System.Numerics.Matrix4x4.CreateTranslation(new(0, 1, 0));
var mat = translationMatrix * rotationMatrix * scaleMatrix;
if (System.Numerics.Matrix4x4.Decompose(mat, out var scale, out var rotation, out var translation))
{
    print(translation);
}```
why ? does unity matrices work different or what
quartz folio
#

I haven't looked into your numerics TRS logic, but it doesn't make sense that the position you get out of TRS would be anything other that what you put in

#

Your TRS logic is likely backwards

astral relic
#

what does backwards mean

quartz folio
#

The multiplications are back to front

fervent furnace
#

when apply transformation usually => p*s*r*t
so it should be s*r*t