#archived-code-general

1 messages Β· Page 90 of 1

leaden ice
#

unless one or more of these colliders is a trigger

rain minnow
#

☝️ especially, if you're using OnCollision messages . . .

sacred sleet
#
void GenerateRivers()
{
    // Adjust these parameters as needed
    int riverCount = 2;
    int riverLengthMin = 10;
    int riverLengthMax = 20;

    for (int i = 0; i < riverCount; i++)
    {
        int x = random.Next(0, width);
        int y = random.Next(0, height);

        // Check if the starting point is on land
        Vector3Int startPosition = new Vector3Int(x, y, 0);
        if (landTilemap.GetTile(startPosition) != landTile)
        {
            i--; // Try again if the starting point is not on land
            continue;
        }

        int riverLength = random.Next(riverLengthMin, riverLengthMax + 1);

        // Generate the river path
        Vector3Int currentPosition = startPosition;
        for (int j = 0; j < riverLength; j++)
        {
            // Place the river tile
            structureTilemap.SetTile(currentPosition, riverTile);
            landTilemap.SetTile(currentPosition, null);

            // Move to the next position
            int direction = random.Next(0, 4);
            switch (direction)
            {
                case 0: // Up
                    currentPosition += Vector3Int.up;
                    break;
                case 1: // Down
                    currentPosition += Vector3Int.down;
                    break;
                case 2: // Left
                    currentPosition += Vector3Int.left;
                    break;
                case 3: // Right
                    currentPosition += Vector3Int.right;
                    break;
            }

            // Keep the river within bounds
            currentPosition.x = Mathf.Clamp(currentPosition.x, 0, width - 1);
            currentPosition.y = Mathf.Clamp(currentPosition.y, 0, height - 1);
        }
    }
}

what here makes my code crash?

leaden ice
#

if that keeps happening the loop will run forever

sacred sleet
#

I see thx

tropic quartz
#

@deep fable
I think that in a lot of games with big stadiums they render the closest people as 3D and the further away ones are just 2D textures.
I think they use Blender (or w/e 3D program) and made an animated render of the 3D people so that the textures look like the 3D models from a distance.

This is just something that I've read and I don't have experience with it myself.

sacred sleet
lament mural
#

Bumping: So I have the following problem: I'm using a rigidbody for my character. It has a physics material of friction 0 and bounce 0 (uses min value for both). Friction is 0 because I'm calculating and applying friction manually when the character is grounded.
When my character lands on a slope from a long fall, it slides a little before it stops.
Any ideas on how to prevent it from sliding on landing? I tried canceling velocity on OnCollisionEnter and also on FixedUpdate but nothing seems to work. I'd rather avoid Update because I want to keep the movement as frame-independent as possible.

coarse gull
#

Can someone help me? My character is rotating and moving nicely taking in consideration the cinemachine direction, but when I release any input key it keeps the movement infinitely in the last direction calculated.

    void Update()
    {
        ApplyRotation();
        ApplyGravity();
        ApplyMovement();
    }

    private void ApplyGravity()
    {
        if (IsGrounded() && _velocity <= 0.0f)
        {
            _velocity = -1.0f;
        }
        else 
        {
            _velocity += _gravity * _gravityMultiplier * Time.deltaTime;
        }
        
        _moveDirection.y = _velocity;
    }

    private void ApplyRotation()
    {
        if (_input.sqrMagnitude == 0)
        {
            return; // No input == keep current direction
        }

        var targetAngle = 
            Mathf.Atan2(_direction.x, _direction.z) * Mathf.Rad2Deg + _cam.eulerAngles.y;
        var angle = 
            Mathf.SmoothDampAngle(
                transform.eulerAngles.y,
                targetAngle, 
                ref turnSmoothVelocity, 
                _turnSmoothTime
                );
        transform.rotation = Quaternion.Euler(0.0f, angle, 0.0f);

        _moveDirection = Quaternion.Euler(0.0f, targetAngle, 0.0f) * Vector3.forward;
    }

    private void ApplyMovement()
    {
        _characterController.Move(_moveDirection.normalized * _moveSpeed * Time.deltaTime);
    }

    public void Move(InputAction.CallbackContext context)
    {
        _input = context.ReadValue<Vector2>();
        _direction = new Vector3(_input.x, 0.0f, _input.y);
    }

I believe it has something to do with not reseting the _moveDirection variable every frame. But I've been trying to fix this for the past few days and for some reason I can't really figure it out.
Any help is appreciated! :)

hexed pecan
coarse gull
knotty sun
#

2 things.

  1. _input.sqrMagnitude == 0 is a float. you should never test floats for equality
  2. _moveDirection is a Quaternion. You should never alter idividual components of a Quaternion
hexed pecan
#

Isn't it a Vector3 not a Quaternion?

knotty sun
hexed pecan
coarse gull
#

Alright. Let me try

hexed pecan
#

Or your _input.y instead of _direction.magnitude, whatever you like

coarse gull
#

I appreciate the help but I think it is more messy right now.

#

I'm considering remaking the whole code. It's already been a few days of trying new things and asking for help online sadok

#

But thank you very much for your time!

hexed pecan
#

I don't see how changing a couple of words is messy

#

You can always use Vector3.forward * _direction.magnitude instead of new Vector3(0, 0, _direction.magnitude); if that helps keep it less "messy"

#

But you do you πŸ˜„

coarse gull
#

Messy in terms of gameplay. I've changed a few things and it is a little bit better now

#

But it still keeps on moving forever if I release all keys

hexed pecan
coarse gull
#

and gravity is only being applied when no key is pressed.

hexed pecan
coarse gull
#

Hmm, tried it and still the same.

cobalt wave
#

@acoustic dagger

#

so you want to make a camera follower

#

by using tags?

hexed pecan
leaden solstice
hexed pecan
coarse gull
hexed pecan
#

It even says it in the comment πŸ˜„

leaden solstice
#

Literally

#

Lol

coarse gull
#

How can I fix it?

hexed pecan
#

You probably want the latter option

#

If you don't want your rotation to update when not moving

coarse gull
#

It is now looking very good.

#

Gravity is not being applied tho.

hexed pecan
hexed pecan
#

Do you see why it matters? ApplyRotation is setting moveDirection's Y value to zero

acoustic dagger
coarse gull
hexed pecan
#

So you want the gravity to happen after that

coarse gull
#

Can't thank you enough

cobalt wave
coarse gull
#

Thank you very much for the help @hexed pecan

acoustic dagger
cobalt wave
#

well

#

find a game object with the tag you want (not in the update method, since finding is costly)
and make the camera follow it

#
void Update()
    {
        Vector3 relativeOffsetPos = target.TransformPoint(positionOffset);
        transform.position = Vector3.SmoothDamp(transform.position, relativeOffsetPos, ref velocity, smoothAmount, followSpeed);
    }

this is how I do it

#

this always looks relative to the player

acoustic dagger
#

o shi you fast

#

tysm

cobalt wave
#

welcome and good luck

coarse gull
#

BTW, currently everything about my movement is tied to the _moveSpeed because of this line

_characterController.Move(_moveDirection * _moveSpeed * Time.deltaTime);

How could I untie the falling movement/speed from the _moveSpeed variable?

leaden solstice
solemn raven
#

hi,
does anyone knows how to draw 1/4 of a circle ?

vec3 rgb(float r, float g, float b) {
    return vec3(r / 255.0, g / 255.0, b / 255.0);
}

/**
 * Draw a circle at vec2 `pos` with radius `rad` and
 * color `color`.
 */
vec4 colorAndBlur(vec2 uv, vec2 pos, float rad, vec3 color) {
    float d = length(pos - uv) - rad; // blur edge
    float t = clamp(d, 0.0, 1.0); // color
    return vec4(color, 1.0 - t); // color
}

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {

    vec2 uv = fragCoord.xy;
    vec2 center = iResolution.xy * 0.5; // position
    float radius = 0.25 * iResolution.y;

    // Background layer
    vec4 layer1 = vec4(rgb(210.0, 222.0, 228.0), 1.0);
    
    // Circle
    vec3 red = rgb(225.0, 95.0, 60.0);
    vec4 layer2 = colorAndBlur(uv, center, radius, red);
    
    // Blend the two
    fragColor = mix(layer1, layer2, layer2.a);

}
#

like top right corner of a circle, top left , bottom right , bottom left ?

hexed pecan
#

By calculating a distance from the pixel to some corner

coarse gull
solemn raven
#

it will always be the same = radius

heady iris
#

although, it is nice to see an example of Move being called twice -- I had a superstition about not doing that for a while

#

(something about messing up isGrounded -- I guess that could be an issue if you did gravity first)

hexed pecan
#

I lived under the impression that the doc is wrong

#

But I dont really use CC

heady iris
#

i should really just test it

#

it's not that much

#

unfortunately I am currently playing Stardew Valley

hexed pecan
#

Like I've just heard that youre supposed to combine your Move calls into one per frame, not sure what was the reason, maybe the isGrounded stuff you mentioned

