#archived-code-general

1 messages · Page 456 of 1

mighty ivy
#

It uses "WorldToScreenPoint" to draw the arrow in the screen where the object is, then with fancy math and adjusting for canvas scale it clamps it in the edges of the UI

#

It works flawless for close waypoints. The problem arises when waypoints are very far: as you can read from the code I forced the Y of the waypoints to be the Y of the player (the camera is above the player, it's a top-down with a 45° angle camera), to be sure that the object is never under the camera. But with far away objects, the object can still be behind the camera, even with the same Y... Has anyone got any solutions?

#

When the object is very far the arrow points on the other side

#

For reference, that's a screen of the game with the tracking arrow in the upper left edge (a bit hard to notice when it's not moving). It's tracking a very far away waypoint: the arrow should be in the bottom right edge.

marsh mesa
#

My camera renders UI even when it's disabled in the culling mask

#

Im trying to do a camera stack, but the main camera doesnt stop rendering the ui

#

it happens when the stack is empty too

#

All of my ui is on the correct layer, and is on a canvas

#

here's how it looks when it set to render nothing

#

what could be the problem

mossy snow
#

canvas is using overlay render mode or screen space with no camera assigned

#

set it screen space and assign a camera

marsh mesa
#

Ooo thanks!

urban summit
#

I just opened a project and it already says that I have a problem with VS code, would this effect my code in unity?

quartz folio
#

Impossible to say. It's not a good idea to have non-normal characters in directories anyway.

#

You may find later down the track issues with building

#

I'm not sure what else you have but . should be reserved for file names, not in directories

urban summit
quartz folio
#

; is not a normal character to have in paths either

urban summit
quartz folio
#

You should just be able to close Unity and rename the directory

urban summit
#

alr, thx man much appreciate your help!

lean sail
#

I had similar issues at work where someone on another OS had a space at end, or a 260+ character path and I just couldn't interact with it

urban summit
quartz folio
#

I'm happy to use A-Z a-z _ - and spaces (as separators only)
I actually think I was mistaken and . would also be fine, it's probably complaining about the semicolon but best to be safe and avoid it too

lean sail
#

Yea spaces are allowed, just not as the last character I believe. The only reason I avoid spaces is habits from the past

shadow cradle
#

is it possible to change vfx graph props that cant be exposed from code? like shape volume/surface

mighty sequoia
#

!publisher

tawny elkBOT
#

✒️ If you're an Asset Store publisher looking to apply for that role, please DM <@&502880774467354641> with an image of your publisher dashboard to be added. It may take a week or so to get to your request, please be patient.

earnest gazelle
#

Can we access the parent of a cloned gameobject from nested children without referencing it in the inspector explicitly?

night harness
#

Yes (via transform.parent) but it's almost always avoidable and might be a sign that your approaching something in a non-preferable way

earnest gazelle
#

I said nested child, maybe it is immediate child or not

steady bobcat
#

you can traverse the "tree" in both directions

earnest gazelle
#

I know I can check transform.parent iteratively to find

steady bobcat
#

you can get components in children or get the transforms children

night harness
#

once the object is instansiated, there is no information unity retains for the child to figure out what parent is the prefab parent specificially

earnest gazelle
#

but it is not ideal, so the answer we are not able to access the root of cloned gameobject directly in the code

night harness
#

we are

#

but the root isn't always going to be the prefab object

#

eg. if you instansiate something as a child of another object

#

it's on you to determine which parent you care about

earnest gazelle
#

Example:
Cloned gameobject (root)
child
child
child
child
child

night harness
#

sure but

#
Parent you spawned the prefab under
  Cloned gameobject (root)
     child
         child
    child
        child
          child
#

if this happens what do you want to find

earnest gazelle
# night harness we are

No, I just spawn a gameobject in the scene and I wanna access the root of gameobject from codes assigned to some children, easy

steady bobcat
#

i pointed out this is possible, what is the confusion?

earnest gazelle
#

You said transform.parent

night harness
#

you can use transform.root but this will not work if the object is spawned under any sort of other gameobject

steady bobcat
#

transform.GetChild(), transform.parent. you can do this all from any transform

#

you can walk up/down as you desire

earnest gazelle
night harness
#

sometimes it is

earnest gazelle
#

but maybe buggy because the spawned gameobjects are in another gameobject, I mean when spawning, pass a parent to them!

steady bobcat
#

If you have a component on the "prefab root" you can locate this

night harness
#

I would strongly recomend considering doing whatever your doing in a way where the parent object is doing this work, not the children

#

this can include the parent object informing the children that it exists

#

eg. dont make the children find the parent make the parent find the children (and perhaps tell the children where it lives)

fiery steeple
#

Is it possible to construct a color from hex code ?

steady bobcat
#

yes, read the damn page 😆

fiery steeple
steady bobcat
#

its just their example

#

You can use it anywhere:

if (ColorUtility.TryParseHtmlString("#FF0000", out var newCol))
{
  //Do thing
}
else
{
    Debug.LogError("Parse failed!");
}

fiery steeple
steady bobcat
#

You could also make your own function that wraps this and returns the colour as you desire

fiery steeple
#

argh 😬

soft shard
#

Isnt there also a Parse without the "Try", which should return the color without a out? Assuming that you are certain your providing valid data to the function

steady bobcat
#

not in ColorUtility

#

Unity probably did this due to Color being a struct

soft shard
#

Ah

night harness
#
        public static Color ParseHex(string hex) => ColorUtility.TryParseHtmlString(hex, out Color col) ? col : Color.white;
#

tada

steady bobcat
#

col may already be "white" as it should be default if parsing fails

earnest gazelle
#

but the code to do some logic is on the root

night harness
#

yup

#

hence why the children shouldn't be looking for anything

#

sounds like a great job for the parent

steady bobcat
#

😆 this really isnt hard to solve

earnest gazelle
#

Currently, I assign the root to the script in the children through inspector

night harness
#

ok

thin aurora
#
public static Color ParseHexOrDefault(string hex) => ColorUtility.TryParseHtmlString(hex, out Color col) ? col : default;
public static Color ParseHex(string hex)
{
   if (ColorUtility.TryParseHtmlString(hex, out Color col))
        return col;

   // Could also be a FormatException
   throw new ArgumentException($"The given hex value '{hex}' could not be converted to a valid hex.", nameof(hex));
}
thin aurora
#

Why this doesn't already exist, idk. Unity does everything only halfway so you kind of get used to doing this.

fiery steeple
thick terrace
#

use the result of TryParse... instead

last quarry
fiery steeple
#

made it better 👍

night harness
#

though as rob and Fused have mentioned if your not interested in using the check to throw an error or log that tryparse function probably returns white if it fails anyway so you could just do

        public static Color ParseHex(string hex)
        {
            ColorUtility.TryParseHtmlString(hex, out Color color);
            return (color);
        }
#

not anything really different just mentioning for the sake of mentioning

last quarry
#

It doesn't return white

thick terrace
#

does it return white? i would assume not lol

#

most likely it returns default(Color)

last quarry
#

It returns black with 0 opacity

night harness
thin aurora
#

You can return Color.White, but this just leads to confusion as to why it's suddenly white in the future

#