leaden solstice
hexed pecan
#

Or collision callbacks (OnControllerColliderHit)

static matrix
#

this is a good idea

elder kiln
#

Anyone ever seen this error?
An error occurred during the replication: A remote server encryption cannot be configured in Plastic Cloud

#

I'm working in a sync view that syncs from an older version of a repo (that got accidentally deleted) to a newer one that replaced it. I've reset client.conf and cryptedservers.conf, and I can see and download from both repositories

#

but when I try to do Pull Visible or Push Visible to sync the changes between the two, I get the error about remote server encryption cannot be configured

glossy basin
#

Hello there , may I ask, what is Graphtools? I was looking for some way to mess with UI toolikt and make graphs into it, but I found this package which doesnt seem to be what I was looking for, but confuses me about its functionality, what is it supposed to do?

leaden ice
#

for example Shader Graph, VFX Graph, and Visual Scripting are graph-based editors

glossy basin
#

can It work with jobs ?

#

or its just for visualiation

leaden ice
#

It's an editor thing

#

it's for making editor tools

glossy basin
#

Ohhh, okay, its clear now

#

thanks

golden vessel
#

Hey, are my inputs frame dependent if I use events with the new input system? If I make a jump with a height proportional to the time the button was pressed, and I press it 2.1 frames, will it behave as if it was pressed 3 frames?

quaint escarp
#

I've been building an "unique id system"; using Type and ulong; I've been very careful so that I can release an unused id and reuse it to another entity, when there are spawns and despawns; I was using Dictionary<Type,List<ulong>> but I recently moved to Dictionary<Type,HashSet<ulong>>; this prevents the id to be repeated, but I'm using this just to be sure I won't use a released id twice; I tried very hard to keep track of my code so I actually don't release the id twice or more, using other variables to check, so that I didn't even need to use HashSet in the first place; I just changed it to HashSet as a "safety measure" because I'm really afraid of doing a mistake in the code and cause a bug to release the id twice; does anyone have a method or has knowledge on how we can be more trustful about our own code? I've been reading and rereading my code and it's working as expected but I'm really scared of causing a corrupt game file with repeated ids. I don't know what to do to be sure it's going to keep working as expected.

leaden solstice
quaint escarp
# leaden solstice What are you using this 'unique id system' for?

I'm using it for identifying an object as "spawned" so it can be saved in the game files with its own properties; whenever I despawn an object and it no longer exists in the game, I release its id for a next object of same Type to use it and pool the GameObject without properties for a new spawn

leaden ice
#

Note that "frames" are not generally a meaningful measure of time because framerate will always vary.

golden vessel
leaden ice
#

Yes of course

#

everything in Unity is based on frames

golden vessel
#

They're checked every frame

leaden ice
#

yes

golden vessel
#

Right ok, thanks

#

Can be weird in low fps

leaden ice
#

potentially sure

#

lots of weird things can happen at low framerates

#

best to avoid them

golden vessel
#

Thanks for the info πŸ™‚

modest sierra
#

Anyone ever implement the IPointerClickHandler interface for tmppro dropdown items? Currently there is only an onvaluechanged interface but I want to get events sent to me when an item is clicked even if it was selected before and the value did not change

leaden solstice
void basalt
#

Said this before and I'll say it again. Avoid GUID for tagging objects with an ID.

leaden solstice
#

Context?

void basalt
#

There's just no reason. Use uint and just reuse IDs.

#

I can name many things wrong with GUIDs if thats what you're asking

heady iris
#

can you name them, then?

leaden solstice
#

He is worried about 'releasing same id multiple times' for some reason, then simplest answer : use GUID and don't worry about releasing anything πŸ˜„

heady iris
#

i can certainly gripe about the lack of serialization support

cosmic rain
void basalt
#

It's just an awful habit

#

you also aren't going to be mapping the ID to an array index with GUIDs

heady iris
void basalt
#

small integers compress fine

heady iris
#

this is nonsense

leaden solstice
#

Awful habit that is widely used and battle tested? Sure πŸ˜„

void basalt
#

widely used by who?

heady iris
#

you do not know what you are talking about

#

at all

leaden solstice
#

Literally everyone include Unity itself

void basalt
cosmic rain
#

I kinda agree with Burt. Depending on the use case it might be different, but I think in most cases using GUID is an overkill. It's like using nuclear missile launch protocols to open your fridge.

heady iris
void basalt
#

That's pretty much what I'm talking about, chief

heady iris
#

then you should say so.

void basalt
#

or you could stop embarrasing yourself

heady iris
#

particularly small, sequential integers

void basalt
#

either way works

#

I'm done with this conversation

heady iris
#

anyway, back to productive conversation...

heady iris
#

it also prevents stale IDs from suddenly becoming "valid" again

#

which is a nice simplification

#

however, if you would like to hold all of your entities in an array, then it is very natural to use array indices as IDs

#

and this, of course, makes it very efficient to store and retrieve your entities

leaden solstice
#

I mean there won't be anything that'd make your code perfectly trustable, even if you use Rust πŸ˜„
Best practice, add enough assertion and make test cases

quaint escarp
# leaden solstice You could use `GUID` or similar stuff and forget about releasing it πŸ˜„

I'm using ulong because of GUID can be unpredictable sometimes; I'm using a list of ids of unlong and reusing them whenever they are not used anymore; the code is working fine, I'm just afraid of making mistakes in the code from now on. The problem with GUIDs might be using the game save between computers. Wouldn't there sometime a possibility of a repeated GUID?

"Best practice, add enough assertion and make test cases"
I think that's the point I'm looking for; but even doing that there's no way to create a "perfect", no mistakes code, is there? I'm testing now, and rereading but I'm so afraid of causing a "collision" in the ids that I froze in place in front of my computer and I can't add more stuff; if a collision happens; I believe, in the way I coded, the worst that can happen is that the old real id owner object will vanish so the new id one will spawn, or the save file will be left with some strings of the old object, but with no usage in the next load.

void basalt
#

but there's nothing checking for it.

#

that will be the least of your problems when using GUID.

#

Also extremely unlikely that you'll exceed the uint range. Ulong is unnecessary for this.

lament bloom
#

I have this sword slash vfx, but I'm not sure what would be the best way to make sure it always spawns in at the correct angle based on the attack animation that's playing

void basalt
#

@quaint escarpOverall, you should make sort of a mini "library" for managing IDs, so that you don't have to worry about shit breaking randomly.

heady iris
#

If these are sequential values that you re-use after freeing them, then you can absolutely get away with a uint

leaden ice
heady iris
#

maybe even an unsigned short, but that's starting to wander into the realm of "maybe I will have a few tens of thousands of objects"

leaden solstice
lament bloom
heady iris
#

i'm not clear on which one C# defaults to

leaden ice
#

or just make it a child of some other animated Transform

#

e.g. the player's hand or the sword or whatever

heady iris
#

v1 is date-time + MAC address

quaint escarp
# void basalt <@767842869003288636>Overall, you should make sort of a mini "library" for manag...
     internal readonly Dictionary<Type,ulong>ids=new Dictionary<Type,ulong>();
     internal readonly Dictionary<Type,HashSet<ulong>>releasedIds=new Dictionary<Type,HashSet<ulong>>();
     internal readonly Dictionary<Type,LinkedList<SimObject>>pool=new Dictionary<Type,LinkedList<SimObject>>();
     internal readonly Dictionary<(Type simObjectType,ulong idNumber),SimObject>spawned                 =new Dictionary<(Type,ulong),SimObject>();
     internal readonly Dictionary<(Type simObjectType,ulong idNumber),SimObject>active                  =new Dictionary<(Type,ulong),SimObject>();
     internal readonly Dictionary<(Type simObjectType,ulong idNumber),SimObject>despawning              =new Dictionary<(Type,ulong),SimObject>();
     internal readonly Dictionary<(Type simObjectType,ulong idNumber),SimObject>despawningAndReleasingId=new Dictionary<(Type,ulong),SimObject>();```
void basalt
#

uhhhh

#

that uh

#

doesnt look good

#

you're making things way too complicated

heady iris
#

that's a lot

void basalt
#

When you're finding a blank ID, just iterate through your data buffer until you find an empty slot

#

reuse IDs and you'll be fine

leaden ice
quaint escarp
#

this is my variables definition, my code is spread in three files, the sim object manager, the sim object spawner and the persistent sim object data saving

heady iris
void basalt
#

When you're doing stuff like this, you can always inherit from monobehaviour and create your own entity class

heady iris
#

it should behave pretty nicely on average

void basalt
#

with an attached ID

#

and just instantiate those rather than default monos

#

much easier to keep track of things

void basalt
#

"despawning" and "despawning and releasing ID"

heady iris
#

i find it very weird to have that latter state

#

even the former, really

void basalt
#

In case you're confused, arthur, Unity is single threaded

#

your code gets executed one line at a time

#

stuff isn't happening randomly in the background

leaden solstice
#

Newer unity has ObjectPool<T> as well if you feel like it

heady iris
#

oh, that's handy

vast pumice
#

Hey im making a game similar to chess i have a vector2 list of movements that piece can move

How can I find the positions behind that enemy?

void basalt
#

@vast pumicetransform.right * distance

vast pumice
#

but its only in this example he can be anywhere in yellow positions

#

and i want to only delete spesific line behinde him not all the right positions

void basalt
vast pumice
void basalt
#

I mean, this is gonna get sort of complicated

vast pumice
void basalt
#

you're going to need to get familiar with dot products

vast pumice
#

like this

void basalt
#

you might not be going about this the right way

#

Tell me exactly the game mechanic you're trying to do

#

just diagonal movement?

vast pumice
#

okey one second i will prepare a photo and send to clear myself

leaden solstice
#

Are you working on a board game? Then I'd want to stick with integer calculations

vast pumice
leaden solstice
#

Use Vector2Int

vast pumice
#

yes its board game

quaint escarp
#

If I could share my screen I could explain better, but I'll try to do it through text:
my game code is here, anyway, if it helps: https://github.com/Arthur-Kenichi-Condino/AbSolitude

  • the game is open world with editable terrain (marching cubes), and biomes can be created with LibNoise for Unity library
  • object despawning is because objects can be off screen and then saved to the files in that state, and they disappear
  • object deswpawning with id release is for when trees are for example broken and they no longer exist; but a new tree can be placed so the id can be used again
  • active is an object that has the function ManualUpdate() called
  • spawned is an object that may not be active anymore but is marked to be pooled (it still exists in the game)
  • the trees in the picture are 7 meters tall
  • the weapons floating are the inventory system that I am implementing. (the bug is fixed already, no new weapons are left floating after new saves)
void basalt
#

Just prevent your entity from moving backwards

vast pumice
#

how should i do this

void basalt
#

Is this like chess or?

vast pumice
#

ye very similar to chess

#

but with diffrent pieces

void basalt
#

So why are you putting board game slots in a list?

#

Valid move positions?

quaint escarp
# quaint escarp If I could share my screen I could explain better, but I'll try to do it through...

So this is what was bugging me:

  • the inventory system also has an unique id system: an inventory is attached to a sim object (like a tree or the character), has its id and is saved to the files
  • an object added to the inventory has its slot id inside the inventory
  • inventories also have the reusable id system:
     internal readonly Dictionary<Type,HashSet<ulong>>releasedIds=new Dictionary<Type,HashSet<ulong>>();
     internal readonly Dictionary<Type,LinkedList<SimInventory>>pool=new Dictionary<Type,LinkedList<SimInventory>>();
     internal readonly Dictionary<(Type simInventoryType,ulong idNumber),SimInventory>assigned                 =new Dictionary<(Type,ulong),SimInventory>();
     internal readonly Dictionary<(Type simInventoryType,ulong idNumber),SimInventory>active                   =new Dictionary<(Type,ulong),SimInventory>();
     internal readonly Dictionary<(Type simInventoryType,ulong idNumber),SimInventory>unassigningAndReleasingId=new Dictionary<(Type,ulong),SimInventory>();```
- unassigning and releasing id is an inventory that is being released because its owner was removed from the game (like a despawned tree that may have its fruits removed)
- active is an inventory that is fully functional
- assigned is an inventory that may not be active but is going to be added to the pool
- when there's an inventory release, all sim objects inside of it also are despawned
vast pumice
void basalt
#

@quaint escarpThis definitely isn't how I would do it

vast pumice
#

if its avaible its green

void basalt
#

@vast pumiceI've never played chess in my life, so I can't help you much more, but you should simply move pieces based on their characteristics

#

you'll end up with different class types for each chess piece

#

@quaint escarpYou should never need to "release" an ID.

#

if that makes sense

heady iris
# vast pumice

rather than deleting options from a list, it seems more reasonable to add valid moves to a list

#

if a piece is allowed to move diagonally once, followed by a forwards rook move, then you can just walk those two possible paths

#

and halt once you run into an obstacle

void basalt
#

@quaint escarpYour inventory should be as simple as possible. It should simply just be an array/list

#

then you can index into it

quaint escarp
#

I'm working this way because it's a game like RagnarΓΆk Online where a lot of monsters spawn and die, through the map, repeatedly, and they have their inventory data, and lose it when they die

void basalt
#

That's not a problem

#

You need a proper entity system first

#

you need a function that can call like "myInstantiate" and it automatically instantiates a new entity for your game

#

automatically tagged with an ID

heady iris
vast pumice
void basalt
#

then have a function on it called "Delete" that automatically goes through and wipes everything

heady iris
#

(possibly including a move capturing that piece if it's a legal move)

heady iris
vast pumice
#

okey thank you very much both of you guys

tropic quartz
#

An another option for a grid based game is to have a 2D array and just use the grid to make checks.
Though I'll admit that after making a Tetris attack style game using a 2D array in the past... they can be a huge pain to get used to tbh.

heady iris
#

you just need some way to query "is this space occupied (and by whom?)"

#

a 2D array certainly makes that easy

vast pumice
#

I already have that

#

Every square in game have tile script which has IsFull bool

chess piece checking if its empty before moving but the other tiles behinde is remaining Isfull = false

#

so checking one by one then stopping is what i will try i think

heady iris
void basalt
#

dont worry about it

heady iris
#

i'll get some sleep now; that'll fix it :p

quaint escarp
# void basalt then have a function on it called "Delete" that automatically goes through and w...

thank you; I'm doing a process that follows this idea; the variables are a little confusing maybe because they keep the objects' references for easy access in the functions, so for example, the "instantiate" you mention, in my game, it saves the variables in ids and active and spawned, but when I "delete", they are placed in despawning because they'll be saved and them removed from the other variables and added to the pool. I reuse objects so I don't need to Destroy and Instantiate all the time.

void basalt
#

Your IDs can be mapped 1:1 to their reference in a simple array

#

no need for dictionaries

#

avoid dictionaries if there's a better way to lookup in a list/array

quaint escarp
void basalt
#

alright I guess thats fine

#

for example, before my game gets built, it goes through each type and assigns a custom "asset ID" to it

#

so that other computers understand what type of object they need to spawn in, based on a small integer

#

there's many ways to accomplish this

quaint escarp
#

thank you for all the help.

Maybe I overcomplicated but I can't change all of it now, because it's how the saving and loading system also works (in background); maybe when I have more time to polish the game, but now I need to add the other features.

The main point of not having a way to predict and avoid all bugs even if adding lots of asserts all they way and doing many play tests is what I wanted to understand: I think it's pointless to stay still in front of the computer reading and rereading for so long; there's always the risk to create new bugs when adding new features, like the floating weapons when I added the inventory system.

I'm using GitHub to check changes and sometimes "go back in time", but even with that sometimes I can't delete other stuff I already added; I was looking for the best practices to keep the code clean and organized, because it's too much from my lifetime (approximately 10 years of learning C# and Unity and coding this project) to restart from zero now.

When I was younger, I had a lot of GitHub repositories of this same project, I don't want that to happen again.

void basalt
#

"like the floating weapons when I added the inventory system. "

#

This is what the entity system is for

#

creating/cleaning up everything so you don't have to

#

You definitely want this solid before you start working on gameplay.

quaint escarp
#

I'm not sure how to implement this ECS now, but I'll study it; I think it didn't exist yet when I started my project.

void basalt
#

each "entity" already has an integer ID attached to it.

safe ore
#

anyone here know how the new input system works ? I'm trying to understand something

safe ore
woeful spire
#

I've got a class called Agent, it handles conversations. Being able to input and output words is pretty much what it does.
In this class I have two events:

public event Action<string> OnHear = delegate { };
public event Action<string> OnSay = delegate { };

I want other scripts attached to the Agent GameObject to be able to read when these are invoked.

Another class that inherits from Agent is AIAgent, this class uses AI to create responses.

When trying to invoke the events in AIAgent however, I can't. Is there a fundamental feature with inheritance that I'm missing here?

somber nacelle
#

events can only be invoked from the type they are declared in. and yes this means inheriting classes cannot directly invoke a base class's event. You could instead use a protected method on the base class that your inheriting classes call to invoke the event

woeful spire
#

okay, will do. Thank you!

cosmic rain
woeful spire
cosmic rain
dawn belfry
#

Does anyone know how could a instantiate an object foward whichever direction an AI is looking. In 3D

glossy basin
dim latch
#

i cant find my function in "onvaluechanged" even though its public. does anyone know?

#

but it works when i remove the params

wide terrace
#

Depending on the Unity Event, it may not supply additional information as arguments to the selected method, in which case methods with arguments will be omitted

latent latch
#

Think there's a bit more to it when adding more than a single param

grave nebula
#

I'm trying to access another script to access it's functions but I keep getting this spammed in the console.

First image is error. Second image is where traceback said it would be (second line). Third image is how I get the gameScript. Fourth image is the functions I'm trying to get

latent latch
#

Well, to start off, start throwing some debugging before, inside, and after your statements which you're trying to grab a reference,

grave nebula
latent latch
#

Right, so it seems this method isn't finding any game objects with your preferred tag, and as a result it returns a null.

grave nebula
#

so this thing

#

I have playercontroller inside player and Game inside MainGame

quartz folio
#

where?

grave nebula
#

?

quartz folio
#

Are you saying MainGame is tagged with "Game"?

grave nebula
#

yes, though I just renamed it to MainGame (the script)

quartz folio
#

can you screenshot that object in the inspector?

grave nebula
#

lemme assign those things too

quartz folio
#

It is untagged

#

and I do not see the Game script

grave nebula
#

oh you wanted the playercontroller script? for some reason those objects don't appear

quartz folio
#

I want to see how this works

#

Ie. the object tagged as "Game" with the Game component on it

#

because if gameScript is null as you say, well, the thing that is assigning it must not be working

grave nebula
#

I took that off of a forum

ruby fulcrum
grave nebula
#

I wasn't sure if I had to specify they != null part in csharp so I just did

quartz folio
ruby fulcrum
#

ohh

grave nebula
#

in this case I don't think it would've mattered

quartz folio
grave nebula
#

I did understand somewhat

grave nebula
quartz folio
#

Perhaps start at step 1 and say what you're trying to do, because I don't really know what you're asking

grave nebula
#

ok

#

I have a function in my MainGame script called getLevel and updateLevel which are both exposed. I want to call these functions from my PlayerController script. That's it.

quartz folio
grave nebula
#

is there a difference between these two

quartz folio
#

private things are not visible from other scripts. So if you don't intend to ask the PlayerController for the reference to MainGame, then it should be private

grave nebula
#

no i meant the serialize field

quartz folio
#

SerializeField is required to serialize private variables

grave nebula
#

from what I'm seeing on the docs, I don't need to set the script reference. All I need to do is drag the object into the reference box in inspector and then call functions via mainGameObject.getLevel()... correct?

ruby fulcrum
#

i might be wrong but serializefield basically means whether its displayed in inspector

#

if you dont want a public variable to be displayed in inspector use [NonSerialized]

swift falcon
#

I am having a problem I tried EVERYTHING i could think of for. I spent the last 3 days stuck on this and I have zero idea what to do. Basically my game has a swap from a car controller -> an fps controller. For some reasons when I press my key F to make the swap the object spawns in like 30 billion miles away (video attached).

Here is my switch script

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

public class enableStuff : MonoBehaviour
{
    public GameObject player;
    public GameObject car;
    public GameObject sphere;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            Debug.Log(car.activeSelf);
            
            if (car.activeSelf == true)
            {
                player.transform.position = car.transform.position;
                Debug.Log("EE");
            } else {
                car.transform.position = player.transform.position;
            }

            player.SetActive(!player.activeSelf);
            car.SetActive(!car.activeSelf);
            sphere.SetActive(!sphere.activeSelf);

        }
    }
}