Better to just use a proper check and return either defualt or throw an exception if you want better behaviour (I'd argue returning default is also bad). Just make sure the hex color is always valid

fiery steeple
misty latch
#

hey, if i have some query where do i ask

thin aurora
#

If you have a question regarding code, this is the place

misty latch
#

it's about unity version control i guess

#

not really code

thin aurora
vestal arch
short flame
#

oops didn't see this thanks

delicate ravine
#

trying to debug an issue with my game

public void HideAndUnhide()
{
    HidyHole hidyHoleScript = hidyHole.GetComponent<HidyHole>();
    BoxCollider playerCollider = gameObject.GetComponent<BoxCollider>();
    BoxCollider hidyHoleCollider = hidyHole.GetComponent<BoxCollider>();
    if (isHiding)
    {
        Vector3 outPosition = hidyHole.transform.position + hidyHole.transform.forward * pushDistance;
        outPosition.y = 0;
        transform.position = outPosition;
        isHiding = false;
        hidyHoleScript.HidingPlayer = null;
        Physics.IgnoreCollision(playerCollider, hidyHoleCollider, false);
    }
    else
    {
        Physics.IgnoreCollision(playerCollider, hidyHoleCollider, true);

        GameObject hidingPlayer = hidyHoleScript.HidingPlayer;
        if (hidingPlayer != null && hidingPlayer != gameObject)
        {
            PlayerController hidingPlayerController = hidingPlayer.GetComponent<PlayerController>();
            hidingPlayerController.HideAndUnhide();
            hidingPlayerController.StunPlayer();
        }
        hidyHoleScript.HidingPlayer = this.gameObject;
        transform.position = new Vector3(hidyHole.transform.position.x, 0, hidyHole.transform.position.z);
        isHiding = true;
    }
}

I am trying to move the player to the side of the hiding place when the player unhides, but i am getting inconsistent behavior. sometimes it moves to the side, but sometimes, it remains in the center of the hiding place. I tried multiple things but not able to figure out what I am doing wrong

vestal arch
#

lol why'd you highlight your code as python

leaden ice
delicate ravine
vestal arch
#

anyways first step here would likely be to just start debugging, adding logs and such to make sure values are as expected and the right branches are reached

#

just to figure out what's happening - you can move on to the why and how from there

delicate ravine
# leaden ice what debugging steps have you taken?

I tried printing out the positions, so after changing the transform.position, the position of the character is printed correctly, but when i print the position at the start of update, it shows it as the position of the center of the hiding place

leaden ice
#

that issue may be coming from the Rigidbody, or it may be coming from some other code you have.

delicate ravine
#

I also tried doing controller.Move, but that was not moving it at all

leaden ice
vestal arch
#

you have a charactercontroller and a rigidbody?

leaden ice
#

HUGE info you should have shared lol

#
  1. If you have a CC, the player should not have other colliders (such as a BoxCollider)
  2. If you have a CC, you cannot move the object via transform.position without first disabling the CC
delicate ravine
#

you need rigidbody for collisions right? I am not using physics so i have set it to kinematic

leaden ice
#

you don't need a Rigidbody if you are using a CharacterControler

vestal arch
prime vapor
#

oops, my bad! moving this there

naive swallow
#

Very thorough question though. Almost makes me wish I knew the answer just so I can encourage that kind of full on description in the future but I am not an animator

delicate ravine
#

not cylinder, capsule i mean

vestal arch
#

if the cc's cylinder is a dealbreaker, you could use an rb with a box collider instead

delicate ravine
#

i tried doing Vector3 move = outPosition - transform.position and then controller.Move(move) but that is not moving it at all

fiery steeple
#

Isn't it possible to create a dictionnary and add values directly like in an array using {} and "key" for the key ?

#

or something like this ["key"] ?

delicate ravine
leaden ice
#

CC is a capsule, no choice

delicate ravine
leaden ice
#

wdym "adjusted capsule"?

leaden ice
delicate ravine
leaden ice
#

so the CC is still there

delicate ravine
fiery steeple
leaden ice
delicate ravine
#

I replaced transform with controller.Move

leaden ice
leaden ice
#

the correct answer here is to disable the CC and then move the object via the Transform

delicate ravine
#

oh, I thought disabling it would be not a proper thing to do

fiery steeple
delicate ravine
#

disbaling it and then reneabling does work

leaden ice
#

obviously you would use whatever objects you actually need for your Dictionary

#

you're focusing in on the StudentName class which is not important

fiery steeple
leaden ice
#
        var students = new Dictionary<int, StudentName>()
        {
            { 111, new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } },
            { 112, new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } },
            { 113, new StudentName { FirstName="Andy", LastName="Ruth", ID=198 } }
        };```
#

They are not using = like you are

#

for you each row would be:
{"DARK_GREEN", Utilities.ParseHex("#0F9D58")} for example

#

{key, value}

#

just like the example

fiery steeple
#

= symbol is the thing that confused me

leaden ice
#

new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 } }

#

you can ignore everything inside here

#

it's irrelevant to the dictionary initializer

#

it's just value basically

#

they were just combining an object initializer with the dictionary initializer to show how you can use them in conjunction

fiery steeple
leaden ice
#

probably

karmic stone
#

Hello! Im using the Animation rigging package for ik animation during gameplay. I want to be able to change weight of the target during gameplay. In editor i assign 0 rotation / position weight, and when i tell it to, set target rotation weight / position weight to 1.
However, it just, doesnt set the weight in code. The debug.log gets called, the line before gets called, but the target rotation weight / position is still 0 when looking at the component after. How do you set the target rotation / position weight?

rightHandIK.data.target.SetPositionAndRotation(RightHandWrist.position, RightHandWrist.rotation);
        Debug.Log("OnStateEnterWateringCan called, setting target position and rotation for right hand IK.");
        rightHandIK.data.targetRotationWeight = 1f;
        rightHandIK.data.targetPositionWeight = 1f;
``` (If this is better in animation just lmk, chose this bc its code)
leaden ice
karmic stone
#

OH its a struct! thats, a dumb mistake on my part. thank you for the info.

#

answer to my question is probably this:
looks like doing rig weight changes during animation transitions is illegal. i’ve wrap code with weight changes into coroutine with animator.IsInTransion check and now all works like a charm

stone rock
#

Is there a proper way to not have these dropdowns on serialized classes without a custom editor?
I would like the settings just displayed in the feature without it being under a dropdown

#