Anyone know what I should do?

cosmic rain
#

The error in your console is also probably not a coincidence

grave nebula
#

gameScript is still null.
I've looked up it several times and everyone says that doing it like this should've worked

prime sinew
#

All you did by adding SerializeField is expose it in the inspector. If it's still empty, you defeated the purpose

grave nebula
prime sinew
#

game does not have a Game component then

grave nebula
#

How am I supposed to drag the script to the inspector, it doesn't let me put it in the field

#

and how do I assign it to Game? I've already done that

prime sinew
grave nebula
#

what?

prime sinew
#

See reply

grave nebula
#

yes, ik, i'm saying what to that

prime sinew
#

I'm going to stop trying with you now

#

Bye

quartz folio
grave nebula
quartz folio
#

Why, you can only assign components. Scripts files are irrelevant

grave nebula
#

so that I can get the script file to not be null

quartz folio
#

Assign a component instance of it.

#

Not the script itself

grave nebula
#

The MainGame gameobject? or is this something different

quartz folio
#

Does MainGame have that script on it? Then yes

grave nebula
#

how do I get the script from MainGame

quartz folio
#

Presumably the player controller is on the player

grave nebula
#

correct

quartz folio
#

Why are you not dragging that into the slot?

grave nebula
#

I have

#

wait

#

PlayerController is a script

#

i thought you can't drag a script into a field

dim latch
#

is there any way i can take a string with multiple lines, and turn it into a list of strings? (a new element for each line in the string) (out of runtime)

quartz folio
grave nebula
#

Like this?
I opened the Player gameobject and found the Player Controller Script. I dragged that to the hierarchy MainGame and dropped which gave me this

#

Oh ic, how do I have two inspectors at once

quartz folio
#

No. I'm on my phone right now and your complete lack of understanding how this works is impossible to rectify. Perhaps someone else can help

grave nebula
#

bruh I have no idea how any of this works which is why I'm trying to understand

#

you're assuming I have any experience with this

#

I can't really click MainGame to open it's inspector while dragging something

quartz folio
blissful wave
#

heyy

#

I was trying to use the Invoke method to call a function after a delay but then it keeps saying,

"Trying to Invoke method: highlightScript.ChessBoardPlacementHandler.Instance.ClearHighlights() couldn't be called."

#
Invoke("ChessBoardPlacementHandler.Instance.ClearHighlights()", 2.0f);
#

Is there anything im missing?

dusk apex
#

Maybe show the console tab with all errors.

#

Usually you'd just provide it the name of the function as a string and some delay value.

#

If anything, you might be able to forward call a method from a different scopecs void A() => B.Instance.C();

#
Invoke(nameof(A), 5f);```
swift falcon
cosmic rain
#

Also, I'm a bit sceptical about the error not being relevant.

swift falcon
#

Fixed!

acoustic dagger
#

yhea

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.

acoustic dagger
prime sinew
acoustic dagger
prime sinew
#

is it rotating?

#

show the full inspector of CameraFollow please

#

you should be doing this in Update by the way, not FixedUpdate. You're not using physics

#

@acoustic dagger

acoustic dagger
#

sending now

#

wont let me.. it says processing

#

can you dm

prime sinew
#

no

#

is it rotating?

acoustic dagger
#

yes

prime sinew
#

what exactly isn't running?

#

please debug log to see up to where your code runs

#

does the code inside if (targetObject != null) run

acoustic dagger
#

the camera is not folowing anything

prime sinew
#

you have several movement code in there

#

please debug log to see what running and what's not

acoustic dagger
#

no error

ebon steeple
#

Hiya, I can't seem to get post-processing working for cinemachine, I've installed all the necessary post processing packages, yet it still fails to work. Please help!

#

(By all the necessary packages I mean literally just cinemachine and post processing v2)

primal wind
#

Are you using URP or HDRP? If you are, URP and HDRP have their own post processing that i think isn't compatible with Postprocessing V2. If not then i don't really know since i never used Cinemachine

lethal plank
#

how do i make multi choice like this?

ebon steeple
formal slate
#

Wondering if there is a way to like just go on and update the game every day to add daily levels to the game like chess.com or daily dadish for an android game?

formal slate
lethal plank
#

alright thank guys

hard estuary
wild pivot
#

Has anyone got any experience using a ps4 controller with unity? I've got the y axis working perfectly on the right stick, but ive tried everything online for the x axis and the best I can do is make my camera permenantly spin in a circle.

dusk apex
#

So, to summarize, don't ask "Any Java experts around?", but rather ask "How do I do [problem] with Java and [other relevant info]?"

loud flume
#

So I’m working on a dungeon generator for a game and it works on a very small scale like with one room in a 40x40 grid but if I want to add more than one room I need to make it bigger. Since some of the code loops through all the points on the array that causes an issue cause there are multiple for loops that loop through 400^2 different items. Is there a better way to do this

hard estuary
# loud flume So I’m working on a dungeon generator for a game and it works on a very small sc...

If you mean nested loops, then it's a good practice to move the heavily nested code to a new method. It would make the code more readable.
In terms of optimization, sometimes putting everything inside of a single loop can change the way code works, so often it's better to leave it as it is. Usually, you shouldn't care about micro-optimization unless you observer some severe spikes in the profiler.

tropic quartz
#

I made a small random dungeon game once. I just used a 2D array, called them x and y.
Iterated through it with nested loops.
Put them inside a function I called "SpawnDungeon()" or whatever.

I don't think generators need to be super optimized (on PC at least) since you aren't running them that often.

keen bone
#

https://pastebin.com/5249PX98 can someone tell me why it doesn't connect? its not the sender device thats the problem sense it works fine in my python script

loud flume
worthy perch
#

Hello, I have this code to click on a specific GameObject collider and show its UI to upgrade it, but when an enemy approaches its colliders this code stops working, there is some order of priority that is preventing the raycast from reaching to the collider that I want ?

heady iris
#

firing a raycast with a zero-vector for the direction seems very weird...

#

but yes, a Raycast will only hit one object

heady iris
#

indeed: filter for just a layer that has clickable stuff on it

worthy perch
#

Thanks to both of you, I'll try it, I'm new and I don't know much about raycasts, what documentation/source do you recommend to learn?

heady iris
#

the unity documentation!

#

note that if you're just trying to click on something, I'd...you know, what would I reach for?

#

in 3D, it'd be a raycast

#

but that's not really practical in 2D

#

I'd probably do a circle overlap

warm stratus
#

hey, i wan t glow, HDR that i can turn on what can i do?

heady iris
#

"glow" comes from a bloom post-processing filter

warm stratus
#

yes i have bloom

heady iris
#

then you need to have a material that produces very bright colors

warm stratus
#

ah ok i found HDR but there is no glow

heady iris
#

you should get glow if you crank the emission way way up

warm stratus
#

i have that

heady iris
#

i think that's for HDR output

#

that's for actually sending wider-ranged color data to the monitor if it supports such a thing

frozen robin
heady iris
#

i was mixing this up with a separate setting for actual HDR output

heady iris
warm stratus
heady iris
#

show me a screenshot of the color picker

#

also, this isn't really a code problem; this should be moved to #archived-urp

warm stratus
#

ok i continue in Urp

ocean river
#

hey, do you know a easy way to detect it some object is (an object) or not? if i mark the maps as static they dissapear, so i want to do it another way.
should i tag every object?
its for collision detection, which should be only checked by the player and not by every single object

#

im asking for the most efficient way

heady iris
#

i do not understand

#

"if i mark the maps as static they disappear"

ocean river
#

i dont understand too, but it should be about the light

#

lightmaps

#

they just dissapear

#

i tried exporting with that baked lights thingie but it turned the mesh invisible

#

im not using standard shaders btw

#

build target is n3ds

gloomy mortar
#

Hello. I have a question regarding design philosophy in unity. I am trying to make a 2D monster collection game with pretty much turn based combat and pretty standard jrpg mechanics.

My question is: How do you decide when to make a new scene/what to split in multiple scenes? I heard the approach to do it ala Zelda (each cave and dungeon is its own scene), or doing it just all on one scene.

What philosophy do you follow?

heady iris
#

a scene should have very narrow connections to other scenes

#

so, a dungeon makes sense as a scene

gloomy mortar
# heady iris so, a dungeon makes sense as a scene

hm ok. I thought about splitting certain GUI areas into scenes.

Like inventory, combat screen and stuff like generically repeating shops. But you would make a lot of scenes, from what I understand? Wouldnt that be a lot of duplicate code? Copying all the stuff for gameplay into each scene?

#

I pretty much plan to make this my first project in this environment and I want to do it correctly so I don't get bad practices ingrained in me πŸ˜„ thats why I ask

lean sail
#

sorry if i misunderstand what u are asking, but a new scene is not a copy of your project. Your scripts still exist under assets and can just be applied to things in a scene

west blade
#

How can I find the force to add to a rigidbody in order for it to keep its altitude?

leaden ice
#

well actually that won't preserve the altitude it will preserve vertical velocity. If you are at 0 vertical velocity it will preserve the altitude

#

If you want to preserve the altitude you'll need a PID controller basically, if you want it to be realistic

west blade
#

A PID controller?

west blade
leaden ice
#

I know it's a big open space shooty army game

#

otherwise no

west blade
#

Helicopters when at neutral collective don't lose or gain altitude unless pitch or roll exceed some value, is this something a PID can do?

west blade
#

perfect, thanks for the help

rotund burrow
#

Is there anywhere I can get basic class inheritance structure for a general game? I dont need code, just a scheme what goes better where and how it is better named.

leaden ice
heady iris
#

that's extremely vague

burnt echo
#

Hey sorry to ask this here, definitely not the correct channel, but I'm having a really annoying issue with my prefabs that I think is some kind of bug? What's the best channel to post it to for some help?

leaden ice
heady iris
#

yeah, pitch it in there if you can't work out a channel

rotund burrow
#

okay, let's say i want to damage player or enemy, which means i need to access a script where the damage function is, but player and enemy are different classes. should i implement something like a health interface then?

desert shard
#

Absolutely

pearl swallow
#

Today I learned that rigidbody messes up navmeshagent.

#

Now I know why my character was moving when it wasn't supposed to.

heady iris
#

only one thing should be in charge of moving the transform

hushed needle
#

Hello, I want to get the angle between the player and the cursor position. This is my code but it doesn't work.

heady iris
#

player is not a direction

#

you've wound up computing the angle between two vectors:

#
  • a vector from the world origin to the player's position
  • a vector from the player to the mouse
heady iris
#

perhaps you meant to find the angle from the player's forward-direction to the mouse cursor

hushed needle
hushed needle
swift falcon
#

Stretching Scale

somber nacelle
# hushed needle Isn't .forward only for 3D?

sure transform.forward is only used for 3d, however your player presumably still has a forward direction in 2d that isn't transform.forward. most likely it's transform.right or transform.up

leaden ice
hushed needle
#

I can't believe it

#
  • 1 day
heady iris
#

yeah, it's very easy to get mixed up

#

can I get a sanity-check on this saving and loading strategy? An "uplink" is basically a save point. UplinkSpec is a scriptable object containing a name and other data, plus a GUID to identify it. It's a custom (and serializable) GUID type, so that's not an issue.

I'm recording a list of save points the player has reached.

https://gdl.space/omisigumot.cs

#

It kind of feels like I should be defining how to serialize an UplinkSpec and then just serializing the entire Progression class

#

but I dunno what's "normal" here

leaden ice
#

checkpoints you've reached/unlocked?

heady iris
#

all of the uplinks you've reached

#

yeah

leaden ice
#

Seems like you'd just have a list or set of Uplink IDs for that

#

not the whole UplinkSpec

heady iris
#

the game manager has a Progression field on it, and I'll have things tell the game manager about progress

heady iris
leaden ice
#

Does that need to go in the save file?

#

Or is that data part of the game build

heady iris
#

Only the GUID is being serialized

#

Resources.LoadAll<UplinkSpec>("Uplinks").ToDictionary(x => x.Guid);

this is fetching all of the UplinkSpec assets and making a dictionary to look them up by their guid

#

so here's an example json blob

leaden ice
#

I'm not sure I'm convinced the deserialization will work.?

heady iris
#
{
    "uplinks": [
        {
            "m_Value0": 853682203,
            "m_Value1": 1180124283,
            "m_Value2": 3413183312,
            "m_Value3": 3594981305
        }
    ]
}
leaden ice
#

data.uplinks.Select(x => uplinkMap[x]).ToList();
if uplinks is List<UplinkSpec> how are you using x which is an UplinkSpec as a key in that dictionary?

heady iris
heady iris
#
[Serializable]
public struct ProgressionData
{
    public List<Guid> uplinks;
}
#

this is one issue: there's the "progression" class and the "progression data" struct

leaden ice
#

Ohhh

#

I was confusing Progression and ProgressionData

heady iris
#

yeah, that isn't clear at first glance

#

That might be why I think I have a problem πŸ˜›

leaden ice
#

yeah it's kind of onfusing

heady iris
#

It'd be nice if I could just have Progression, and not need to hand-build anything

leaden ice
#

So basically - if you want this to be clean you would fully embrace the "memento" pattern

#

I think you kind of have a mixed model here

heady iris
#

that's a new one

leaden ice
#

Progression is partially serving as a runtime data structure and partially as a storage/serialization data structure

heady iris
#

yeah

#

(to the point that it actually just updates itself when deserializing, rather than there being some static "deserialize" method that returns a new Progression)

leaden ice
#

https://en.wikipedia.org/wiki/Memento_pattern
This pattern is basically just making sure you have a clear separation between the two. You have a runtime Progression object and a ProgressionMemento object which is for serialization

#

IDK if this is the "best" approach but I think it would alleviate the confusion aspect a bit

heady iris
#

although, I think the Progression object does stick entirely to runtime data -- it's just that it has the serialize/deserialize methods stapled onto it

#

it's strictly a list of uplinks (so far)

heady iris
#

i need to think about that some more, too

#

back when i was doing extremely janky javascript-based browser stuff, I just slapped a version number on the save, and then ran it through a series of "migration" functions to get it up to the latest version if needed

#

It was a pretty convenient strategy. If version 5 of the save format added a new list of florps, I could just add an empty list to the save object to migrate from 4 to 5

#

i have no idea what yDiff is

lament bloom
#

I'm using an animation from a unity store anim pack that comes with a lot of extra stuff i don't necessarily need. I created a state in my player's animation controller and added an animation from the pack as the motion for this state, but I'm finding that upon entering it, some code in a StateMachineBehavior defined by the anim pack asset is throwing NREs. The problem is, I never attached this behavior to my animator state, and I can't find out how to make this code stop running

heady iris
#

but you're dividing 0 by 0

#

probably happens on the first frame

fair trout
#

Sorry deleted it:

#

yDiff is just a constant

#

it shouldn't change 1/2 way through a loop

#

Am I losing my mind?

heady iris
#

it isn't changing halfway through the loop

#

oh wait, where is that error coming from?

#

"time parameter is not a valid number"

eager yacht
#

Looks like two different executions

heady iris
#

i thought you were doing something in side the loop that was throwing an exception and bailing out

#

it does, indeed, feel like two different components

#

make sure you don't have a duplicate somewhere

fair trout
#

sorry I removed the line that causes the error to not confuse, let me bring it back

heady iris
#

don't do that!

fair trout
heady iris
#

show the code exactly in the configuration that caused the problem

fair trout
#

I thought it was irrelevant

heady iris
#

well, if you fully understood what was going on, you wouldn't need help with it, now would you? :p

fair trout
#

long day πŸ˜„

#

irrelevant right? the problem is the Nan

eager yacht
#

If this is a component on an object, put , this); in the log so you can click the log and see what object it originates from. If yDiff is a constant, like you say, then this is two different objects.

heady iris
#

it's throwing an exception and bailing out

#

either:

  • yDiff is somehow changing
  • you have two copies of the component, as Nomnom is saying
fair trout
#

let me Log Iteration then

heady iris
#

Debug.Log("Hello", this);

fair trout
#

hmm ok

gloomy mortar
heady iris
#

they're things with components attached

#

such as things that derive from MonoBehaviour

heady iris
gloomy mortar
#

theoretically you can just always copy and paste your player character and such

heady iris
#

you are gonna be so hyped to find out about prefabs

fair trout
gloomy mortar
heady iris
#

yes, it returns nothing

#

it logs something to the console, though..

#

do you mean that clicking on the log item doesn't take you anywhere?

fair trout
#

it doesnt

lean sail
heady iris
fair trout
gloomy mortar
eager yacht
#

Ok so do this instead so we stop flopping around like headless fish. What defines what you mean by a "constant" here. Show the actual yDiff variable @fair trout

lean sail
gloomy mortar
fair trout
eager yacht
#

understandable

fair trout
#

I thought it was a bug, because when I reset unity the bug disappeared, but really what happens is, I also reset my preset settings so it never chose that switch

#

That was embarrassing lol

lean sail
#

according to google though there is a tile palette window where u can select whatever layer u want visible

gloomy mortar
lean sail
#

It depends what u mean call it in a function, u can spawn one in yes

gloomy mortar
#

pokemon just as an example. My game is not really pokemon, just in the same genre of gameplay

lean sail
#

it wouldnt even really be a huge game object but generally yes u would want to bring the whole gui as one object rather than trying to load like player health, enemy health, player combat bar, etc etc

#

assuming you always want to load every element in that prefab

gloomy mortar
#

in terms of GUI

lean sail
lean sail
#

what i said might not relate depending on how you want your game. Like lets say before the fight you have health or some information displayed on screen. The prefab you have for initiating a fight shouldnt have that health or extra info inside it as well

#

honestly u can just ignore that last part if it doesnt relate and experiment with it in your game

gloomy mortar
#

with 2 life bars

#

in normal gameplay, life would only be displayed in the menu screen

woeful slate
#

Hi all, I'm currently working on a 2D project where I have 3 character types: Human, Goblin & Skeleton. Each character type has it's own animations, which in turn limits the actions they can take e.g. mining, attacking, walking, fishing, etc, but they all share common logic such as health, taking damage, movement, etc.

I also have 2 ways of controlling these characters, either directly by a player, or by an AI. The goal here is to allow a player to inhabit any of the characters in the world.

What would be the best way to design the code here?

#

I'm relatively new to unity so I'm still wrapping my head a bit around the script vs game object thing

gloomy mortar
woeful slate
gloomy mortar
woeful slate
#

so a interface for handleEvent function in the sublcasses that the parent can call?

gloomy mortar
# woeful slate so a interface for handleEvent function in the sublcasses that the parent can ca...

possible. But I would just make all of it in the class definition:

Base Class would contain stuff like general definitions for animation names and stuff that is identical.

Base Class also contains a rudimentary string event system that corresponds to animation names you select, but what the string calls will be assigned in the super class (human, goblin etc)

Then create a Human class, which inherits from base class.

#

with this, you can use stuff like "Attack", but have it correspond to different animations based on super class. But you can handle the super classes like Base because they inherited from Base. This enables you to use them in a generic way, but you have to cast them properly if you need animations and such.

woeful slate
#

I'm not sure I fully follow, animations are defined in an animation controller right?

#

or is that not required

gloomy mortar
woeful slate
#

one thing that might help clear this is up is I think you mean to subclass rather than super class

gloomy mortar
#

and would probably be done through a dictionary that contains animation strings (Attack, Walk etc) and would be filled in the super class

woeful slate
#

because Base is the parent (super) class and Human is the subclass

gloomy mortar
#

I meant subclass if you see it like that

woeful slate
#

how would the child subclass define the animations to be played via this string system

gloomy mortar
#

for example

gloomy mortar
# woeful slate how would the child subclass define the animations to be played via this string ...

Dictionary contains:

Attack, 1
Walk, 2
Death, 3

And is located in base class (super class)

Then you inherit from it and create the human class.

Which contains a animation call interface that takes a string.

It uses the base dictionary to translate string to key.

THen you have a dictionary in the subclass (human), which assigns

1, [Animation Handler for Attack, for human]
2, [Animation Handler for Walk, for human]
3, [Animation Handler for Death, for human]

If you do it like this, you can add any number of unique animations depending on the race.

woeful slate
#

I see

gloomy mortar
# woeful slate I see

Hm, something missing? I pretty much did this with almost no unity knowledge (am a newbie). If you know of easier ways via unity, I would love to know them πŸ˜„ as I said, newbie.

woeful slate
#

still figuring it out myself

tropic quartz
#

That's interesting, I've never used a dictionary. I feel like I learn as much as I teach stuff here. Glad I joined.

gloomy mortar
#

dictionary are really useful for association chains, especially in class structures

hollow hound
#

Not sure that this is the right place to ask, but have a question about Rider IDE.
It always moves fields around (moves events after inherited MB methods for example). It's extremely annoying and I believe someone here faced this issue. Is it possible to change?

leaden ice
hollow hound
gloomy mortar
hollow hound
somber nacelle
#

events are delegates

#

there's also the unity events which appear to be separate

hollow hound
fast belfry
#

What are the advantages in using singletons\scriptable objects compared to static classes? Right now I'm coding an Audio Manager and it works just fine with a static class. Just wondering whether there are some consequences to that I'm not aware of.

late lion
#

But if you're marking your singletons as DontDestroyOnLoad, then you have the same problem anyway.

fast belfry
heady iris
#

i'm not sure that random singletons would be super relevant when it comes to memory consumption

#

the big question here is whether the singleton is a unity object or not

#

if it's a gameobject, then it needs to exist somewhere in the scene (so you need to DDOL it to keep it around between scene changes)

#

if it's a scriptable object, then it doesn't need to exist in a scene

#

and you get the...extremely confusing behavior of SOs in editor vs. in builds

fast belfry
#

And I guess dependencies are a bit clearer with SO

#

But if I don't really care about injecting into unity lifecycle using a static class should be ok?

heady iris
#

here's the thread i was struggling to find

late lion
heady iris
#

i was only thinking of the singletons themselves

#

that's a good point

late lion
#

I'm saying this from experience; I had a crash happening between scene loads on low memory mobile devices and it was because of this.

heady iris
#

i can believe it

#

i'm curious, how would you profile that?

late lion
fast belfry
#

So basically don't store references to assets or clear them (we're already doing that actually in lots of other places) and I should be fine with a static class

heady iris
#

Oh, neat. I haven't done too much with the profiler yet

#

other than just squinting at it and going "yeah that's my game's memory usage"

hollow hound
somber nacelle
#

keep in mind there are two sections to configure the file layout for. there's the general section and the unity section

glossy basin
woeful slate
glossy basin
#

scriptable objects are a type of class which can be used as variants in a very easy way

#

and you create them via asset menu

#

they essentially look like this in code

#

this is their menu asset

#

and they look like this on inspector

hollow hound
glossy basin
#

hello there , Im curious, what is the lightest data I can use on my voxel project for creating chunks? I am currently storing blocks as an Enum on a array (i.e BlockType.Stone)

#

Also, how do I know whats the size in kb or mb of my procedurally generated chunks?

heady iris
#

for an enum, it'll depend on the size of the datatype used to store it

#

iirc they're normally ints

glossy basin
glossy basin
heady iris
#

indeed, but i'm not sure if you can change the underlying type for an enum..

#

ah, you can

#

public enum Whatever : byte

glossy basin
#

interesting

somber nacelle
#

just be aware that unity probably won't be able to serialize enums that are not int-backed

#

but if you don't plan to have more than 256 different block types then byte will be the way to go. otherwise you'll need to use a larger type like int

glossy basin
#

this will probably stay below 255

#

and how do I measure how big my procedural mesh is in size?

#

Ah yes, ofc it was going to be as easy as just defining my enum with bytes

#

I think I already know where the issue is

glossy basin
#

Im gonna need some help here

#

So apparently what causes that weird behaviour of deforming meshes so bad is the UV part of my mesh

#

I assume this is happening because the UV uses Int on its process

heady iris
#

wouldn't bad UVs just give you weird texture mapping

glossy basin
#

this is the code I use for assigning UVS

heady iris
#

perhaps it's mangling the mesh data

glossy basin
#

I essentially need to change int to byte right?

#

this is a Job

heady iris
#

where is the enum involved here?

glossy basin
#

this is before schedulling the job

heady iris
#

it shouldn't matter if it's a byte or an int; it'll get casted to an int if needed

#

and every byte value is representable as an int value

glossy basin
#

Hmmm, very weird

#

maybe the float2 causes a problem?

#

I am confused though, the code should work fine with this, weird thing is that it generates the data correctly if I decide to not use the uvs

near cave
#

are there any good alternative tutorials/videos for creating grid systems in unity that isnt code monkey? i find his videos very hard to follow

heady iris
glossy basin
heady iris
#

that's even more mysterious

#

since that means it's not that the uv process is somehow mangling the mesh

glossy basin
#

yeah, I just comment this line mesh.SetUVs(0, UVmap); and it works

glossy basin
heady iris
#

wait, the UV order?

glossy basin
#

it should only distort the UV rather than modifiying the mesh itself

frosty lark
#

Does anyone know why audio.play is so expensive?

#

This is on mobile πŸ˜„

heady iris
#

is this every time, or just one time?

#

is it a large audio file?

frosty lark
#

I literally press play

glossy basin
frosty lark
#

on my games main menu

glossy basin
#

enable deep profile on your profiler and track down what casues that much time spike

frosty lark
glossy basin
frosty lark
#

oooh

#

its loading the sound

#

then playing it

#

odd

glossy basin
#

So this means there is something wrong on your gamemanger

frosty lark
#

I wonder how you load the audios before hand

#
    public void StartGame()
    {
        m_PlayerSpeed = m_PlayerStartSpeed;
        m_Difficulty = 1;
        m_BackgroundMusic.Play();
        m_PlayerCurrentMovement = m_Player.transform.position.x;
    }
#

This is literally it

glossy basin
frosty lark
#

yes

#

wait no

#

its 0.7mb

glossy basin
#

Uh

frosty lark
#

idk if 700kb is too long for phones

glossy basin
#

it is very lightweight

#

is the startGame being called on start or awake methods?

frosty lark
#

its called on a button event click

#

my awake deals with loading of chunks etc

glossy basin
frosty lark
#

So this is when the game starts

#

Which is fine its loading all the chunks

#

games not open yet and ill make a loading screen etc

#

I press play

#

ill investigate further though πŸ˜„

glossy basin
# frosty lark I press play

Honestly I dont know whats going on there, it seems like the methods are set up propertly, maybe it is the audio file format?

frosty lark
#

hmm its mp4

#

this will be fun

glossy basin
#

@heady iris so... my problem fixed on its own lmao, I have no clue of what happened, it no longer happens

heady iris
glossy basin
#

maybe I forgot to save a change on a script

#

Idk

#

but it works LMAO

frosty lark
#

the more you know

glossy basin
tropic quartz
#

Maybe something weird happens with compression on the sound file.
Sound files have quite a few import settings.

#

Ah you found those lol

frosty lark
#

then mp3 lmao sorry @glossy basin

glossy basin
glossy basin
stone echo
#

is there a way to store config variables in c#? Me and a friend are working on a github project and we have a string that is different when i run it vs when she runs it. I was thinking of making some kind of config file where we can set the string and then put that file in a .gitignore so that we wouldnt have to keep changing the variable everytime we pulled changes

#

but im not sure how to do that, what's the best approach for this?

frosty lark
#

you can have a json file in your git repo

#

What variables do you keep changing?

#

might give us insight on what might be better

stone echo
knotty sun
glossy basin
#

why is this very specific line on mesh collider expensive? is there a way I can reduce how much time it takes? it takes around 1ms to complete (very low though, but I am an optimization maniac lmao)

frosty lark
#

wasting time trying to get tiny improvements

#

when 1ms is great

boreal compass
#

I have some textures with different discretized colors, for example the only red pixels will be (1,0,0,1) fully red, IE its easy to tell what color a pixel falls under. I want to count the number of pixels of each color in the texture and sum them in buckets, so i can tell if for example 50% of my texture is red, 20% yellow, 10% blue etc. Exact accuracy is not important, I just need generally which colors are there more of than other colors, and approximately how much more. Does anyone have suggestions on how to do this?

glossy basin
# frosty lark when 1ms is great

Yeah, I mean, not sure if this will be a problem on low end hardware, I want to test my project with some friends but since I got a monster pc build, I am not sure if the power of my end minimizes the impact

unborn flame
#

would it be easier to code a system where instead of having the player pickup items and store them in the inventory have them instead pickup items and bring them to the npc to complete a quest?

#

for example the code would be something like "if item is in hands while talking with npc then complete quest"

lean sail
#

Depends how advanced u want the inventory or the pickup to be

unborn flame
#

very simple

latent latch
#

if you dont want any inventory management then sure why not

unborn flame
#

just pickup and give

lean sail
#

Then both are gonna be the same difficulty, and its just a matter of what u want in ur game

latent latch
#

if(condition == true)

unborn flame
unborn flame
lean sail
#

just a note, u dont need to check if a condition is true. the condition is a true or false statement

lean sail
unborn flame
#

currently i do but is really diffcult to manage

#

its a mess

lean sail
#

like interact with object -> object destroyed, bool on script set to true, then npc checks if bool

#

well an inventory system then would be way harder compared to just picking up an object and having it follow u, until reaching a trigger on the npc

lean sail
#

The 2 things you are comparing though really cannot be compared. If you have an inventory system, thats gonna be for multiple items (i hope). Then you go to the npc and turn it in.
Comparing that to just picking up an item, which only allows you to pickup one or two at a time is drastically different and heavily affects your gameplay even. Whether its a positive or negative effect depends on the game

hexed pecan
#

Or at a scale thats not 1,1,1

twin fractal
#

i need some help this code wont work and i dont know why

using UnityEngine;

public class Rotation : MonoBehaviour
{
    public float speed = 5f;

    private void Update()
    {
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, speed * Time.deltaTime);
    }
}
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.

knotty sun
twin fractal
knotty sun
#

you have multiple variables in that script, speed, direction, angle, rotation. debug them

twin fractal
#

ok

glossy basin
#

maybe this is cause because this is a procedural mesh

twin fractal
hexed pecan
#

I wonder if changing the "Cooking Options" in your MeshCollider before assigning the mesh would prevent that:

knotty sun
knotty sun
#

transform.rotation is a moving target, you cannot reach a moving target

twin fractal
#

oh

twin fractal
knotty sun
#

by making a start and end point and rotating between them

twin fractal
#

ok

twin fractal
desert shard
#

if it works, leave it

knotty sun
delicate smelt
#

How would you guys do an item system.

I mean let's say I have a 20 different swords that have different stats. 20 shields, 20 armors etc.

What is the most efficient way to manage this data and use it for my game?

I thought about making a json file where there would be all the items separated by category where all the stats are written. I can then just ask my game to parse the json for the stat I want.

Is it a good idea or is there better?

vagrant blade
#

Scriptable Objects are a good usecase

glossy basin
glossy basin
delicate smelt
solemn raven
#

hi ,
is the basemesh class inherited from monobehaviour ?

#

i have a customized basmesh class and a customized monobehaviour one that are highly optimized and they are pretty small , im thinking of combining both of them into one since i usually use both of them together, and just add a bool to block that parts that im not using

solemn raven
#

BaseMeshEffect , my bad

heady iris
#

ah

#

it inherits from UIBehaviour, which inherits from MonoBehaviour

#

never heard of that intermediary..

solemn raven
#

well , that is all i need , i will combine the two and add few bool
thanks a lot πŸ™‚

#

❀️

heady iris
#

is this in an older version of unity?

solemn raven
#

2021.3.5f1

heady iris
#

i'd just never heard of the dang thing

#

weirdly hard to find in modern documentation pages

glossy basin
glossy basin
heady iris
#

why on earth is this thing in UnityEngine.UI

#

i guess it's for shaping UI elements?

#

you know what, no: i'm about to go have fun in unreal tournament with some friends. i do not want to learn more cursed knowledge tonight

#

Interface which allows for the modification of verticies in a Graphic before they are passed to the CanvasRenderer.

When a Graphic generates a list of vertices they are passed (in order) to any components on the GameObject that implement IMeshModifier. This component can modify the given Mesh.

#

yeah

solemn raven
#

hey , is it possible to make the property appear on the editor instead of the real value ?

private float _foo;
public float foo
{
   get { return _foo; }
   set { _foo = value; }
}
latent latch
#

they don't actually hold values

#

it's c# special getter/setter mini functions

#

there is a shorthand way of writing that out though

 [field: SerializeField] public float foo{ get; private set; }```