This is that class.

    [Serializable]
    internal class SharpenSettings
    {
        [SerializeField] internal float sharpness = 0.0f;
    }

    public class Sharpen : ScriptableRendererFeature
    {
        [SerializeField] private SharpenSettings m_Settings = new SharpenSettings();

        private SharpenPass m_SharpenPass = default;
        private Shader m_Shader;
        private Material m_Material;
leaden ice
#

A PropertyDrawer is the most straightforward approach

stone rock
#

Ok, will do it with editor scripting then

swift falcon
#

I was thinking, what's the best way to handle attribute modifiers (like items giving + speed)? A list of the modifiers, that are all sumed/multiplied when getting the final value (and are removed when the item is unequiped), or just a simple variable that is modified on equip and on unequip?

leaden ice
#

Otherwise it's hard or impossible to recalculate the value when an arbitrary modifier is removed or expires

swift falcon
#

yeah that's true

#

makes sense

drifting zealot
#

Hello guys, one question about virtual properties, Imagine that I have a virtual property with its respective field, in a child class I want to override the Set method to add a small validation, but of course, to access the original field of the parent class it must be public, which will allow it to be accessed from the child class, enabling access without using the set method, allowing them to bypass the validation. Is there any way to avoid this? I was thinking about having each child class define its own field, but I'm not sure if that is the best way to solve this.

vestal arch
#

it must be public
no it doesn't
access levels aren't limited to public and private
sounds like you'd want protected here

drifting zealot
naive swallow
#

If I want to exclude a specific collider from a raycast is there any better way than storing its old layer, setting it to a layer that the raycast will ignore, then setting it back? Ideally, I'd like to have them all on different layers so I wouldn't need this switcheroo, but for Render Feature purposes I need them all to be on the same layer

soft shard
naive swallow
#

That might work. I dunno what's lighter, that or the layer switcheroos. I'll need to check

lyric veldt
#

does anyone know whats the best way to procedurally spawn objects in a maze, like if i want to spawn a cabinet that like hugs the wall whats teh best way to do that

lyric veldt
#

is procedurally generated too

#

do you want the code

rigid island
#

could probably get all surfaces that have a specific normal direction then shoot some rays and casts and figure out placement

lyric veldt
rigid island
#

procedual anything can be tricky, if the walls are prefabs you could potentially get away with placing some premade gameobject as empty points to potential spawns, then you can put them in array and pick random one when generation is done

lyric veldt
#

or I thought of a new idea

#

I'm thinking of using a hybrid system for the game, like the maze walls will be procedurally generated using my current algorithm, but instead of randomly placing objects, each floor tile will have several possible preset variations, and I will setup rules for how these floor should spawn, like when there is a deadend have a floor tile that contains chests etc

rigid island
hexed pecan
shell scarab
#

is this a thing now or is rider just bullshitting me? InitializeOnLoad should be enough no?

somber nacelle
#

that's for when you have Domain Reload disabled when entering play mode. static members do not get reset with domain reload disabled and since that is not readonly it's possible to change the object stored in it. so you'd want to reset it inside of a method called with RuntimeInitializeOnLoadMethodAttribute

shell scarab
#

would that be in project settings? I haven't touched it.

#

or preferences?

somber nacelle
#

even if you haven't touched the setting you've got analyzers that check for it.

shell scarab
#

ah

somber nacelle
#

this appears to be from the Project Auditor package's included analyzers

shell scarab
#

that would make sense as to why I haven't seen it before, i did just install it

#

except I haven't checked off 'Use Roslyn Analyzers' so maybe Rider is just using them anyway

lyric veldt
#

i want it spawned like this

lean sail
#

Im guessing AI code?

lyric veldt
#

maze generator right

#

and i want to have different object on the floor,

#

so i figured I should just randomly generated different like "presets" of the floor, and spawn it on the floor

#

one issue im having right now is I want the object to have a whole wall on the back

#

so i tried using a point to trying to figure out the closes wall

#

but if the wall spawns vertically

#

it will rotate the wrong way

#

so something like this

lean sail
# lyric veldt

you can type in one message instead of 10 different ones.
also part of this is still unclear like what you mean by "if the wall spawns vertically" or really what your end result should look like. did you write this code? Parts of it are very questionable. If all you're doing is spawning the door in this location, then rotating it, that isn't going to move them closer to the other wall which is what it seems like you want.
stuff like this is probably easiest if you step through with the debugger and see whats happening line by line so you can see where your algorithm is going wrong. Also reconsider that logic around line 35. you seem to be calculating the direction of the raycast, when you just used the direction in the raycast.

#

Or maybe it seems like obj is the floor in this case? In that case then its still a bit odd what you're doing with this orientation object. Maybe some of your values there aren't aligning to what you think it may be. I notice you also have Debug.DrawRay in there. Id suggest drawing it as green or red conditionally if it actually hit an object.

lyric veldt
lyric veldt
#

so basiclly instead of raycasting one time, i just have a list of empty object that raycast the back of the drawer or whatever, and if lets say all 3 of them hits a object with a wall tag, it sets its rotation there

#

what do you think of this possable implementation

lean sail
#

you should really learn to debug rather than just copy pasting AI, especially if you dont understand what the code is doing

lean sail
scenic wraith
#

I was surprised to find yesterday, that assigning a value to a property was 4x slower than assigning to a field - at least when using a Stopwatch to benchmark.

I had thought JIT compilers basically give properties and fields near identical IL. Can anyone explain why assigning a property could be so much slower?

sturdy holly
#

jus tnoticed I am not seeing the debug visuals for wheel colliders in 6.x

vestal arch
scenic wraith
#

I would have thought the JIT compiler would inline the property’s method body, eliminating the need for a separate function call. head scratch

vestal arch
#

i mean compiler optimization is kinda fickle isn't it

#

maybe it does in specific cases?

scenic wraith
#

You’re probably right

vestal arch
#

you'll probably get better answers in the c# server or something

#

!csharp

tawny elkBOT
mellow sigil
#

Stopwatch isn't reliable for micro-benchmarks

#

also debug and release builds are different

scenic wraith
#

Ah, in this case it’s not an auto backing field. But it is just a getter and setter to an explicit backing field.

#

Thanks for this info. Is there a better tool to use than Stopwatch for testing something like this?

quartz folio
#

Very different results with .net framework and mono though

scenic wraith
#

Looks like I need to learn more about benchmarking code

scenic wraith
#

Sadly, zero change

#

At least with my silly Stopwatch testing approach.

thin aurora
#

I imagine it's a nanosecond difference

#

Negligible at best

scenic wraith
#

Between a field and property?

thin aurora
#

Yes

#

Unless you did something wrong

#

Even calling a function takes no time at all. Especially aggressive inlining considering it gets rid of it altogether (AFAIK - not sure)

scenic wraith
#

Must be a testing methodology issue. :/ I’m literally getting more that a 4x slowdown with a property.

Testing approach:

  • just a float variable, with a property that has getters and setters to that same float.

  • first test: iterating 100,000,000 times over a line that just assigns the float.

  • second test (in a separate run): doing the same thing, but assigning the property.

Assigning the field: ~972ms
Assigning the property: ~4200ms

scenic wraith
#

Hard to figure out how JIT, cache misses, or the GC could be interfering with the results. But I hadn’t accounted for:

  • the difference between editor/debug/release build timing.
  • the difference between .Net and Mono
#

Editor - probably stupidly

cosmic rain
#

Debug, Development, release?

cosmic rain
leaden ice
still zephyr
#

oh thanks

quaint crypt
#

Hello,

I am using unity 6000 and terrain trees and infinite terrain.
I want to be able to add monobehaviors to my trees to be able to keep track of the tree's type, hp, state, make it fall, add rigidbody etc.

I know terrain tree's can't have monobehaviours, so what can I do?

My current thought is I need to have a tree manager that subscribes to OnTileGenerated, OnTileEnabled, OnTileDisabled and keep track of every tree instance based on location. I also need to switch terrain trees with prefab trees close to the player (5 meters - ish). Is this doable? WHat are better alternatives?

vapid vessel
#

yeah you can get the instances: cs var trees = terrain.terrainData.treeInstances

#

which means you likely want some sort of "tree manager" per terrain. You'd keep track of all the treeInstances in a big list, you can get the position (0-1 a percentage of the terrain size, so some calculation needed to convert to world pos). From there, you can:

  • loop through the list and use Physics.OverlapSphereNonAlloc at the tree position or similar for checking whether the player is near/chopping the tree down
  • keep track of hp for each treeInstance
  • spawn a "falling tree" prefab at the tree position when the hp is 0
quaint crypt
#

Can I efficiently remove a tree from the terrain using the API (without obvious stutters)?

vapid vessel
#

you'll need to make a new treeInstances array without the tree you want in it, which likely will have a bit of a stutter because it'll be a big array 🤔

#

you might be able to replace it with a tree that has zero scale though, which would mean replacing the one treeInstance instead of the whole array

#

which would be much faster

#

yeah it looks like you can do that - you'll want to test it though!

quaint crypt
vapid vessel
#

exactly, yeah 😁

#

you might even want to use a quadtree structure for it

quaint crypt
#

That sounds great, thanks!

#

I wonder how games like Valheim do it

last quarry
#

They don't use terrain trees. Or Unity terrain.

#

DOTS ECS would be my choice for such a large amount of interactable objects. It's not impossible with GameObjects but the engine will hate you.

quaint crypt
#

Thanks!@

last quarry
#

Valheim is also not the epitome of technology but it predates DOTS so we won't hold that against it 😏

It uses some type of voxel terrain. Trees, I think, are just GameObjects. It uses a low draw distance to get away with it all.

night harness
#

the ideal answer is probably never the one the game your thinking of uses 😛

young yacht
last quarry
#

ECS is a replacement for GameObjects / components that handles large amounts of objects better

#

So when you're talking "infinite terrain with trees you can cut down", it starts to sound like an attractive solution

cosmic rain
dense estuary
#

For my game there will be a bunch of buildings throughoit the map. The player will enter these buildings (through a prompt on the door) and collect loot, then leave. There is going to be several large (premade) buildings.

#

How could I make so many buildings in one scene, or would I load a new scene. I'm not sure how I would transfer data about the player throughout scenes. Plus, if there are a bunch of these buildings, how do I save the scenes and .make new ones when the player leaves and goes into a building of the same structure?

#

I was thinking I might be able to somehow load the buildings under the map and teleport the player in. I might be able to load buildings, then when the player searches a building and leaves I could block off the door so I don't need to save it to storage.

#

But I don't know how practical that would be. Any advice?

trim schooner
#

ECS and subscenes would be a better/ modern way to do this

dense estuary
#

ECS?

trim schooner
#

Unity's entity system

#

google -> unity entities / unity sub scenes

#

you can load a sub scene pretty much instantly -> tele port in / out

last quarry
#

It'd be perfect for open world games if only it had a functioning terrain system like the one they canceled

last quarry
#

Unity truly doesn't mind having 100,000 objects in memory

night harness
#

"large premade buildings" is a very unclear scale ye

dense estuary
#

Wrong message to reply to mb.

last quarry
#

I get it

night harness
#

i have some pretty good experience with lethals dungeon generation 😄

last quarry
#

Do you mind if there's a hiccup / loading screen?

night harness
trim schooner
dense estuary
last quarry
#

LoadLevelAdditive is probably a good bet.

night harness
#

how do I save the scenes and .make new ones when the player leaves and goes into a building of the same structure?

and they won't be procedurally generated.
little confused on what exactly you want saved here? the looting/exploration state?

dense estuary
#

Basically the positions of doors in the world is procedural, but the buildings appear more than once.

#

I'm not very good at explaining things.

#

There will be multiple instances of buildings.

#

But few types of buildings.

#

Does that make sense?

dense estuary
#

Thank you.

dense estuary
#

Thank you

dense estuary
#

But LoadLevelAdditive would make this process so much easier.

night harness
#

(For more comparable contexts, lethal uses additive loading where the ship is in a scene that never unloads and the moon is in a scene loaded and unloaded additively)

vague cosmos
#

Im working on making a fighting game right now, and im using Physics2D.OverlapBox to damage each collider after a attack is called, but once a collider is hit, the attack function is called ~20 times per second until the physics box is no longer overlapping. I'm having trouble figuring out why this is, would it be possible to get some help?

#

Please view lines 87, 1667, 1743, 1938, and 3043 for relevant code

vestal arch
#

that's a terrifying file

rigid island
#

holy shit why is this script 3k lines

last quarry
somber nacelle
#

jesus christ that attack method alone is over 1000 lines

last quarry
#

That’s not even the whole thing

vestal arch
#

half the script is commented?!

#

what the hell happened here

last quarry
night harness
#

i don't mean to pile on with the previous comments and point out something unrelated but maybe dont do this one

    private void OnDrawGizmos()
    {
        GameObject point = GameObject.Find("StandWestPoint");
    }
last quarry
#

Like I'm not gonna debug this just by looking at it 😄

#

This is... wow

rigid island
night harness
last quarry
#

It also does nothing

night harness
#

(does stuff i just removed following said stuff)

last quarry
#

Oh

vague cosmos
last quarry
#

Yeah that'd be your best bet at making sense of that.

#

Cleaning up the code would also help

vague cosmos
#

Sounds good

night harness
#

The FindWithTag at the start of update is also pretty rough

vague cosmos
#

Most of it is commented because I’m figuring out the best place to put everything by the way

vestal arch
#

there's also a lot of repeated code here

#

seems like a few dicts would help

#

or perhaps a list of your lists

tall coral
#

Hey, so I've been working on a procedural chunk generation script. Currently, it uses wave function collapse with a few randomly placed water and grass chunks to generate the land mass and water mass, then finds any grass bordering water and replaces it with beach. I'm now trying to think of strategies to spawn forest chunks, and I'm wondering what kind of generation techniques are usually used for this. I've considered choosing a random grass block, spawning forest, moving in a random direction until it finds grass, then replace that, go back to the root chunk, repeat until a random amount of trees have been spawned for that forest. This causes issues however if the total number of trees it tries to spawn is less than the total landmass it's on, it fails. So I considered creating a list of all grass chunks that don't border a beach, then randomly changing half into forest but I feel like it would look too chaotic. Am I on the right track here?

#

I should mention this was the previous version which used just one generation cycle with adjacency rules to spawn water, grass beach and forest chunks but as much as it is more dynamic, it's not very realistic / doesn't make much logical sense

last quarry
#

Hmm, bit of perlin noise as a first step maybe?

delicate ravine
#

what is the best way to check if an object is visible by the camera?

#

Renderer.isVisible can give true even if it is not in view i believe

vestal arch
#

visible period, or more specific checks like within the frustrum or has line of sight to the camera

delicate ravine
#

in sight, like if player is playing, they can see it

#

WorldToViewportPoint and the check if it is within bound?

hexed pecan
vestal arch
#

you could use that along with a raycast to if there's something in the way, i guess?

#

actually no that would just check for a specific part being visible or not

delicate ravine
#

i dont care if it is behind something, just should be within the rectangle of the camera

#

in my game it cannot be behind things anyways

vital jackal
#

When i click on a scriptable object, is there a way i can get a callback for when that scriptable object is shown in the inspector? Or even when it is hidden (ie: something else is selected)

fiery steeple
#

Hey,
Why do I have a null reference exception even tho my tiles 2D array contains something please ? 🤔

steady bobcat
#

😐

fiery steeple
somber nacelle
#

the tiles array itself may not be null, but it contains null elements because it's filled with whatever is the default for the type when initialized and the default for a reference type is, of course, null

fiery steeple
somber nacelle
#

you don't have to loop separately, just null check it right there in your loop you already have and create an instance if one does not exist already

steady bobcat
#
var thing = myArray[x, y];
if(thing != null)
{
    //Do stuff
}
fiery steeple
steady bobcat
#

If its not a monobehaviour you can also do: array[x,y]?.DoThingy();

#

but in this instance id not recommend that if this confused you

somber nacelle
#

in this specific case though that isn't useful because you can't use the null conditional operator on the left side of the assignment operator until c# 14

fiery steeple
steady bobcat
#

It does NOT WORK with monobehaviours

fiery steeple
steady bobcat
#

? is not safe to use with unity objects because of unity weirdness relating to doing == null comparisons

somber nacelle
fiery steeple
vestal arch
#

for stuff deriving UnityEntity.Object, == null and is null are different.
you usually want == null.
the ?. syntax uses is null, so it's not that it doesn't work, it just works differently and is most likely not what you want

steady bobcat
#

just dont use ? right now 😆

fiery steeple
#

It feels like the IsValid() method in unreal where it checks both if the reference is not null and not in the process of being destroyed

steady bobcat
#

Yea its similar but its too late to change things

#

stick with

var thing = myArray[x, y];
if(thing != null)
{
    //Do stuff
}
fiery steeple
steady bobcat
#

i think its too late to change. You could only really replace == null safely with an extension method that checks for null and valid state.

fiery steeple
#

they should add an IsValid() method because it makes more sense than what there's currently 😬

vestal arch
#

there is also just a bool cast/conversion

eager tundra
#

Rider nowadays recommends checking for "Unity null" with the bool conversion instead

fiery steeple
vestal arch
#

why would this run before your initialization anyways

#

that seems like something you should look into

fiery steeple
#

Yeah

#

Thank you guys 👍

eager tundra
steady bobcat
#

the double access will probably be optimised away but tis a tad lazy

somber nacelle
vestal arch
# fiery steeple Tell me more

x != null and x in conditions are equivalent - same for x == null and !x
for any x that derives UnityEngine.Object

fiery steeple
vestal arch
#

yes, i messed that up

fiery steeple
#

phew 😄

eager tundra
#

either that or use is null if I'm not checking for "Unity null"

vestal arch
#

if anything it's more implicit

#

the actually explicit checks are either private or internal, unfortunately

somber nacelle
#

ah, looks like they finally updated their suggestions there. and they suggest the implicit cast to bool because it shows intent to check the lifetime of the UnityEngine.Object rather than the possible intention of a pure null check

eager tundra
plush laurel
#

I'm working in a game with a similar mining-building mechanic to that of terraria. I have a Tile struct and a custom grid class and I'm trying to think of the best way to store different types of blocks which will have different textures, different break resistance, different things they might do on place... What would you recommend?

lean sail
plush laurel
vestal arch
#

definitely not separate classes, no

radiant flicker
#

Good afternoon everyone! I'm trying to get a character to look at specific objects in a scene. Right now I'm just trying to get the function working in general. I managed to get the normal rotation working but now I want to clamp the X and Y(?) axis to prevent the rotation from looking unnatural and I'm at a loss of how to approach this.

Here is how my code is set up. There are no references to other scripts.
https://paste.mod.gg/hvtmxbhcmesz/0

lean sail
#

if you just had 2 blocks where the functionality is the exact same, whatever the base block can do, the only difference being the texture, the only difference would be creating 2 SO assets and providing different textures.

radiant flicker
#

Overview of my steps are:

  1. Get a Transform reference to the head.
  2. Store the initial rotation values (this is for later when I want the character to rotate it's head back to it's original position once it hits it's rotation limit.)
  3. gain direct access to the head's x and y, rotation value so I can use the mathf.Clamp function limit the rotation.
  4. Put that information back into my head reference and use Slerp to have it gradually look at a target.

What currently happens is that it...kinda doesn't work. It looks towards the initial target object but vibrates and place.

lean sail
#

or sorry it mightve been "animation rigging"

radiant flicker
#

I have! Bone Rigging right? I was testing this out with a downloaded asset but...I think the OP did not correctly orient the animation skeleton from Blender to Unity so when I tried multi-aim constraints it just has a broken neck and I don't know what combination of up/forward vectors to use to get it to work properly.

#

If anyone has used it and knows what settings to put for the multi-aim I'm all ears but in the mean time I'm just using a simple 3D cube gameobject (with no rigging)

#

The end goal is to eventually have the character be able to look at anything under a specific list then after X amount of seconds it looks somewhere else. Like how Animal Crossing characters walk around in their homes.

lyric veldt
#

Does anyone know why my visual studio intellisense isnt working, I have tried everything, retarting my pc, reinstalling vs, restarting unity, reinstalling the unity package

lyric veldt
#

that fixed it thanks

somber nacelle
#

didn't you just say you reinstalled the package?

lyric veldt
#

mutiple time

somber nacelle
#

then are you sure you didn't just forget to install it again after the last time you uninstalled it? that's really the only way i can see it having been deleted if you had been explicitly installing it multiple times

lyric veldt
#

in the

#

visual studio installer

somber nacelle
#

that's the workload

lyric veldt
#

oh

lean sail
# radiant flicker I have! Bone Rigging right? I was testing this out with a downloaded asset but.....

Yea I think it was the multi aim constraint. I haven't tested around with it in some time but it should be customizable enough to make work as you want.
with your code, im not positive as to why its vibrating in place but it could be because of the headBone.rotation.eulerAngles part. When you read the rotation as euler angles, its converting it from the quaternion. The conversion could give you any set of euler angles that equal the same rotation

radiant flicker
# lean sail Yea I think it was the multi aim constraint. I haven't tested around with it in ...

Yea I think it was the multi aim constraint. I haven't tested around with it in some time but it should be customizable enough to make work as you want.

In this case the component worked fine ( I tested it out on some dummy gameobjects) the problem is the placeholder asset itself. I could techincally say "Yeah I know this works" and leave it broken for when I put the new stuff in but seeing it not work annoys me so here I am lol.

im not positive as to why its vibrating in place but it could be because of the headBone.rotation.eulerAngles part. When you read the rotation as euler angles, its converting it from the quaternion. The conversion could give you any set of euler angles that equal the same rotation

what do you suggest I replace it with? The reason I did that is because I'm trying to restrict how far the head can move left/right, up/down using mathF.Clamp

#

But everything I've searched for deals with active inputs and this character is just moving around autonomously. I feel like I'm close but I'm not familiar enough with rotations to know how to get the current rotation of an object the same way you would get the specific position. transform.rotation.x/y/z always turns up an error for me.

#

Okay I got the Slerp to work normally again.

#

But I need to test if the rotation limit is actually happening.

lean sail
#

reading euler angles here at any point will be questionable

radiant flicker
#

I'll see what AngleAxis does. I already have the code working that it looks towards a specific object. What I'm trying to do is have it not turn pass a min/max angle limitation.

rigid island
#

where is the code question ?

jagged path
#

There is no channel for animator help

rigid island
jagged path
#

oh

#

ok

tall coral
#

With a 2d chunk map, what kind of pathfinding algorithm would be used to find, for example, all grass blocks in one land mass? The idea is to figure out how many grass blocks there are per land mass so that I can make sure the forest generation doesn't try to replace more grass blocks with forest than there even are available to change

latent latch
#

Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly colored areas with a different color, and in games such as Go and Minesweeper for d...

turbid pagoda
#
Interaction.onInteract = new UnityEvent();
Interaction.onInteract.AddListener(() =>
{
    Logger.LogInfo("interacted!");
});
Interaction.onInteract.Invoke();

For some reason, this doesnt log

#

I know that Interaction.onInteract is a valid unityevent slot

steady bobcat
#

if the unity event is serialized it already has a value

#

otherwise, dont use a unity event (and use a real event instead)

lean sail
#

or that the logger itself works as you expect it to

turbid pagoda
#

Yes

#

I have put a log statement before and after and both run

turbid pagoda
steady bobcat
#
[SerializedField]
UnityEvent unityEvent;

^ this is given a value by unity, no need to = new();

#

public event Action MyCoolEvent; <- normal event

#

unity events replicate event functionality and allow serialized subscriptions but these are slow

fiery steeple
#

Hey, I have another question please :
For some reason my code colors properly the revealed tiles but not the not revealed tiles. So the code should :

  • color the revealed tiles in BEIGE and LIGHT_BEIGE in a checker pattern [WORKS] ✅
  • color the non revealed tiles in LIME and LIGHT_LIME in a checker pattern [DOES'NT WORK] ❌
naive swallow
#

See what your IDE says about it

fiery steeple
lean sail
somber nacelle
#

yeah the issue could simply be that the colors dictionary has the same color for two of the keys

naive swallow
steady bobcat
#

someone needs an enum

fiery steeple
steady bobcat
#

yea

tall coral
somber nacelle
# fiery steeple nope

can you stop posting screenshots of code? i'm sure by now you've seen how to correctly share your code dozens of times.

fiery steeple
#

but don't enums return an int value making the key work both with MyEnum.value and an int 1 ?

naive swallow
# fiery steeple

So, if it's an even cell, you want it to be beige if revealed, otherwise red.
And if it's an odd cell, you want it to be light beige if revealed, otherwise lime.

It looks like the "Red" isn't working, so either that color is wrong, or it's never both even and unrevealed. Try some logs to see

steady bobcat
somber nacelle
naive swallow
steady bobcat
#

the council has spoken

fiery steeple
#

(for unrevealed ones)

vestal arch
#

just a sidenote, you should group by isRevealed first rather than the parity

turbid pagoda
lean sail
steady bobcat
#

you can use Action to define one easily:
public event Action event1;
public event Action<int, string> eventWithArgs;

turbid pagoda
#

I cant change the code for defining the event

lean sail
#

while i also prefer to use c# events, its not like UnityEvent is impossible to use here. the performance aspect really doesnt matter

steady bobcat
#

if its not serialized there isnt a good reason to use it

#

if its on a monobehaviour/scriptable object and serialized then it has some benefit

#

I personally avoid them where possible as i dislike how hard it can be to check subscribers later

turbid pagoda
#

Interaction is a instance of the class interactable, which holds a definition for a unsteralized public UnityEvent (onInteract)

#

And I cannot change that

steady bobcat
#

then wack who designed it and stop setting it to a new instance?

turbid pagoda
#

But its not set to a instance

#

I cant add a listener to null

steady bobcat
#

its not a monobehaviour or SO ?

lean sail
steady bobcat
#

im puzzled at what this thing is

turbid pagoda
#

Its a plugin

steady bobcat
#

can you say what?

#

its confusing to me as i presume the plugin object invokes the event but why would they not even give it a value on construction?

turbid pagoda
#

They do

#

In the editor

vestal arch
steady bobcat
#

wha

turbid pagoda
#

As a persistent event

steady bobcat
#

in the inspector?

turbid pagoda
#

What

steady bobcat
#

you said "in the editor"

turbid pagoda
#

Yes

#

The unity editor

steady bobcat
#

so it is serialized 😐

lean sail
#

🤷‍♂️ if you both wanna focus on the plugin or c# event/unity event thats fine but none of this is actually solving your problem.

steady bobcat
#

im trying to figure out what they are doing wrong

turbid pagoda
#

Is it steralized?

#

I might have been mistaken

steady bobcat
#

if you can see a GUI thing for it in the editor YES

#

thus you should not do = new() as you may break functionality

turbid pagoda
#

All I know is that the events for other instances of the Interactable class are assigned in the editor

lean sail
#

whats wrong is that we aren't looking at the context surrounding the object. it literally doesnt matter if its serialized if all that code is running sequentially. Which is why im trying to get context surrounding the code

turbid pagoda
#

Its a plugin

#

Through bepinex

lean sail
#

ah so a mod?

turbid pagoda
#

Yes

lean sail
#

we dont help with modding

steady bobcat
#

i want my time back

turbid pagoda
#

But its still a unity problem though

naive swallow
long bison
#

are you like modding a game or have modded unity?

turbid pagoda
#

Cmon nobody responds in the bepinex server this is like my last hope

turbid pagoda
long bison
#

very interesting rule...

long bison
#

so I finished coding my very small college project and when I went to build the game, I got this error for the script I've pasted to this message:
"The type or namespace name 'ShaderKeywordFilter' does not exist in the namespace 'UnityEditor'"

I searched up a solution for this and it told me to put "#if UNITY_EDITOR" at the very top of my program and "#endif" at the bottom of the "using" section at the top of the program. This didn't seem to fix anything, since I now get another error when I go to build, which is the following:
"The type or namespace name 'MonoBehaviour' could not be found (are you missing a using directive or an assembly reference?)"

Do you know how I can fix this? I am completely lost https://hastebin.com/share/ugezikejab.csharp

steady bobcat
long bison
#

oh

steady bobcat
#

and also surround your editor only code

somber nacelle
#

just remove the preprocessor directives and line 4, you don't appear to be using that namespace anywhere anyway

naive swallow
long bison
#

oops, I probably misread that solution, I'll try it now

naive swallow
long bison
#

alright, those lines automatically put themselves there when I made the script so I had no idea if I needed them or not

somber nacelle
#

that one would not have been added automatically when creating the script. you probably auto completed something and either weren't paying attention to the namespace it said it was using (and therefore it added the incorrect namespace) or later removed whatever was using that namespace

fiery steeple
#
public Color GetTileColor(int i, int j, bool isRevealed)
{
    //print($"[{i}][{j} - {isRevealed} - {(i + j) % 2 == 0}]");
    if (isRevealed) {
        if ((i + j) % 2 == 0) {
            return colors["LIGHT_BEIGE"];
        }

        return colors["BEIGE"];
    }
    else {
        if ((i + j) % 2 == 0) {
            print("Light_Lime");
            return colors["LIGHT_LIME"];
        }
        print("Lime");
        return colors["LIME"];
    }
}
somber nacelle
#

log the actual color too

naive swallow
fiery steeple
long bison
fiery steeple
somber nacelle
#

sure, or maybe add more than just a single piece of data per log

fiery steeple
somber nacelle
#

where do you think

fiery steeple
#

at the top of that method ?

#

no wait

#

I can't do that

#

so I have to put a print in each place where I return that color

#
public Color GetTileColor(int i, int j, bool isRevealed)
{
    //print($"[{i}][{j} - {isRevealed} - {(i + j) % 2 == 0}]");
    if (isRevealed) {
        if ((i + j) % 2 == 0) {
            print(colors["LIGHT_BEIGE"]);
            return colors["LIGHT_BEIGE"];
        }
        print(colors["BEIGE"]);
        return colors["BEIGE"];
    }
    else {
        if ((i + j) % 2 == 0) {
            print(colors["RED"]);
            return colors["RED"];
        }
        print(colors["LIME"]);
        return colors["LIME"];
    }
}
somber nacelle
#

so you've now confirmed that it is in fact returning a 50/50 mix of two separate colors which clearly indicates the issue is elsewhere

naive swallow
somber nacelle
#

but again, you should print more information in your logs. instead of a single cryptic piece of data you can include that data as part of a string containing more context

fiery steeple
#

I suspect this method as the culprit :

private void OnMouseDown()
{
    if (Revealed) return;

    // Make the first tile never be a mine
    if (!firstClick) {
        firstClick = true;
        if (Value == -1) {
            Value = 0;
        }
        OnFirstTileClicked?.Invoke();
    }
    
    Revealed = true;
    spriteRenderer.color = GetTileColor(Coords.x, Coords.y, Revealed);
    textComp.color = GetTextColor(Value);
    textComp.enabled = true;
}
somber nacelle
#

i'm not saying you need to print more info here now since we've already determined this is not the issue. i'm just saying you should provide more context in your logs just in general so instead of just seeing random pieces of data in your console and then needing to already know what that data is supposed to be, you can instead provide words and other context

naive swallow
fiery steeple
#

that's why I'm kinda confused 😄

naive swallow
#

If you had printed the object, the indices, the isRevealed, and the color all at once you could have saved yourself a bunch of reloads

fiery steeple
#

oh ok 😄

fiery steeple
somber nacelle
fiery steeple
#

Ok so I think that's not the culprit anymore

#

!code

tawny elkBOT
fiery steeple
tall coral
vestal arch
fiery steeple
vestal arch
#

that doesn't matter

#

i'm talking about what you have right now in StartGame

#

anyways, the issue is you never set the color when you generate the tiles

#

in GameManager:166, you just get the color, you never actually do anything with the color

somber nacelle
somber nacelle
#

so what does that tell you?

fiery steeple
#

Let's go 😄

vestal arch
#

it's saying to reset the grid before you even create it

fiery steeple
# vestal arch it's saying to reset the grid before you even create it

as I said it's there once we finished the first game, that's why I added that first condition to make sure "tiles" isn't null before executing the code below. But I think this will still create an issue as you (or someone else) explained to me above where "tiles" could be not null but the values in it are null 🤔

vestal arch
#

that literally just is not a concern right now

somber nacelle
#

there's also literally 0 reason to call ResetGrid in StartGame considering it only does something that GenerateGrid already does

vestal arch
#

you can call just ResetGrid and not GenerateGrid when you restart

#

you're trying to think ahead but you're skipping all the logical steps lmao

fiery steeple
#

I know why I made that mistake

vestal arch
#

they all still exist

fiery steeple
#

because at first I thought about destroying all the tiles in the grid and instantiating new ones when the game restarts

vestal arch
#

the entire point of not reloading the scene is to avoid having to generate new tiles, no?

vestal arch
fiery steeple
# vestal arch they all still exist

Yeah, but I'm thinking about giving the player the choice to change the grid size between games, so in that case I will need to clear the tiles and instantiate new ones to the new grid size

vestal arch
vestal arch
fiery steeple
vestal arch
#

yeah you need to slow down and actually think through these systems

fiery steeple
#

my brain can't do that 🤣

#

my brain is already thinking about creating the next Windows 🤣

fiery steeple
#

Why is there these black / dark lines around each square plz ? 🤔

vestal arch
#

what sprite are you using? the 2d elements square?

fiery steeple
vestal arch
#

does it have a border

fiery steeple
#

it looks like yeah

#

is there an already made white square in unity directly ?

vestal arch
#

if you have the 2d feature, yeah

fiery steeple
vestal arch
#

did you create your project with the 2d template?

fiery steeple
#

I don't remember 😬

vestal arch
#

if so, you'll have the 2d feature installed
you can check in the package manager

#

2D Sprite specifically comes with some sprites

fiery steeple
vestal arch
vestal arch
#

not sure what you're expecting

fiery steeple
vestal arch
#

it's part of the 2D feature

delicate ravine
#

can you change the position of gameobject with NavMeshAgent with transform.position? I have an object which goes to another object and when it is near, it should go inside the other object, I am doing agent.isStopped = true before that, but transform.position is not changing the position

rigid island
#

or there are methods to use

drifting zealot
rigid island
drifting zealot
#

Hello guys, I have a question about properties and herency, Please check the following code:

#

This is being overriden in a child class with the following code:

#

it works but something is telling me that this is a bad practice, basically if I forgot the "base" in my set method I could cause an infinite loop, what do you think?

#

is this a common practice? or am I writing poor code?

mossy snow
#

poor code imo. Your property doesn't look like it has side effects, but it does for subclasses. It would be better to make it a private field and expose a public method to change it explicitly, which would then be specialized by subclasses if needed. What does your parent class do with this property? The fact that subclasses are implementing logic when its value changes and the parent apparently does not is smelly

delicate ravine
#

i am not update the position anywhere else in the code

drifting zealot
# mossy snow poor code imo. Your property doesn't look like it has side effects, but it does ...

Basically the parent class contains the basics fields and methods that a controller/player must have(move, jump, grab something, etc), Then I have two child classes that works in a different way since the two controllers are a different, one is for VR and the other one for non-VR, the non-VR controller was written by me so is checking the field to do some action, but the VR (The one from the image) uses a few components that were not written by me, those components are checking their own variables so I need to modify their own variables using my own variable , in this way I can make my field affect those other scripts, What I try to do is not to have to modify variables from those other scripts in a different way; this way, by simply modifying a field in my code, I can change what is needed in those third-party components.I hope this is clear.

delicate ravine
mossy snow
naive swallow
# drifting zealot

Might be better as abstract instead of virtual. Then every child class would be forced to make its own backing field, so you still keep the polymorphism but don't have a chance at a stack overflow

proper pier
#

If I find myself in need of an abstract static field, which C# does not support, am I better off manually adding a static field to each child class or using a "template instance" to replicate that kind of behavior

lean sail
proper pier
#

and itd be abstract because the parent class would force each child to implement it

lean sail
proper pier
lean sail
#

Anything that handles commands should do it purely through MovementCommand

proper pier
#

yeah your right in general, but sometimes there are things you specifically would have to do manually. For example, state trees

#

which are internal to the system itself

lean sail
#

I dont know what youre specifically referring to as a state tree, but no you dont have to do it manually. That's literally the point of inheritance.

mossy snow
#

I'm with bawsi, your architecture makes no sense

lean sail
#

Either way just an abstract method returning a string already solves your issue

#

You cant have an abstract static thing

proper pier
#

got it; trying to learn tho; when you say manually do you mean like manually writing code for each derrived class instead of using the parent class

lean sail
#

plus also you'd be hiding objects if using static which just isnt a good idea

proper pier
#

Perhaps this is just bad design, but in this class I have, in the BuildStateTree() method, it would be useful to have a static reference to the state name of other movement commands instead of having to manually inject the correct string name: https://hastebin.com/share/jidexezoqu.csharp

lean sail
proper pier
#

I get why you cant technically have them but I don't neccessarily get why they imply bad design

mossy snow
lean sail
proper pier
mossy snow
#

You mean convenience? You have tightly (and in a brittle way by using magic strings) coupled states together this way

#

why use a magic string at all? You could be referencing the types directly

proper pier
#

yeah i def could i dont know what i was thinkin

#

However, I don't see the issue with tightly coupling states with their command. To elaborate a little, the BuildStateTree() method is creating a DAG that evaluates whether or not the movementCommand can be executed based on current state. Anyways I think I get your points so don't feel like you need to continue this convo unless you want to (if u have more to say and want to I'd love to hear it)

mossy snow
#

There isn't anything necessarily wrong with doing things that way (personal style), but since the states are already tightly coupled, you don't really need magic strings here.You're doing something similar for the transition key. Why isn't that an enum, for example? You actually have a comment to explain what the values mean instead of just making the values tell you what they are

proper pier
#

Thanks for the help guys

velvet fossil
#

quick question anyone knows web tools or extensions for creating UML diagrams from my code?

cold parrot
velvet fossil
#

Thanks so much, I'll check it out

young yacht
#
bool HasLineOfSight()
    {
        Vector3 origin = transform.position + Vector3.up * 1.5f;
        Vector3 direction = transform.forward;

        if (Physics.Raycast(origin, direction, out RaycastHit hit, 100f, wallMask))
        {
            return false;
        }

        return true;
    }

hey guys how would i go about checking if there's a wall between the enemy and the player then go around that wall?

true heart
#

you probably need to have the walls in a layerMask, and check if the raycast hits that laymusk then return nothing, else return true

young yacht
#

exactly what i did

#

fixed it already

#

added 4 emptyGameobjects around my player

#

enemy chooses one, goes there tries to shoot, if cant hit then choose another random one, repeat

swift falcon
young yacht
#

since the enemy can shoot with a pistol, dodge and run away

swift falcon
# young yacht i want the enemy to feel a bit smarter than just "walk straight towards player"

Well that's for the eyesight of the enemy.

And for walking behaviors, you can use NavMesh for the pathfinding, which means finding the shortest path to the destination without running into obstacles. (Unity handles that for you if you use their built-in NavMesh)
And to actually figure out the destinations your enemy should choose, there's no single way, it depends on what you want

#

A good starting point for some simple logic is by setting the destination to the player, and then offsetting it with a large Random.insideUnitSphere , this would make the enemy approach the player seemingly indirectly.

young yacht
#

i'll probably add a coroutine to my HasLineOfSight()

swift falcon
#

I might be able to help you improve it if you send the script

young yacht
#

its quite big

swift falcon
#

You can use a website

young yacht
#

which one was it again?

vapid vessel
swift falcon
#

Yeah something like that, theres a lot of them

young yacht
thin aurora
#

!code 👇

tawny elkBOT
young yacht
#

can you see it?

#

those are the two scripts

#

dont mind the shit fest xD

swift falcon
#

Goddamn, I recommend splitting it into multiple scripts because there's too much unrelated logic in there.
I don't completely know where to start to be honest with you

young yacht
#

yeaaaa

#

my workflow is to vomit code first

#

then separate it when the enemy is behaving well

swift falcon
#

Its gonna be faster to seperate it from the beginning

young yacht
#

also its easier if you actually see it in game

grizzled dune
#

Hello everyone, im currently facing an issue for my Fade in Fade out script I made, each time the player presses E a fade in fade out anim plays out and switches the player from normal to his combat varient
everytime I click E the player just stands still and my movement doesn't work and he doesn't switch to his combat variant
The error im getting:

NullReferenceException: Object reference not set to an instance of an object
PlayerInventory+<PlaySwordCutscene>d__5.MoveNext () (at Assets/Scripts/PlayerInventory.cs:28)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <bc88c87c01184d1499d92d3b79a10ce6>:0)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
PlayerInventory:PickupSword() (at Assets/Scripts/PlayerInventory.cs:15)
SwordPickup:Update() (at Assets/Scripts/SwordPickup.cs:13)

And here are the 3 scripts I used(The Sword Pickup, Player Inventory and CutsceneFade): https://paste.mod.gg/hudraoorcybu/0, https://paste.mod.gg/kramgwerzivm/0, https://paste.mod.gg/gagdusapzhou/0

vestal arch
#

line 28 is playerWithoutSword.GetComponent<PlayerCombat>().inputEnabled = false;
there's 2 things that could be null there, playerWithoutSword and playerWithoutSword.GetComponent<PlayerCombat>().
if playerWithoutSword were null, it'd error on line 27, so it's the latter

grizzled dune
vestal arch
#

do they need to be separated though?

#

could just have them be the same object that switches modes and sprites and such

grizzled dune
fiery steeple
#

Hey,
For my Minesweeper game, I need to figure out all the adjacent "0" tiles and the adjacent "0" to those tiles, etc...
How can I do it ? I'm thinking about the floodfill algorithm, but is it the right approach or is there a better way please ? 🙂

vestal arch
#

sure, that one works

fiery steeple
vestal arch
#

there's no "best"

#

this one works fine

rigid island
#

i think the original used floodfill

fiery steeple
naive swallow
fiery steeple
#

/ is that the conventional way

naive swallow
#

what could be made better

naive swallow
#

you have a problem, you have an algorithm that solves that problem. End of consideration.

fiery steeple
#

I have this tendency of overcomplexificating things, that's why I always ask 😄

vestal arch
#

this question is part of that tendency

fiery steeple
#

yes

vestal arch
#

floodfill is pretty basic, it's just depth-first search except you aren't searching for anything

naive swallow
#

Okay, so, here's the situation: I have a whole bunch of royalty free vehicle meshes from a bunch of different sources, so there's a whole bunch of different ways they're constructed. Some of them have every individual submesh as a separate GameObject, some of them are a single GameObject with a dozen materials.

What I need to do is to recolor certain materials with a "Team" color. Currently, I have a script on the parent of the meshes that has a list of Renderers to recolor to the team colors, and it goes to each renderer and loops through its materials, changing the _BaseColor of the material to tint it to the team.

The problem with that is the ones where it's a single renderer with multiple materials. Some of these materials need to be tinted, but some don't. Imagine a vehicle where the chassis, hood, and windows are all sub-meshes on the same renderer with their own materials. I want to tint the chassis and hood, but not the windows.

I'm expecting to put a script on all of these renderer objects to determine which materials to tint, but what would be the best way to do that? If I have another component and drag in materials, they're going to be different instances than the ones the mesh uses when it's spawned in, so I can't just loop through those and change the color. Should I just make a list of "Excluded materials" and loop through the renderers materials, and skip the ones that share a name? That feels kinda... code-smelly. I hate using the name of something for a functional purpose.

night harness
#

I've gone through the exact same bullshit before and it def is code smelly. I ended up having a water tower turn blue cuz of it's name 😛

#

Depending on what you need and dont need to mess with, any chance you could identify the type of material and/or shader properties?

eg. you could figure out what "glass" is

naive swallow
late lion
# naive swallow Okay, so, here's the situation: I have a whole bunch of royalty free vehicle mes...

I can think of two options:

  1. Make it index based. Each material corresponds to a specific submesh, which has a specific index.
  2. Store a property on the materials you want to change. Such as a _UsesTeamColor integer property which is set to 1. It will be ignored by the shader since it has no corresponding property, but it will still be saved on the material and can be fetched with Material.HasInteger or Material.GetInteger.

As long as the original material has it, it will get duplicated to instantiated copies. To add the property to the material, you either have to do it from editor script, Material.SetInteger, or use the Debug inspector mode to edit the property list directly.

naive swallow
#

I... never even considered that as an option...

late lion
#

Yes, it's just a serialized key-value pair list.

naive swallow
#

That's so simple

#

I just never thought of it

late lion
#

There's also Material.SetOverrideTag and Material.GetTag, but I haven't used it for custom tags and that's not really its purpose, but it might work.

delicate ravine
#

unity doesnt consider parent class of a script class as the component of an object?

#

i have a parent class that implements common stuff and then 2 child classes that are used by different objects. but if i try to get the parent class using getcomponent it doesnt return it

night harness
#

classes don't have parents or children, that's something the Transform class specifically deals with. do you mean inheritance?

delicate ravine
#

nvm the issue was something else. i was talking about inheritance

naive swallow
delicate ravine
#

i figured out the issue, i was accidently using a child class in the GetComponent instead of the parent, hence it was returning null

neon mason
#

Hey

vestal arch
vestal arch
neon mason
#

Where is the Unity 6 app binary exe?

vestal arch
neon mason
#

I see it generated the exe after putting a new folder, however it didnt generate it in the existing folder where Unity generated files lay

somber nacelle
#

are you referring to your build exe? because that goes into the folder you tell it to

neon mason
#

Yes, however it did not generate it. It only worked with a clean build folder

somber nacelle
#

well this is still not a code issue so if you need further help then take it to #💻┃unity-talk and actually provide details instead of expecting people to immediately know wtf you are talking about

low spear
#

Hi, we're getting this error when starting Unity suddenly. We can't isolate it to a specific change, and it's not saying what file it is... it's just this message. Any ideas how to get more information? Has any got this recently?
Parser Failure at line 2: Expected closing '}'

final kestrel
low spear
final kestrel
#

same lol, 1 hour fighting against nothing

low spear
#

same same... what a waste of time that was 😄

leaden ice
#

I think it's probably related to the cloud outage

final kestrel
#

yeah, cause can't create more project related to cloud

night harness
tame silo
dense yoke
#

I'm seeing HitObj receiving the result from GetRaycastObject(). How exactly do I get that object from the Raycast and pass it to HitObj?

somber nacelle
#

How exactly do I get that object from the Raycast and pass it to HitObj
what do you mean by that? HitObj is the object hit by the raycast because that is what you return in the GetRaycastObject method

dusk apex
tawdry zinc
#

hey this is more so a general question rather than a coding specific one

#

but is there any way for me to change the colour theme for visual studio to github dark default?

#

I have this theme installed for visual studio code (blue one) but not visual studio, and when I search up downloads for visual studio, it only comes up with results for visual studio code

#

its not one of the default themes I looked through them all

somber nacelle
#

this is not unity related. nor is it code related.
but you can search the available extensions inside of visual studio

tawdry zinc
#

oh sorry

somber nacelle
#

if the theme exists it can be found there

dense yoke
tall coral
#

So, the concept for my 2D building system uses a grid-based system to place start and end points for walls, but then uses a spline to create a curve if the start and end point aren't in line with each other. What concept best fits this / what unity methods should I learn about in order to be able to accomplish this?

#

Here is a diagram of how it would work, green being start and end points and yellow being the center of the curve

dense crow
#

It looks like no one is using 'partial' in unity, Do u guys use it ?

somber nacelle
#

i use source generators, so yes i do create partial types.
whether people use them for defining types across multiple files is an entirely different story. it's really just a personal preference if you want to do that or not

dense crow
somber nacelle
#

use a convention that makes sense to you

cosmic rain
#

It sounds to me like these should be separate classes then. Or use the unity singleton implementation.

#

Not partial classes.

dense crow
cosmic rain
somber nacelle
#

wait does it really?

dense crow
cosmic rain
cosmic rain
#

Then put all the singleton related logic in that base class.

dense crow
tame thunder
#

Typically when handling thousands (or at least a thousand) AIs in 3d space that, while don't need complex decision making, do need to be checking for hundreds of potential targets

Is something like DOTS practically required? Or are there solutions efficient enough to stick with the OG format

#

I understand using nav mesh agents is beyond impractical but even when you have to have non agent AI determine distance and targets when they're tightly bunched up
You lose grids/partitioning and it becomes a mess where 20,000 checks are ran on a single frame

dense crow
night harness
#

Considerations on if theres any potential checks you can re-use or avoid in certain contexts would assist heavily in bringing down whats necessary there too i'd imagine

night harness
#

If I have two tri’s (two sets of 3 world space positions) is there any suggested way on checking if they intersect?

west lotus
tame thunder
tame thunder
#

Because dots is well above my knowledge lol

west lotus
# tame thunder I would be running it every 3 seconds

Every 3 frames for thousands of agents just means that every 3rd frame of your game would be heavy. What I’m suggesting is each agent having it’s own timer and update frequency based on realtime rather than frame count. That way each frame you are running ai logic for less agents

tame thunder
#

They're mostly just simple home made state machines that use local movement

west lotus
#

For example we also put our ai in a priority queue based on their engagement and proximity to the player

tame thunder
#

This would be top down

west lotus
#

I did not mean nav mesh agents

tame thunder
#

Ahh ok

west lotus
#

Any piece of software capable of “making a decision and acting on it” is an agent

#

Technically

west lotus
#

That dude can wait

tame thunder
west lotus
#

I would need more context for your game. What I shared as an example works for us because we are making an fps

#

You seem to be making an rts

#

What about the clumps is concerning you ?

tame thunder
#

Mount and blade would probably be the ideal example,

I handle it very messy at the moment but having the two "squads" that become interlocked (upwards of 40 agents each) run through each other's list of agents within the opposing squad to determine the closest unit

But that causes issues where if there are say a thousand agents, then we can have scenarios where 50,000 magnitude checks happen within seconds (obviously not ideal)

#

Because there's no restriction on a squad being say, in a single straight line and able to access every target in the scene

Or in tiny groups that don't typically need to run that many checks

#

At best I've split ranged up from melee so melee units only check the squad they're engaged with

west lotus
#

Well this sounds like some form of spatial partioning is needed

tame thunder
#

Do I just need to work on a much smaller partition?

#

I did try the partitioning originally but even with 2x2 unit grids (which created a lot of partitions) there can be a lot of units/agents on a single grid

#

I'm sure the system works but I've made a mistake with how I'm thinking it through somewhere

#

I did originally try to limit it to squads on squads but a player could just run a squad down the side of the line and the enemy naturally would just accept death lol

west lotus
#

Well at that point you can write a parallel job to do distance checks

tame thunder
#

Yea it's looking like Ill have to implement a proper job/burst system

west lotus
#

Or you could try sticking your units inside a kd tree. Thats very fast for finding X amount of closeset things to a point

#

But you will need to be smart about how and when you rebuild the tree

tame thunder
#

That would work even worse than spacial/grid partitioning if they all clumped into one big horde right?

#

But better for long range battles over larger maps?

west lotus
#

Mmno because you would use to find the closets units within a range

#

The range could be a meter

#

There is a jobified implementation inside the mega city repo somewhere in the audio or util section

tame thunder
#

But the range might need to be 1 meter or 100 meters so there would be a lot of worst-case checks I think

#

Oh ok cheers I'll have a look

dense crow
tame thunder
#

Just that each check itself has a 3 second gap before it's requed

mint zenith
#

yo

#

can someone help me with animation

#

cuz its dead

vestal arch
#

if you're not getting any answers, maybe you didn't provide enough info

trim schooner
#

They did not provide any information

mint zenith
mint zenith
vestal arch
#

how do you expect us to help if you don't give us any info to work with

mint zenith
#

just

#

read

#

what

#

saiud

trim schooner
#

!ask

tawny elkBOT
vestal arch
#

and there's so much that doesn't require animation knowledge that you left out

mint zenith
trim schooner
#

anyway.. stop spamming this channel with unrelated chat (☞゚ヮ゚)☞

vestal arch
#
  • what are you trying to do?
  • what assets are involved?
  • where did it disappear from?
    etc
#

none of this is related to animation specifically. it's just info about what situation you're in

#

go provide more detail

mint zenith
mint zenith
vestal arch
#

it kinda is

mint zenith
#

nice fkn ragebait bro

#

nice ragebait

#

keep going

vestal arch
#

your loss if you don't want help shrugsinjapanese

mint zenith
#

are u stupid or smth

#

i just said i dont know whats going on myself

#

so how do u want me to provide more detail

trim schooner
#

<@&502884371011731486>

mint zenith
#

its not my fault

#

hes lit

#

stupid

#

and cant read the words

#

displayed on his monitor

mint zenith
#

see

#

ragebait

#

what did i say bro

vestal arch
#

jeez calm down

mint zenith
#

u keep telling me to do smth icant

#

its annoying

vestal arch
#

you say you don't know how to animate, but the info i told you to provide doesn't have anything to do with animation

mint zenith
#

theres no more details bro

#

thats it

vestal arch
#

it's just what you see in the editor

trim schooner
#

but you can.. at the bare minimum you could show a video of the issue

#

show the setup, show what you have done.

mint zenith
#

ok let me take screenshots

#

then

trim schooner
#

we weren't stopping you 😄

vestal arch
vagrant blade
#

@mint zenith Enough with the spam, or you will be muted.

#

In the future, ask your questions with details, and dont' cross post.

trim schooner
#

This is a code channel, for code related questions. #📲┃ui-ux is where you would need to move your question (delete from here so no one tells you off for crossposting)

#

oh, you've already posted there..

stoic hound
#

yeah probably not code related

low spear
#

Hi, we're replacing the standard Windows cursor, with a sprite on a canvas (so we can do animated weapon aiming ones etc.). We hide the windows one with Cursor.visible = false;, but that also keeps it hidden if you move the cursor outside of the window etc. Is there a good way to detect that? Like the window losing focus etc.?

trim schooner
#

It's only hidden while Unity still has focus, make it lose focus and it will come back already

zealous vortex
#

uh why could there be a huge ass triangle in my mesh ;-;

#

it only apears when the size of the mesh reaches about 300x300

mossy snow
#

it likely has a 16 bit index buffer and exceeded 2^16-1 verts

zealous vortex
#

how would one go about avoid that but still having more vertices

mossy snow
#

set its index buffer format to 32 bits

zealous vortex
#

thanks

visual fjord
#

Hi

#

How can resolve this error

#

"Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater."

leaden ice
leaden ice
#

With your keyboard

#

the delete or backspace key

visual fjord
leaden ice
# visual fjord

looks like you're using some kind of code generating plugin'

#

and that plugin is generating those

#

Or you have some kind of setting in your VSCode that is automatically compiling the code

#

and making these Debug/net10 folders etc

#

basically this is probably a VSCode issue

#

you have it misconfigured somehow

visual fjord
leaden ice
vestal arch
#

because those obj files shouldn't exist

visual fjord
#

I get it

#

And yeah

#

I have delete the files

old trout
#

just kind of a sanity check, is there any real downside to waiting on a callback in a coroutine for a process i want to be functionally infinite? this is for a turn based prototype

leaden ice
old trout
#

any reason why?

#

(that line is actually only there since i was calling EndTurn in StartTurn to test this lol)

leaden ice
# old trout any reason why?

waiting one frame is yield return null
WaitForEndOfFrame is a special thing for waiting until a specific part of the frame used for some very niche post rendering things

#

check the docs

#

also creating those objects is unecessary GC allocation

vestal arch
#

@old trout

old trout
#

that a good image, thank you!

dawn nebula
#

Alright I'm pretty confused here. I found this script online because I want to find a nice way to serialize dictionaries.

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class SerializableDictionary<K, V> : Dictionary<K, V>, ISerializationCallbackReceiver
{
    [SerializeField]
    private List<K> m_Keys = new List<K>();

    [SerializeField]
    private List<V> m_Values = new List<V>();

    public void OnBeforeSerialize()
    {
        m_Keys.Clear();
        m_Values.Clear();
        using Enumerator enumerator = GetEnumerator();
        while (enumerator.MoveNext())
        {
            KeyValuePair<K, V> current = enumerator.Current;
            m_Keys.Add(current.Key);
            m_Values.Add(current.Value);
        }
    }

    public void OnAfterDeserialize()
    {
        Clear();
        for (int i = 0; i < m_Keys.Count; i++)
        {
            Add(m_Keys[i], m_Values[i]);
        }

        m_Keys.Clear();
        m_Values.Clear();
    }
}

I expected 2 Lists to show up in the inspector.

#

but instead I got this

#

How... is that happening?