mild briar
#

does anyone know if i call an enumerator using an if statement inside of update, will it update the variable inside uncontrollably

#

System.Collections.IEnumerator PerformExplosion()
{
if(nearPlayer) {
GameObject.Find("GameState").GetComponent<GameState>().livesLost++;
Debug.Log(GameObject.Find("GameState").GetComponent<GameState>().livesLost);
}
Debug.Log(nearPlayer);
Destroy(gameObject, 0.3f);
yield return new WaitForSeconds(1.0f);

}
#

Also, hi, im new here. Just started game development recently, look forward to working with folks

solemn raven
latent latch
#

It's just a one liner, no need for the whole property field expanded

#

it's just a shorthand way to write it

solemn raven
#

yeah i know but i wanna run some logic when the value is changed , that is the whole point of using properties

glossy basin
#

is this a good size for a procedural mesh considering how many vertices it has?

latent latch
#

ah, well the inspector does not set it through the field and only the value, but what you can do is add some logic with OnValidate

solemn raven
#

hmm, well if that is the only way to do then i guess i'll do that, it would take a couple of temp variable to compare it on validate i guess to see if it has changed

latent latch
#

That's what I've concluded on in the past. There's methods of using custom inspector drawers and attributes, but that's usually more effort than I'd usually want to put in.

#

Ah, perhaps look into naughty attributes too

#

Maybe that's useful for your case, but I've not really experimented with it

solemn raven
#

@latent latch thanks ❀️ I actually went a head and solved it with another bool , it toke few minutes

shut zinc
#

Is there a better way to handle inherited classes constructors, I want to call the base constructor but not type an empty constructor every time I create a child class

latent latch
#

You do call the base constructor first though and then the derived constructor in this case

#

Unless you mean you don't want the extra empty constructor here, I'm not too sure since the compiler likes to get angry without it,

shut zinc
#

Yeah, I don't want the extra constructor is all

cosmic rain
cosmic rain
#

I mean, you don't need to explicitly define a default constructor.

leaden ice
#

Not a default but if they want the parameter they need to define it

cosmic rain
#

Ah indeed. Somehow totally missed the parameter.

glossy basin
#

Hello there, I was thinking about optimizing my game further, so , it runs at 390+ fps when idle, and goes down to a minimum of 170 fps when generating chunks while moving (this is barely noticeable, it goes down very slowly), so I am generating my chunks using job system and every time I create a chunk, my code creates multiple native arrays necesary for data, it looks like this

#

way too many arrays

#

so I was thinking of having this array on a separate scripts to instead of creating them every time, just resuse them from that script, clearing them before using them

#

So, is there a way to clear a native array without disposing it? does my thinking make any sense?

solemn raven
#

hi ,
is it possible to dynamically set the range value ?
for example :

[range(0,70)]
public float speed;

can i somehow when a bool foo is true , raise the max range to 100?

cosmic rain
#

No. At least not without some reflection trickery

#

Or a custom inspector/property drawer.

latent latch
#

Could try this method, but you'll have two different values in your script which you need to check which you are reading from

solemn raven
solemn raven
cosmic rain
#

You'll need to define the range logic in it instead of the attribute though

solemn raven
#

i had to make 2 classes PropertyAttribute and PropertyDrawer

#

and included both of them with the same class i was working in car

#

it looks a bit geeky and complex which i dont mind as long as it doesnt impact the performance

keen solstice
#

Still having issues with my code

#

#1100748368537464862 over here, can't figure out how to call a gameobject

Should I make it slot.gameobject?

thin aurora
#

You serialize a field to show in the inspector, not a property

#

[field: SerializeField] informs Unity to serialize the backing field of a property. If you write it as public float foo { get; private set; }, there will be a backing field created by the compiler, which is serialized. You never use the property.

thin aurora
#

I assume you want to trigger property code? There is no build in way to trigger a property instead, but you could add custom editor stuff to simulate it.

#

For example, I made this property drawer that triggers a method when the value was changed in the inspector:

[CustomPropertyDrawer(typeof(ObserveChangeAttribute))]
public class ObserveChangeAttributePropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginChangeCheck();
        EditorGUI.PropertyField(position, property, new GUIContent(property.displayName));
        if (!EditorGUI.EndChangeCheck() || !Application.isPlaying)
        {
            return;
        }

        var observeChangeAttribute = (base.attribute as ObserveChangeAttribute)!;
        var method = property
            .serializedObject
            .targetObject
            .GetType()
            .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(x =>
                x.Name.ToLower() == observeChangeAttribute.Method.ToLower() &&
                x.GetParameters().Count() == 0)
                .FirstOrDefault();

        if (method == null)
        {
            var fieldName = base.fieldInfo.Name;
            throw new Exception($"Method \"{observeChangeAttribute.Method}\" not found whilst invoking change on \"{fieldName}\".");
        }

        method.Invoke(property.serializedObject.targetObject, null);
    }
}

Which could be called like this:

[SerializeField] [ObserveChange(nameof(OnFontSizeSettingsChange))] private int _fontSize = 12;
#

Note it's not very performant, but it's a way to validate settings, if you want.

#

End of my wall of text πŸ˜„

lean otter
#

I am installing an ads plugin in my Unity project. It's my first time installing plugins and I got different errors when I try to export the build for Android.

These are the plugins I installed.
First I installed Google Mobile Ads Unity Plugin v7.4.1 in my Unity project.
Then installed the following ads network through the Admob mediation
AppLovin Version 6.6.0
Meta Version 3.9.1
Unity Ads Version 3.6.1

Check the attached file for the errors I am facing.

Which plugin is creating the issue?

dusk apex
#

This is the coding channel, for general non code discussions consider using the #πŸ’»β”ƒunity-talk .
Also, not many folks will download your text file to see it's contents (discord doesn't embed text files for all platforms). Consider posting the logs on a paste site and linking it where needed (!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.

thin aurora
coarse cape
#

thanks sorry

drowsy river
#

How to set a border for a object cuz rn I am just checking if the x pos and z pos are both not bigger then a border var and then a empty if statement idk what I should put in that if statement to not let them go further

dusk apex
drowsy river
#

ty for the help

hard estuary
granite nimbus
#

how does bool check with Camera work? I've noticed it in a tutorial, they do

Camera myCamera
if (!myCamera) // ...

I can't find any info on that. Does it return false when myCamera is null or what?

dusk apex
granite nimbus
#

so it's just null check, alright

dusk apex
#

Well, there's not much to say.. it returns false when your variable is null.

granite nimbus
#

does it work on any class? I never knew it

#

any nullable type*

dusk apex
#

Depends if that class has got an overloaded operator for bool check

hard estuary
granite nimbus
thin aurora
#

Not often used in c# since we only have null

#

So I just prefer to do if (myCamera == null) to differentiate with booleans, not that that ever matters.

granite nimbus
#

I guess I'll just stick to explicit == null for readability

thin aurora
#

Fun fact: Javascript ended up with the === to check if something is truly the value compared with, which == might not catch, because of this falsy stuff

granite nimbus
dusk apex
#

Pretty sure nearly all components inherit Mono so it would be the same.

thin aurora
dusk apex
granite nimbus
dusk apex
#

In the Editor, it could be not null but still throw an NRE - fake Unity null (I believe only if it's exposed to the editor, not sure)

granite nimbus
#

does it have to do with the weird overload of == operator, where basically the variable isn't null, but object doesn't exist

dusk apex
dusk apex
#

My interpretation of it - don't take it word for word

hard estuary
late bloom
#

Hiya, stumbled onto a bit of an annoying issues. I use GUIDs on Scriptable Objects to find references for persistence. Like this:

        private void OnValidate()
        {
            if(string.IsNullOrEmpty(_guid))
                _guid = Guid.NewGuid().ToString();
            UnityEditor.EditorUtility.SetDirty(this);
        }

Problem occurs when I duplicate a scriptable object, then I have a duplicate GUID. How would I go around this issue?

dusk apex
#

It should be an Unique Identifier?

#

Meaning they would not be the same? (relative to assets)

heady iris
#

yes, the problem is that the serialized field is preserved when duplicating the asset

rain minnow
#

can't you create a new SO instead of duplicating it, or clear the string so it creates a new one?

late bloom
heady iris
#

alternative strategy: just use the asset's GUID! I'm trialing that for a save system for a solo project right now

#

i am a little concerned that I could shoot myself in the foot if I remove content and then decide to put it back later

#

but I guess I can just pluck the old assets (and corresponding metadata) from VCS

late bloom
#

Oh, why didnt I think of using that

heady iris
#

a compromise would be to just use the asset's GUID as the default

#

and then let the user override it

#

...but then you'd be back in the same boat: duplication would give a duplicate GUID

late bloom
#

I'm not super concerned about deletion here

#

Because it's an avatar for the player

heady iris
#

I was going to go grab an example

late bloom
#

And we have a fallback if none is found

heady iris
#

but i left my laptop in the car, oops

late bloom
#

So worst case, someone loses their selected avatar, but nothing game breaking

heady iris
#

i'm considering this for my save system, anywhere I need to serialize a reference to a SO