#archived-code-general

1 messages · Page 152 of 1

pure cliff
#

doesnt seem to be a big deal atm but I gotta go back and make the two the same type at some point

#

then wont need to do that

ashen yoke
#

you can use a single buffer

pure cliff
#

?

ashen yoke
#

a list that acts as a buffer

#

you clear it, use it, repeat

pure cliff
#

oh yeah, that prolly would be much more performant

#

Ill keep that in mind if this ends up needing the performance boost

eager ingot
#

Hmm...I want to use addforce to move the player, but I ran into a bit of a problem. I want to make it so that there is a maximum amount of force a player can add using WASD input, but if you are airborne, forces like jumping, explosions, etc can make the player move even faster. I want their airborne speed to be essentially limiteless. I tried setting a maximum velocity, but I quickly realized that this would cause the airborne velocity to follow the same rules as the running/strafing velocity. How can I set a max input velocity or acceleration to my rigidbody?

mental rover
eager ingot
#

That's not a bad idea actually

#

I'll give it a shot

pale bay
#

hello, can someone help me understand what im missing in regards to saving:

I have a mobile game that saves a json file to the application.persistentDataPath and this works fine in the editor, however building and running the game onto my android, I find that I cannot find the file

The first image shows the file in my local machine when saving on my local pc

Setting up a log in the saving process, building and running the game on my phone, and viewing said log in LogCat shows the directory of the that file

2023/07/18 20:20:57.977 3978 4040 Info Unity Saving settings to: /storage/emulated/0/Android/data/com.DefaultCompany.marblegame/files/settings.json

I navigate to that file and find nothing (second image)

I know for a fact that it exists because everything I open the game, the save file is loaded and my settings are applied correctly

What might I be missing here? I want to view the file so I can debug an issue

#

I have windows file explorer set to view hidden files btw

leaden ice
#

also that directory doesn't look quite the same

pale bay
#

for example, I have a slider UI element that has its value set when that file is loading as well as saved when the app closes it. it works fine. Ill set more logs up.

from what I understand /storage/emulated/0/ is ignored

#

I could be wrong about the second part but I do not see the storage directory when navigating my phone in file explorer

leaden ice
#

also showing your code for writing the file would be good

pale bay
#

Saving

    public void SaveSettings()
    {
        SettingsSaveData.musicVolume = MusicVolume;
        SettingsSaveData.sfxVolume = SFXVolume;
        SettingsSaveData.vibrationState = VibrationState;

        string jsonData = JsonConvert.SerializeObject(SettingsSaveData);
        File.WriteAllText(_settingsFP, jsonData);

        // This is the log in the log entry that you suggested to implement
        Debug.Log($"Saving settings to: {_settingsFP}");
    }

Loading

    public void LoadSettings()
    {
        if (File.Exists(_settingsFP))
        {
            // If the save file exists then read it
            string jsonData = File.ReadAllText(_settingsFP);
            SettingsSaveData = JsonConvert.DeserializeObject<SettingsSave>(jsonData);

            Debug.Log($"Loading settings from: {_gameStateFP}");

            if (SettingsSaveData == null)
            {
                Debug.Log($"File not found, creating new object");
                SettingsSaveData = new SettingsSave();
            }

            return;
        }

        // Return a new score data object if no save file is found
        SettingsSaveData = new SettingsSave();
    }

I got this log when rebuilidng with the save log
2023/07/18 20:48:53.237 16704 16727 Info Unity Saving settings to: /storage/emulated/0/Android/data/com.DefaultCompany.marblegame/files/settings.json

Save file content:

{"musicVolume":0.0,"sfxVolume":0.389136523,"vibrationState":false}
leaden ice
#

should work

pale bay
#

my thoughts exactly

mellow copper
#

HI, teams, when tried to add an example script, I met an error [No MonoBehaviour scripts in the file], but the file name is already same as class name. What should I do to avoid this?

Here's my code and file name, editor version is 2023.1.3f1c1.
ExampleClass.cs

// Initializes the target variable.
// target is private and thus not editable in the Inspector

// The ExampleClass starts with Awake.  The GameObject class has activeSelf
// set to false.  When activeSelf is set to true the Start() and Update()
// functions will be called causing the ExampleClass to run.
// Note that ExampleClass (Script) in the Inspector is turned off.  It
// needs to be ticked to make script call Start.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    private float update;

    void Awake()
    {
        Debug.Log("Awake");
        update = 0.0f;
    }

    IEnumerator Start()
    {
        Debug.Log("Start1");
        yield return new WaitForSeconds(2.5f);
        Debug.Log("Start2");
    }

    void Update()
    {
        update += Time.deltaTime;
        if (update > 1.0f)
        {
            update = 0.0f;
            Debug.Log("Update");
        }
    }
}
pale bay
#

ill keep digging, im sure its something small

pale bay
#

reconnecting my phone and trying again worked

pulsar isle
#

How can I check in a coroutine while something is true keep looping and if it is false then execute the code underneath?

somber nacelle
#

a while loop

#

that's kind of their whole deal

pulsar isle
#

so something like this?

#

or do I have to put something inside the while loop?

somber nacelle
#

yeah, but you'll want to yield inside the loop, a yield return null if you just want to wait until the next frame to check the condition again

#

alternatively, if you don't plan to have any other code in the loop you can yield a WaitUntil

pulsar isle
somber nacelle
#

WaitUntil takes a parameterless Func that returns bool so you can just use a method that returns a bool. or keep the lamda expression, either one works

west sparrow
pulsar isle
#

I just tested my code and the coroutine works but there is a minor problem

#

The coroutine runs before the camBrain.isBlending bool is first set to true

#

So it instantly runs the code after the WaitUntil

somber nacelle
#

when are you starting the coroutine?

snow geode
#

How can I check if a button is being held down and if a button is not being held down anymore through a script where it references the buttons? I can’t just use the onclick() trigger on the button it self because I need this to work with multiple instantiated copies of the player.

pulsar isle
somber nacelle
#

is this before or after you start whatever transition/blend for the cinemachine brain?

pulsar isle
#

After

#

I incremented the priority of the camera and then started the coroutine

#

And I made the code only run once with a bool for it to not repeat endlessly

#

So right after the player presses the key there is a bool that stops the code from running again so it all only runs once

somber nacelle
#

ah, in that case the actual update of the vcams is probably happening later in the frame. you could try a 1 frame delay at the beginning of the coroutine with yield return null; to see if that gets it working

pulsar isle
#

Oh, so I could use yield return null and then yield return new WaitUntil() in the same coroutine?

somber nacelle
#

yes, you can yield as many times as you'd like in your coroutine

pulsar isle
#

Wow, thanks xd

somber nacelle
#

actually you may want a WaitForEndOfFrame instead of null, but just try it with yield return null first

pulsar isle
#

Then I guess it could also work by using first yield return new waitforseconds(delay), right?

somber nacelle
#

sure, if you want to wait for a number of seconds instead of for waiting until specific parts of the update cycle

snow geode
somber nacelle
#

if i knew the answer i would have already provided it

snow geode
#

Ok, thanks

molten sun
#

Quick question, how do you change the shadow quality of individual lights at runtime? I don't want to change the shadow quality globally, only for individual lights.

I learned about Light.shadowResolution, which seem to be exactly what I'm looking for, but the documentation doesn't have any examples of how to actually use this.

Does anyone have an idea on how to do this? Thanks (I'm using the built in render pipeline)

fathom plank
#

Thoughts on setting up a health system like this? Basically I was thinking this way avoids the need of getting the component on the target game object directly in a collision event/etc to apply damage, and instead you can just fire an event with the collider.gameObject, or w/e and if it has a health script, great, if not oh well.

#

i guess a downside is that the FireApplyDamage has to know which game object has the script attached to it to apply properly so it would be awkward to add as a nested child

cosmic rain
# fathom plank Thoughts on setting up a health system like this? Basically I was thinking this ...

Imagine you have thousands of objects with health. Each of them would get the method triggered and make a reference comparison.
Not to mention that it's plainly confusing implementation. It implies that Health is some kind of global object or concept.

Getting a damageable component on the go would be way better. Getting components on a gameObject is not that expensive, considering most of them have less than 10 components. If you have the component reference you would be able to do other stuff and make specific checks on it as well. For example, if you only want to apply damage to enemies, you could get the character component and check it's "team" or "faction" before applying damage to it.

fathom plank
#

if a script is disabled, afaik you can still get reference to it, as well as call functions on it, maybe im mistaken? This was also an attempt at basically making the script a no-op in the case its already been disabled

#

i mean i suppose i could early out, in those cases

cosmic rain
#

You can make an enabled check all the same.

fathom plank
#

fair enough

earnest gazelle
#

Please read my question carefully.

#

A developer presses play button in the editor when the scene is playing. I want to show a dialogue box with yes/no button.If No button is pressed, it should do nothing. isPlaying = true freezes the game.

#
        EditorApplication.playModeStateChanged += OnplayModeStateChanged;

 private static void OnplayModeStateChanged(PlayModeStateChange state)
    {
 if (_state == PlayModeStateChange.ExitingPlayMode && Application.isPlaying)
        {
            if(EditorUtility.DisplayDialog(DialogTitle, DialogMessage, "Yes", "No")){}
            else{}
        }
    }
}

isPlaying = true is the problem.

mossy snow
#

so you want to abort the mode change? if you're checking for exiting play mode, you're probably too late. Might be smarter to try and target the play button itself

earnest gazelle
#

Suppose a level designer in play mode is working on a scene and suddenly press play button before saving it. I want to prevent it

somber nacelle
#

why not just save the scene when the play button is pressed instead of showing a dialog?

thin aurora
gray mural
#

what's the best way to get this difference assuming that white square is gameObject and I have RaycastHit2D info about red object?

#

note: player should be translated to that red square's position

verbal cliff
#

what do you mean by the difference? the gap between?

lusty gull
#

i suggest using distance - collider.bounds

gray mural
#

where 1f is 1 unit in world space

#

and 1f - red.size is diff between 1 unit and scale (don't mention prefab's initial scale)

lusty gull
#

something like this, it should be like take the AB vector, then you can use this vector to get distance and direction from one another. Then you can take the half collider bounds and multiply for the direction, then subtract from the original vector and get the distance of that one. repeat for as many objects as you have! i don't know if it's clear

earnest gazelle
lusty gull
gray mural
#

then is works @lusty gull

#

if gameObject is in the center of unit

gray mural
# lusty gull

I see, so it's transform.position.y += A.halfBound + B.halfBounds + x

#

(I know that transform.position cannot be set like this)

winged mortar
lusty gull
#

halfbounds in my calculation is a float. If you need the direction information, you can use:
A + AB.normalized * (AB.magnitude - HalfboundsA - HalfboundsB)

gray mural
#

if it's position isn't inted (int)?

lusty gull
#

no. if you need dynamics not based on transform, i suggest looking into the Collider API

gray mural
lusty gull
#

the useful methods for you in this instance will be ClosestPoint and ClosestPointOnBounds

cold egret
#

- Given a collision2d, can i get a color of the object i just collided with at the contact points?

copper rose
#

about unity version control i have again same problem, one new project created by going to project settings -> unity project id, but unity version control using another projecct, how can i fix that? because i have changesets from one project pending in another project, a really big problem i made my self

gray mural
#
collision2D.transform.GetComponent<Renderer>.color;
cold egret
#

- It has a texture. It's a tilemap renderer, and tiles do have various colors, they're not solid. So getting the renderer's color might give an approximation, but never the actual color. I mean it's ok if there's no other way around this, but i'd like to get the exact color of the collision spot

gray mural
rain crane
#

Hello is there anyway to make a triggered 2D collider reload on everytime i press fire1 button? i tried enabling and disabling the collider but it doesnt count any collisions with an object with collider

cosmic rain
rain crane
gray mural
#

oh, collider

rain crane
#

yeah

gray mural
rain crane
#

I use OnTriggerEnter2D method

gray mural
rain crane
rain crane
gray mural
#

I have done it once before

#

I have to remember it.

rain crane
#

aight

gray mural
# rain crane aight
Physics2D.IgnoreCollision(triggerCollider, otherCollider, true);

Physics.Simulate(Time.fixedDeltaTime);

yield return null;
gray mural
#

this should work

#

we ignore collision for 1 udpate, then simulate physics and retrigger OnTriggerEnter2D this way

rain crane
#

the otherCollider is now the problem since i do not know who can it be.

short badge
rain crane
gray mural
#

you have to ignore specific layer e.g. Enemy

#

not all layers

#

also you can find collider by tag

#

or name

#

there are so many possibilities to do it

gray mural
#

also currentMovement is too small

#

but it may be enough

cosmic rain
rain crane
#

but it seems i found an easier solution

cosmic rain
short badge
rain crane
cosmic rain
rain crane
cosmic rain
#

Maybe explain what exactly you're trying to do? Detect when a sword is overlapping with the enemy or something?

short badge
gray mural
short badge
#

well i believe i fixed it* looks fine for now lol

rain crane
#

aight.
I made a box collider 2D and made it with the scale of the swords' range.
i was planning if i could re enable the collider on attack and detect the new collisions.

gray mural
#
private void OnEnable()
{
    playerInput.Movement.Move.started += onMovementInput;
    playerInput.Movement.Move.canceled += onMovementInput;
    playerInput.Movement.Move.performed += onMovementInput;
}

private void OnDisable()
{
    playerInput.Movement.Move.started -= onMovementInput;
    playerInput.Movement.Move.canceled -= onMovementInput;
    playerInput.Movement.Move.performed -= onMovementInput;
}
short badge
#

Thanks!

gray mural
#

just in start probably

#

it's just 1 script, so it doesn't make sense

#

also we write scripts from capital letter

cosmic rain
rain crane
cosmic rain
rain crane
gray mural
cosmic rain
rain crane
finite panther
#

error for me text error fix

#

me

gray mural
finite panther
#

too lazy

#

and i dont know how to use unity

#

so fix it

rain crane
cosmic rain
rain crane
lusty gull
#

guys anybody knows if it's possible to use [BurstCompile] on extention methods?

gray mural
#

How to make gameObject not be affected by Rigidbody2D at all, without making is static or kinematic (in order to trigger OnCollisionEnter2D)?

winged mortar
#

Does the thing you are colliding with have a rigidbody attached?

#

Iirc you need atlast one of the two to have a rigidbody

#

If yes, then you can just remove the rigidbody from your gameobject

winged mortar
#

Why do you need the collision?

gray mural
winged mortar
#

Then the other collision could have a rigid body right?

winged mortar
gray mural
#

it's moved by tranform.Translate

#

😭😭 it shouldn't have rigidbody, because it's behaviour will be broken then 😭😭

winged mortar
#

RigidBody.MovePosition

gray mural
winged mortar
#

Or

#

translate is just transform.position + difference iirc

gray mural
#

also when my player has rigidbody it's behaviour seems to be quite weird.

#

it doesn't seem nice

#

I just cannot move as usually

winged mortar
#

Looks like there's a collider on your playing field

#

And it's pushing it out of the field as soon as it starts

gray mural
winged mortar
#

Why are doing this weird 2d 3d mix man

gray mural
winged mortar
#

Not an expert on this but if you click 2d as a template when creating your project you shouldn't be getting stuff like this right

winged mortar
#

Also, try using a tilemap!

gray mural
#

it should

gray mural
winged mortar
#

There's probably someone else on YouTube that can explain that significantly better than I do, but lets just say that it isn't required but it can simplify everything

gray mural
#

I see

#

I think I should probably jsut use Physics.OverlapBoxAll

sonic edge
#

Hello, I have an issue in my 2D game. I implemented a ledge grab which works with 2 collisions : one to detect the ledge to grab, and another one which verify that there is no "Ledge" above (so the player will grab the ledge at it's top). When I jump it's working pretty well, however if my character is too fast (-20 y velocity is the max), the box starts bugging and will sometimes detect the ledge and sometimes not. Does someone know how to fix this ? https://streamable.com/wfhc7k

winged mortar
#

Although not ideal, you can raycast from your previous position to find these kinds of colliders

#

Or up the fixedupdate rate

#

But I am pretty sure this is just a problem with any fast moving object

winged mortar
#

You can also make your colliders larger

winged mortar
sonic edge
#

ok I asked and I will see if there is a easier way to fix it ...

gray mural
#

hello, any way to implement smth like OnCollisionEnter?

#

I don't mean functionality, I mean that my method should be "called" like it's

#
private void Foo(Vector3 smth)
{
    // and here is already all information about `smth`
}
#

it also doesn't seem to be overriden

#

ok, it's hard one, don't care about it

#

I have another question. Why do BoxCollider2Ds not collide?

winged mortar
#

Depends on your setup

gray mural
#

their z position is the same

winged mortar
#

Rigidbodys?

gray mural
winged mortar
#

That are simulated?

gray mural
gray mural
winged mortar
#

One of them needs to be a rigidbody for unity to do anything with them

#

I think you can also manually call the physics functions from the context of the collider

gray mural
#

so I move my obstacle in Update

private void Update()
{
    transform.Translate(GetDirection(direction) * speed * Time.deltaTime);
}

and I check for collision in LateUpdate in another script

private void LateUpdate()
{
    if (CheckCollision(k_obstacleTag))
        gameManager.EndGame();
}

But late update is a bit too late

#

it does execute just when colliders are on each other

#

any suggestions?

hasty haven
#

Wow, looks like I should not be using lists for this

steady moat
hasty haven
#

Yeah, I was able to do that for the vertices but I am now in a puzzle for the triangle data, since there are different submeshes

#

and I dont want to pre allocate 256 large capacity arrays for worst case

#

I do have a solution idea though

steady moat
#

Whatever you do, you gonna want to allocate contiguous memory.

#

List is just a wrapper around an array.

hasty haven
#

My plan is to make one main array with some logic around it, i already know the max case in terms of triangle indices (just integers)

#

And the type is denoted by a byte

#

So I think I may count all the types before generating and partition the main array sorta

#

each partition being the size of the worst case for triangles

#

worst case meaning all sides of the voxel are rendered

steady moat
#

Are you generating the voxel base on visibility ?

hasty haven
#

Yeah so the original data for voxels is simple byte array,
a 3x3x3 chunk would be 27 bytes.
When I am generating the mesh I check visibility of each voxel that isnt empty

#

The time is super inflated with the deep compiler open, usually its <10ms for worst case

#

which is a grid that looks like this

steady moat
#

Did you try without checking visibility ?

rancid jolt
#

I made this code for bullets to move towards the direction of player in 2D environment but they are moving upwards.

steady moat
#

Because I am not sure what is the performance upgrade you gonna gain.

hasty haven
#

Performance upgrade is massive

steady moat
#

You might be doing something wrong then

hasty haven
#

this is the worst case, every face is exposed

steady moat
#

You should not have an issue rending this.

hasty haven
#

I dont, my question is just to see how people would suggest splitting up the submesh types without allocating garbage

prime sinew
hasty haven
#

It works very well but I am just further optimizing, this is 3x3x5 chunks all of the worst case.
Uses <5% cpu at any time and <25% gpu and i have a 1050 ti

#

moving around and destroying them even

steady moat
hasty haven
steady moat
#

Also, you could use two step algorithm, one that define the amount of memory needed and the other that do the actual thing.

hasty haven
#

Ah maybe I should do that beforehand and include it with the block data

#

during generation

#

Count of each block type

rancid jolt
naive narwhal
#

Isometric Hexagon Tactics Battlemap: __Grid __vs GameObjects

My goal is to create an isometric hexagon battlemap with units moving across those hexagons on their turns. The hexagons will need to be** re-colored** / highlighted on various circumstances:

  • when unit is selected to display where they can move + when I hover mouse on those tiles;
  • when skill is selected to display where it can be used + mouse hover;
  • etc.

The question is, which should I use to generate those hexagons: GameObjects or Grid?

Grid does sound like the perfect choice, but I struggle to find viable ways to constantly change how tiles are displayed based on different rules (distance from character GameObjects, etc).
Meanwhile, if the hexagons are GameObjects I'll be able to change their Sprites based on game state changes, mouse hover events, etc

naive narwhal
leaden ice
#

And only write in one place?

steady moat
naive narwhal
# leaden ice And only write in one place?

With mouse -- probably, yeah, you're right.
With tile properties -- each time something happens, I'd need to apply those changes both on Tilemap, as well as that other array that stores all the properties.
Say, I pressed my mouse button on a specific tile and now it needs to be on fire. I'll need to change both the Tilemap (for visuals), as well as the array (to apply effect properties).
And all of that by comparing world coordinates to tilemap and vice versa.

leaden ice
naive narwhal
leaden ice
#

all that code would not be in one place

steady moat
naive narwhal
naive narwhal
steady moat
stuck plaza
#

I need a help with my project

#

Anyone can help me?

vagrant blade
#

You need to ask a proper question, first.

naive narwhal
#

@leaden ice @steady moat
Thank you both, I have more than enough to research / experiment with for now! 🙂 ❤️

gray mural
# gray mural

just understood I could ignore collision between them, then realised collider can just be trigger 🙄

#

stupid me 3 hours ago

gray mural
#

it explains everything you need in 2 words

topaz ocean
#

Im trying to make a dynamic physic material that belongs to the instance its assigned to. Would I need to make a struct or set of variables to re construct the physic material each time its modified or is there a more straightforward way of doing this?
Ive tried using a custom editor to create and modify a physic material when the instance is validated, but these changes are not ever saved.

leaden ice
#

but can't you just modify the one you're using as needed?

#

Why create a new one

unreal temple
#

So probably I'd do something like this:

class PhysicsMaterialController : MonoBehaviour {
  [SerializeField] Rigidbody _rigidbody;
  PhysicsMaterial _material;
  public void SetPhysicsSettings(float bounciness, float whatever, ...) {
    if (_material == null) {
      _material = (PhysicsMaterial) ScriptableObject.CreateInstance(typeof(PhysicsMaterial));
      _rigidbody.physicsMaterial = _material;
    }
    _material.boucninesss = bounciness;
    _material.whatever = whatever;
    // ...
  }

  void OnDestroy() {
    if (_material) Destroy(_material);
  }
}
#

that kind of thing

topaz ocean
# leaden ice Why create a new one

Well Im creating a prefab of a collection of objects with joints and colliders to represent a wheel, and I figure it could be useful to have the ability to dynamically adjust the properties at runtime. To do that though I need a material instance for every wheel. I couldnt just modify a material asset because that would modify the base and all of the instances that use it.

unreal temple
#

Just make sure to destroy it when you're done with it

leaden ice
topaz ocean
#

How is that mechanically different from constructing one with new()?

leaden ice
topaz ocean
#

I mainly ask in case the way theyre cleaned up is considerably different, because you mention I need to destroy it I would like to know where the heck it actually goes when its created. I thought the garbage collector would handle the one created with new().

leaden ice
#

UnityEngine.Object derrived objects all have a C++ half and a C# half

leaden ice
#

Destroy is needed for the C++ half

topaz ocean
#

Ohh because c++ doesnt have automatic garbage collection

leaden ice
#

yes, not only that but even if it did - you need to tell it to drop all the references to the object somehow. You can assume the engine tracks these objects somewhere

topaz ocean
#

If I managed to accidently not destroy the instance is that something I have to manually clean up or would that just require an engine relaunch

leaden ice
#

which may or may not be a big deal

dusk apex
#

Pretty sure when the Editor or application terminates, the memory is freed.

leaden ice
#

^ this for sure

#

but if your game is long running and you do it a lot, it can build up

ashen yoke
topaz ocean
ashen yoke
#

only way for it to know you want a new native object is through the api it provided

gray mural
#

How do I hide this field in derived class?

[SerializeField] protected Direction direction;
leaden ice
#

if you want it hidden in a derived class then derived class was probably the wrong design decision

gray mural
#

I think I just shouldn't care about it

gray mural
pure cliff
#

protected means classes that inherit from this can access it
private means they cant

gray mural
pure cliff
#

or do you mean you dont want it to show up in the inspector?

gray mural
#

I just cannot override it

#

so yeah, I just don't care then

dusk apex
#

You wouldn't be able to inherit the data as private.

pure cliff
gray mural
gray mural
dusk apex
pure cliff
trim schooner
gray mural
pure cliff
#

no need to overcomplicate it with weird hacky stuff, usually this just means you need to further subdivice your inheritence out to make a branch

gray mural
dusk apex
gray mural
pure cliff
gray mural
pure cliff
#

No this just sounds like you need to further subdivice your tree

pure cliff
#

Whats the names of these things so we have common lexicon

gray mural
pure cliff
#

so instead of "the things" I can say what they actually are haha

gray mural
pure cliff
#

kk

#

and then whats the high level reason you dont want one obstacle to have the field exposed

#

like what makes it special

gray mural
#

it's just spike

#

it cannot move like enemy

pure cliff
#

gotcha

gray mural
#

but I have Direction.None anyway

#

(it's enum)

pure cliff
#

No probs, so what you want is to rename ObstacleController to be like, DirectionalObstacleController or whatever

pure cliff
#

and then you want like

ObjectController -> ObstacleController -> DirectionalObstacleController

gray mural
dusk apex
pure cliff
#

And then your spike inherits from just ObstacleController and all the rest inherit from DirectionalObstacleController

gray mural
#

nah, that's so strange to do one more class just to hide one field

pure cliff
#

Now actually, you can pretty much have all your logic in ObstacleController still so

pure cliff
#

this was just your first roadbump that made it obvious that you needed 2 layers of fineness for defining your obstacles

gray mural
gray mural
pure cliff
#

that then saves you writing the same 1 line of code on a bunch of other classes

gray mural
#

I was also thing about doing

EnemyController : ObstacleController : ObjectContorller
pure cliff
#

yeah EnemyController could be a better name if thats the special logic for "has a direction"

gray mural
#

I just haven't invented full logic of my game

#

that's why it's strange

pure cliff
#

yeah so I think you will have multiple layers of defining your classes, and thats super normal

gray mural
pure cliff
#

I also typically subdivide my folders to match these various layers, and I just call it <Category><Type>Base in my folder tree

dusk apex
#

You need to decouple stuff from the base class if they aren't available in every inheriting class

gray mural
pure cliff
#

For example I very likely will soon have EnemyEntityBase abstract class and UIEntityBase in this folder structure

gray mural
pure cliff
#

Though I have largely circumvented that by instead using composition pattern + strategy pattern

#

so instead of logic being on the entities themselves, all they set is "what is my strategy" and paramets for it, and then I grab the matching strategy class for em, I effectively inject in what their AI is for how they behave

gray mural
pure cliff
gray mural
#

I have never used abstract classes before actually 🤔

pure cliff
#

all an abstract class is, is blocking the ability to new() one up

gray mural
pure cliff
#

Like if you have abstract fruit class, and then apple : fruit, as a normal class it means you are allowed to new apple() but you arent allowed to just new fruit()

dusk apex
#

The band-aid solution would be ```cs
Class A
private something//Field can be serialized and exposed to the inspector but private
protected Something//Property exposed to inheritant

gray mural
#

oh, wait

#

no

#

we don't need it

#

you're right

dusk apex
#

Exactly

pure cliff
#

yeah so you wouldnt even have Direction in ObjectController, and only DirectionalObjectController will have it show up

gray mural
pure cliff
#

The other option is do what I am doing:

Dont care what "Direction" stuff like a spike is, it can actually be allowed to face left/right/up, but it has zero impact

pure cliff
#

cause in the end what direction my sprites face is purely handled by the animator

gray mural
#

I'm kinda perfectionist, you see

pure cliff
#

so I would just have the spike have the same sprite for every direction

pure cliff
#

yeah then that honestly is fine

gray mural
#

even though my "sprites" are solid colors now

#

even solid colors as sprites are better than if I draw them myself

pure cliff
#

it mostly depends on

  1. how expensive your directional logic is to be running on things that dont care about it
  2. How many of them there are

Like its possible breaking out the class to refactor the direction logic apart, may cause a significant or insignificant performance change

gray mural
#

making lots of classes and inheriting from them may be quite confusing, but it's much less confusing than if you have 100 half-same classes with repeating behaviour and 5 times more redundant code

pure cliff
#

exactly yup

#

and like I said, usually once you break it out a bit, you quickly start finding other things that belong in that layer instead of the layer above or below naturally

#

as you expand the project and start wanting other features you quickly go "Oh wow thank god I broke this out earlier, cuz now I have the perfect spot for <other thing> to go!"

gray mural
gray mural
pure cliff
#

Im currently bumping into this awkward process of dealing with how I want my architecture to work with "bubbling up" events, because I have designed my whole game engine to be a big tree of services that are the "source of truth", and the monobehavior game objects sit at the very bottom of the tree, and their only job is to be controlled by the parent services

dusk apex
#

Should probably focus on writing code once and not having to touch it again unless you're doing so for learning purposes.

pure cliff
#

but... stuff like click events and whatnot occur on those monobehaviors all the way at the bottom, and the stuff that cares about if the event happens are close to the top, so I gotta like, bubble it up

gray mural
#

I think I will be doing it in my currect game

pure cliff
#

eh its just all the core logic for my game

#

but I like to keep all my code largely aggregated into 1 large stack of services with a single entry point at the very top, and everything cascades down from there

pure cliff
#

I just dislike events but I cant be having my models acting like they are services

ashen yoke
#

you are misunderstanding probably

#

event bus is not related to c# event

pure cliff
#

I know what an event bus is yes

#

Pipe<T> would be the modern C# class to use to make a simple one

ashen yoke
#

the separate services/systems stack is common, but what you described seems like overly imperative approach that defeats the purpose of component model

pure cliff
#

Id still have to hand off a reference to the writer to said classes, Id need to figure out how to do that

ashen yoke
#

can you link to Pipe<T>

pure cliff
#

derp not pipe

#

Channel, my bad

#

pipes are for interprocess stuff, wrong one haha

ashen yoke
#

channel seems to solve a different set of issues

pure cliff
#

Channel is what I would use for an event bus

rocky jackal
#

I first generate a list of directions the green lines are the directions within the fov and the red ones are outside. The yellow line is the transform.forward and im trying to find the closest unobstructed direction forward in the fov area but for some reason it returns the closest unobstructed world forward transform. can someone help ?

pure cliff
#

async support (but not mandatory), and works fine for a pub/sub model

ashen yoke
#

typically a simple event bus would act as a mediator

#

alright

pure cliff
#

var eventChannel = Channel.CreateUnbounded<MyEvent>()

and then you have eventChannel.Reader and eventChannel.Writer which you can async or synch read/write off of respectively

#

and hand off the reader to the thing you push to, and then you can hand the writer off to everyone who has events to push onto the bus

#

its pretty much just a Queue but it has support for stuff like Streams and Async reading/writing which can be nice

ashen yoke
#

can you show me a simple example of some ui mono raising some event and some system subscribing to that event?

#

i want to compare apis with mine

gray mural
#

@pure cliff @dusk apex thank you both for help guys btw

pure cliff
#

yeah so I have

public class WaitButtonEntity : EntityBase
{
    ...
    public event EventHandler OnClick;
    public void Clicked()
    {
        if (Pausing)
            return;

        OnClick?.Invoke(this, null);
    }
    ...
}

As an example of the monobehavior (EntityBase is a mono)

#

It has a button which hooks into the Clicked() method

ashen yoke
#

ok how is OnClick linked to the channel?

#

where does the initialization happen

pure cliff
#

Im not using a channel atm I just hook into it directly

#

I was just saying if I wanted to use a bus, Id use Channel<T> but I havent yet

#

My main issue with event bus is it restricts you to trying to figure out how to make all your events "sameish" so they can use the same bus, and that can cause antipatterns to arise

#

eventbus mostly makes sense when all your events really are gonna be sameish in some way so thats not a downside

ashen yoke
#

i dont understand

pure cliff
#

That or you have to make a bus for each different type of event which sort of defeats the purpose

ashen yoke
#
struct OnClickedSomeButton : IEvent{}
void Clicked()
{
  EventBus<OnClickedSomeButton>.Raise();
}
#

this is my current

#

yes there is no shared channel/pipe

#

havent required it, yet

pure cliff
#

so right now I just hook into the event like this

public class InputService : IInputService
{
    ...
    public InputService(IEntityService entityService)
    {
        EntityService.WaitBtn().OnClick += OnWaitBtn;
    }

    private void OnWaitBtn(object sender, EventArgs e) { ... }
    ...
}
magic heron
#

Hi guys, i'm trying to make an object stacked when clicked to only take half of it, but when both conditions are met, nothing happens, can someone please help me?

#

sorry to interrupt btw

ashen yoke
#
public class InputService : IInputService
{
    EventBinding<OnClickedSomeButton> _onClickBind;
    ...
    public InputService(IEntityService entityService)
    {
        _onClickBind = new EventBinding<OnClickedSomeButton>(OnWaitBtn);
    }

    private void OnWaitBtn(OnClickedSomeButton ev) { ... }
    ...
}
#

here

ashen yoke
#

my bus api

#

showing example

pure cliff
#

ah kk

brazen narwhal
#

Hello, is it possible to set a GameObject to a specific size and not just scale?

lean sail
brazen narwhal
#

Wait, I may be misunderstanding things, Im just new to unity. Does any two objects given the scale of (1,1,1) will be the same size?

gray thunder
#

no

pulsar dove
ashen yoke
#

you have to understand that "size" is an abstraction

#

an object "size" can mean different things, for example in most cases you mean visual bounds of the mesh

gray thunder
#

You could have a huge building and a small player

ashen yoke
#

the object can have no mesh, but a collider, then the size will be the bounds of the collider

gray thunder
#

both being the scale 1,1,1

ashen yoke
#

the object can have no bounds from renderers or colliders, so it wont have any size

brazen narwhal
#

Is there a way to make them the same?

ashen yoke
#

what do you want to make same size, 2 meshes?

brazen narwhal
#

I need to make a GameObject change in size based on a given scale

ashen yoke
#

2 meshes?

brazen narwhal
#

Yes? Sorry, I am not used to the terms in unity

lean sail
brazen narwhal
#

The game object is a 2d sprite

ashen yoke
#

so its a sprite

#

sprites also have bounds and size

#

what is the problem you are trying to solve?

#

ie i place one sprite next to another but they are displaying differently

#

show a screenshot

brazen narwhal
#

I need to change the size of the object so that it will be in matching sizes with a map

ashen yoke
#

so you want to stretch the sprite over the whole map?

#

as background?

brazen narwhal
#

The size of the object may vary in sizes since it will be uploaded by the user

ashen yoke
#

you have several instruments, first ppu in the sprite import settings

#

then scale

brazen narwhal
#

The user will also give the scale in m(unit)

ashen yoke
#

ok do you have consistent ppu across all sprites?

#

can the ppu be used as a basis for size?

brazen narwhal
ashen yoke
#

how does user set the meters?

brazen narwhal
#

The user just knows what the size of the sprite is based on meters. Because it will be made with that on mind

#

But their sizes will not be uniform

ashen yoke
#

size of the sprite is based on meters

#

what does it mean

brazen narwhal
#

The user will make a sketch outside the app and will upload it. It will then be overlayed on a real world map

ashen yoke
#

ill rephrase

brazen narwhal
#

Thats why it needs to be correctly scaled to meters

ashen yoke
#

what is the correlation between meters, and the sprite user makes

#

what exactly should user do to achieve a 2x2 meter sprite

brazen narwhal
#

For example, the user makes an image which should be 2m in length on real world. Of course it will not literally be a 2m image. What I need to do is to change its size to be 2m when overlayed on a real world map on the app. The user knows that it is 2m in size and will be able to input that on the app. But the problem is the images made may not be in uniform sizes. Like one may make a 500x500px for 2m irl size. Another one may make a 700x700px for 2m irl size

ashen yoke
#

so user sets the size in meters

#

in the app, there is a input field or dropdown

brazen narwhal
#

Yes

#

An input field

ashen yoke
#

ok, so you have the size in provided by user, you have constructed the sprite at runtime with Sprite.Create()

#

which accepts ppu value

#

use some universal ppu across all sprites, for example 100

#

then simply scale the image by the factor of the meters the user provided using 100 pixels as one meter initially

#

so a 512*512 sprite will be ~5x5 meters

#

target is 2x2

#

the math will be something like

float scaleX = (ppu * targetMeters.x) / sprite.width;
brazen narwhal
#

Thank you so much! I can finally do itUnityChanCheer

#

The way you explain things is so easy to understand. Also sorry for not being very clear at asking questions

brave harness
static matrix
#

How can I set whether or not a particle system loops on runtime?

simple egret
# brave harness

It's probably because your buttons are not anchored properly, so their detection area gets moved when the resolution changes.
Ask in #📲┃ui-ux as it's not a code issue.
Post the question as text for folks with limited data plans and slow networks.

brave harness
simple egret
#

What?

hasty haven
#

Love when one of my methods starts always returning true :(

simple egret
brave harness
#

K

soft shard
# earnest gazelle A developer presses play button in the editor when the scene is playing. I want ...

Ah, misunderstood what you were trying to do - since this is a Editor script, you want to use EditorApplication.isPlaying instead, with your example:

if (state == PlayModeStateChange.ExitingPlayMode)
        {
            if (EditorUtility.DisplayDialog(DialogTitle, DialogMessage, "Yes", "No")) {  } //do nothing, exit will happen automatically if "yes"
            else { EditorApplication.isPlaying = true; } //prevents exit if "no"
        }
brisk grove
#

Hi

#

guys i dont know how to use github

#

can any 1 help me

brisk grove
#

1 thig

#

how to open a unity project from it

#

...

dusk apex
#

Say what? You'd use the Unity Hub and Editor to open Unity projects.

#

GitHub is a code hosting platform for version control and collaboration. It lets you and others work together on projects from anywhere.

#

Relative to working together and from anywhere: you'd have the same versions synced using version control.

leaden ice
modern creek
#

Is there a preset or an easier way to set a RectTransforms anchors based on the size of the parent? I'm finding I do the following - and it seems like there should be a better way.

In the video, I show how I get a dialog box to resize properly based on the parent. First I do it without any anchoring, then I do it with the default anchoring, then I show how I get it to work correctly: I have to memorize the size of the parent (in this case, 1920x1080), then set the child to stretch, then manually set the left/right/top/bottom anchors to AnchorMinX = L/W, AnchorMaxX = 1-(R/W), AnchorMinY = B/H AnchorMaxY = T/H

I do this often so that all my elements size properly but it seems like this should be a default anchoring setup somehow? I'm thinking maybe I should/could write an inspector plugin for this? Or am I just doing something incredibly naive/wrong?

leaden ice
#

could you not just think of it that way?

soft shard
#

There are also additional options if you hold down SHIFT or ALT before clicking, when you open that menu @ 7 seconds of your video, I believe SHIFT lets you do essentially what your doing manually

modern creek
#

Yeah, I'm just saying I have to do the above like... over and over and over when I nest components. If I do a nav bar that's 1920x100, then every button inside it that I want to be scaled properly has to do the above

#

I feel like there should be a preset? for what I'm doing that I'm not aware of

#

Or is this anchoring just part of y'alls layout process as well? Ie, figure out some reference resolution and manually lay every item out pixel by pixel..?

leaden ice
#

I defeinitely don't think about pixels

#

I think in terms of percentages usually

#

occasionally "pixels" when doing offsets at the top

#

e.g. like 10 units from the border or whatever

#

so there's no math - in your case I would have just written .24 and .76 directly

modern creek
#

yeah the only problem with that (using "pixels" instead of percent) is then they break when different scales

#

ok, i could probably shift my brain into working like that

thick frost
#

I always thought that "code rot" was the tendency of unmaintained code to fall out of date with libraries. But I've seen it used elsewhere in different context. How so you folks use it?

modern creek
#

i could even make my reference resolution something like 10000x8000 (or whatever 16:9 is)

modern creek
leaden ice
modern creek
#

Or not even negatively connotated scope changes. IE, you've got a player object with a deepcopy:

public struct Player
{
  public string Name;
  public Player DeepCopy()
  {
    Player p = new()
    {
      Name = this.Name,
    };
    return p;
  }
}

Then your designer says "we need age, too!" so you add public int Age and now your DeepCopy() is "rotten". Simplistic example, perhaps

brave harness
random oak
#

Help my Coroutine is stopping inside an if statement and I have no idea why. It is only in one particular condition in the coroutine, there are no errors and I am not deactivating the script in any way.
Anyone know why this might be and how to check what's wrong?

leaden ice
simple egret
leaden ice
#

The only things that will stop a coroutine are:

  • Deactivating the GameObject it's running on
  • Calling StopCoroutine or StopAllCoroutines
  • yield break
  • Destroying the GameObject it's running on
  • an exception being thrown
    @random oak
random oak
#

it only stops when reaching line 39

leaden ice
#

it will only stop on yield statements

#

unless you get an exception

random oak
#

I mean it prints but nothing else happens after

#

no errors

leaden ice
#

TurnManager.Instance.NextTurn(); will happen next

#

add more logs to check

random oak
#

it doesn't reach line 80

leaden ice
#

line 80 is in the else

#

else won't run

#

since you're in the if

#

87 will run after 39

brave harness
random oak
#

sorry line 89

#

it always reaches line 89 normally but doesn't when inside line 39

leaden ice
#

(the whole window)

random oak
leaden ice
# random oak

Ok first off you have Collapse turned on in your console

#

you should turn it off

#

with Collapse on the logs will not always show in order

#

second - please show the full console window in these screenshots as it's important to see everything especially the top right and top margin

random oak
#

ahh didn't know sorry

leaden ice
#

See how ENDED ROUTINE has a (2) at the end?

#

That means that it happened twice

#

so it is indeed running when you expect

#

but due to the COllapse setting it is not showing again after the other log, it is merely being added there as a (2) @random oak

#

when you turn off Collapse it will show as expected

random oak
#

ok let me try again with no collapse, I have to restart editor cause unity flooded me with errors when I did

#

2022 shenanigans

#

yeah it's weird now is working after draw??

#

yeah it keeps working so far, idk so maybe some weird editor bug causing coroutine to act strange?

#

I'm so confused

leaden ice
#

It was working always

#

the logs were just obfuscated by the COllapse setting

#

at least that's how it seems from my outsider perspective

random oak
#

the logs were there somewhat put all over the place to try to find it , but in the game it wasn't switching turn to other player at times

#

anyway seems to work so far ! so who knows if it was just internal editor bug/crash in unity causing weird behavior .
Never happened on 2021
ty for you help @leaden ice

brave harness
daring cove
#

Hey,
How to calculate the angle required to turn a vehicle?

Vector3 direction = destination - vehicle.transform.position;

float angle = Vector3.SignedAngle(vehicle.transform.forward, direction, Vector3.up);

int angleNormal = angle > 0 ? -1 : 1;

TurnHull(angleNormal);

This always causes angle to get stuck between 166 and -166 causing angleNormal to be 1 and -1 meaning the vehicle doesn't know where to turn and just turns in place forever.

static matrix
#

c# deciding to use python syntax for switch-case for no reason:

leaden ice
lost dove
#

Greetings, hoping for someone to have a look at this.
When my player faces direction 0, the determined input axis needed to rotate towards the mouse position is fine. However if I start rotating my player ship, then the axis keeps jumping between 1, 0 and -1.. and I'm not sure how to make it consistently just stay 1, or -1 depending on the easiest path towards target angle.

#
            var direction = Entity.Transform.Rotation.ToEuler().Y;


            //var direction = Properties[(uint)EntityPropertyTypes.TurretRotation].Int;
            // Get the mouse position in screen coordinates
            Vector3 mousePosition = Input.mousePosition;

            // Calculate the target direction angle based on the mouse position
            float targetDirection = Mathf.Atan2(mousePosition.y - Screen.height * 0.5f, mousePosition.x - Screen.width * 0.5f) * Mathf.Rad2Deg;

            // Adjust the target direction angle to match the desired rotation
            targetDirection -= 90;

            // Normalize the target direction angle to be within the range [0, 360)
            targetDirection = (targetDirection + 360) % 360;

            // Calculate the angle difference between target direction and current direction
            float angleDiff = targetDirection - direction;

            // Normalize the angle difference to be within the range [-180, 180)
            if (angleDiff >= 180)
                angleDiff -= 360;
            else if (angleDiff < -180)
                angleDiff += 360;

            // Determine the direction based on the angle difference
            int rotationDirection = 0;
            if (angleDiff > 5)
                rotationDirection = 1;
            else if (angleDiff < -5)
                rotationDirection = -1;

            // Set the direction value to your desired input or use it as needed
            // For example:
            ksReactor.InputManager.SetAxis(Axes.TURRET_ANGLE, rotationDirection);```
leaden ice
static matrix
#

different question: Can I change the material of a particlesystem on runtime?

lost dove
#

@leaden iceThank you. I cannot use signed angle however, at least not in that manner because I will be dealing with a single angle coming from the server, telling my client that "my turret is rotated to x rotation", and according to that turret rotation, I need to determine whether or not it is facing my mouse, and then determine how to reach it with an axis, so that the player can let the server know where to put it.

#

I'm using my player ship angle presently as a dummy until it is perfected.

leaden ice
#

which is the cause of your angst

#

is that what the server will be doing?

#

The server should use SignedAngle

lost dove
#

The server is just updating a float that starts from 0.

leaden ice
leaden ice
#

then you won't have euler bouncing nonsense to worry about

lost dove
#

oh wow

#

delta angle looks promising

lethal vigil
#

How can I make sure my game stays the same on all mobile resolutions. Its works fine most phone devices but if someone was to play it on the ipad, it cuts too much from the left and right side. My game is a endless side scroller. I know there are anchor stuff I can do which works fine for ui but how can I made sure all game objects also fit in all screens

leaden ice
#

you would have to do letterboxing or something to force an aspect ratio

lethal vigil
leaden ice
#

you can also do some math and set the camera's orthographic size according to the aspect ratio to show what you want to show

leaden ice
#

one of those

#

or changing the shape of the world according to aspect ratio

lethal vigil
#

what would u suggest?

leaden ice
#

It's not my game

#

probably just setting camera size

daring cove
# leaden ice isn't this backwards? `int angleNormal = angle > 0 ? -1 : 1;`

Thanks It was flipped haven't seen that before, its been weeks 🙃

I'm having bit of trouble figuring out pathfinding for vehicles.
Is there a way to make NavMesh.CalculatePath not find the quickest route, but calculate a more central route. I already have baked navmeshes with ideal values but the pathfind algorithm always manages to find a way get off the navmesh by taking the very edge of the navmesh and clipping a fender on the side of house.

quasi crow
#

Hey, just curious - how do you guys structure your game managers? I have seen some enum-based game managers and I also heard about finite state machines, is it a good idea to use one along with a game manager?

leaden ice
#

It's different in every single game I make

#

some games need a more formal state machine

#

others don't

quasi crow
leaden ice
#

Probably two scenes

#

Menu scene and Game scene

quasi crow
#

Yeah, something like that, so I guess the manager should just handle switching the scenes and maybe toggling some pause and game over menu?

leaden ice
#

perhaps

#

basically oyu're either:

  • in the menu scene, menuing
  • in the game scene waiting to start the game
  • in the game scene playing the game
  • in the game scene paused
  • in the game scene looking at a gameover UI
#

so that game scene stuff could be a state machine if you want

#

but it's also simple enough it doesn't need to be formalized much

quasi crow
random oak
#

does unity support nullable types?

public bool? MyNullableBool()
{ return null; }```
swift falcon
#
direction = tempRotation.eulerAngles;
rb.AddForce(direction * 500f * Time.deltaTime * ai.projSpeedBonus);```
swift falcon
#

any ideas for why this will only add force upwards?

leaden ice
#

rotation is a quaternion

#

don't read .z from it and expect anything useful

somber nacelle
leaden ice
swift falcon
#

aight so how would I go about getting the angle from the rotation?

leaden ice
#

project the rotation on the x/z plane?

swift falcon
#

essentially just move it forward on it's z axis

#

it's in 2d so i cant use forward

leaden ice
#
Vector3 forceDir = Vector3.ProjectOnPlane(transform.forward, Vector3.Up);```
#

oh 2d

#

then

swift falcon
#

and transform.right gives me issues for some reason

leaden ice
#

maybe you want transform.up

#

it dpeends how your sprite is laid out

swift falcon
#

I'll try it out

leaden ice
#

also yes get rid of Time.deltaTime and 500

swift falcon
#

yeah i gotta fix all my rigidbody settings in this project still

#

this is the first game I made so a lot of the early stuff is messy

#

I just set the direction to transform.right and it worked this time thanks yall.

hushed dust
#

If you're making a game in which the player gets surrounded by dozens of enemies, and they make footstep sounds when they walk... what's the most common solution to preventing a cacophony of footsteps?

leaden ice
#

Otherwise they'll all add up and break your eardrums

#

you can of course also do some kind of pooled audiosource thing and limit the number of concurrent active audio sources

hushed dust
#

yeah i do that part already

#

normalize is a good tip though. do you generally apply normalize to all your mixing groups?

leaden ice
hushed dust
#

haha hey thats one more than most 😄

leaden ice
# hushed dust haha hey thats one more than most 😄

For context: in that particular case it was sort of a tetris / bejeweled style game and when the blocks were eliminated they would burst into particle systems (sort of like a firework explosion). Those particles would fly over to the score counter UI and each particle would make a small sound when it finished doing so.

When you scored a big combo all the simultaneous sounds were maxing out the speakers and very unpleasant. Using the Normalize effect made it sound better.

hushed dust
#

@leaden ice oh man... i also did not realize you can add duck volume to a mixer group and add a send above it and send it to itself

sturdy thorn
#

Excuse me, I'm finding an issue when I try to make the enemy wander randomly they get stuck within the obstacles, I wrote the code that sets the destination anywhere else when they touch said obstacles, but they wont avoid them and will just get stuck.
[18:32]
https://pastebin.com/fUkn47gp

mossy gust
#

How could I save a list to a json file?

leaden ice
devout nimbus
#
public State.CombatState CheckCombatState() {}```

I assumed you could have methods with return values on interfaces but I get "Not all code paths return value"
The only place the interface is implemented returns a value. Are you just not able to have return values with an interface? Been a while since Ive touched C#
somber nacelle
#

you're not returning anything there

devout nimbus
#

Yes it is the method on the interface

somber nacelle
#

well you've provided a default implementation

#

which you are not returning in

devout nimbus
#

I have to provide a default return value? Odd

somber nacelle
#

you do if you provide a default implementation for the interface method. if you do not wish to do so remove the curly brackets and replace them with a semi colon

devout nimbus
#

It works. I assumed you wouldnt have to with the default implementation

#

That works also

#

Thats stupid imo but it works. Thank you

somber nacelle
#

you either declare the method without a body so it does not have a default implementation and your implementing objects have to provide their own implementation for the method, or you can use the default interface method where you've declared a body for the method so it must be a valid body, including required returns

devout nimbus
#

Makes sense

dusky cosmos
#

Shader error in 'Universal Render Pipeline/Lit': maximum ps_4_0 sampler register index (16) exceeded at INVALID_UTF8_STRING(11) (on d3d11)

I get 5 similar errors while getting build

rotund moat
#

how to lock character in one rotation

leaden ice
primal wind
#

Also if it's a rigidbody you would need to add a constraint on rotations otherwise the world could interact with it in such a way that it would rotate

copper blaze
#

does anyone know how to autoformat c# code in visual studio code such that the curly braces start on the same line as method declarations? (sorry if i'm asking this in the wrong channel, not sure where else to ask)
example:

private void method1() {
  // i want this
}

not

private void method1()
{
  // not this
}
somber nacelle
unreal trench
#

didnt know, sorry

fathom plank
#

I created this little healthbar rendering manager script, it works well enough, but feels somewhat awkward. Basically the intention is that healthpools are just health amounts current/max, etc for a character. The HealthBarManager class is attached to a canvas, and determines which healthpools should currently be rendered, takes care of making sure the renderers are in place while the healthpool is on screen, recycling them when they are no longer on screen. Anyway, just looking for any feedback on the design of this 🙂

wintry crescent
copper blaze
lean sail
wintry crescent
#

I can never remember, help
If I have a class A, and a class B:A
and I have
A b = new B();
and I call b.GetType()
will I get A or B

wintry crescent
lean sail
#

overall i dont see anything wrong though

fathom plank
#

this is the sort of heiarchy ive got currently

lean sail
#

You could probably just keep the current setup, and disable the healthbars on the canvas while the enemy is offscreen, while just not updating the healthbars position

#

When they come back on screen, enable and update position

fathom plank
#

thats currently what happens with the pool manager class. when the healthbar goes offscreen, it gets tossed back in the pool so whenever any other character with health comes on screen, it can be assigned one of the available healthbars, i figure it was a good idea since not all characters will be within the viewport at all times so this keeps the number of objects down a bit

#

so like if all 4 of those tanks are destroyed, the 4 healthbars will stay attached to the canvas but disabled, when it new tanks are created, as they come on screen, the healthbars will reactivate as needed and get assigned to the tanks as they come on screen

hoary swift
#

anyone knows if there is a method like AssetBundle.LoadAllAssets<T>() for addressables which takes an IResourceLocator as a parameter?

ivory ginkgo
#

Are there some better practices to acquire lists of players/enemies/entities/items that are available in the level other than the basic options like below?

GameObject.FindObjectsOfType(typeof(SomeScript));
GameObject.FindGameObjectsWithTag("SomeTag");

Is there a better way to cache these items in a Singleton List on spawn or something? I'm not sure on the best practice here. Any ideas or references would be great!

ashen yoke
quartz folio
fathom plank
ashen yoke
#

its actually pretty cool, and doable

ashen yoke
ivory ginkgo
ashen yoke
#

separation of concerns

#

what keeps track of enemies? what makes sense to keep track of enemies? enemy system? etc

#

a generic EntityManager is also good, you can use dictionaries by types

quartz folio
#

The best practices in games are very "do whatever makes sense for you and your setup"

ivory ginkgo
ashen yoke
#

depends, you can make a big mess if you dump everything into a single class and use direct references to strongly typed lists

#

if it can be neatly generalized, abstracted behind a single api its good, healthy

ivory ginkgo
#

I might try an EntityManager with a dictionary or lists of each type and see how that goes. My project doesn't have a lot of different types, it's pretty simple. Appreciate the help. May seem like a simple thing, but I like to use good/best practices where I can, so I was curious.

native copper
#

I need help and I wasn't sure which channel to put this in. I made a lego wall in blender and in unity I wanna make it so when the player shoots a rocket at it the wall blows up into a bunch of lego bricks. I can make it so when the player shoots the wall the wall disappears and a lego block instantiates but I want it to instantiate a bunch of different colored blocks and have them spread out in a bunch of directions

cosmic rain
lean sail
native copper
#

well how would i get the instantiated ones to have a random pool of colors

native copper
#

thanks

lean sail
#

or else the user will just see it change colors randomly

native copper
#

yeah i guess your're right

rancid frost
#

does anyone know why my vertical meshes (the blue color shapes) are see through?

leaden ice
#

triangles in meshes are single-sided

#

unless you use a mateiral that renders backfaces

rancid frost
#

hmm, shouldnt I be able to not see the blue faces at all then?

#

When I flip it back, it looks fine

#

But the order is wrong

#

top is down and down is up

leaden ice
leaden ice
ashen yoke
#

no thats not normals

rancid frost
leaden ice
#

what does "flip" mean in this context?

rancid frost
#

flipping the x axis

#

of the meshes

leaden ice
#

that flips it upside down basically

ashen yoke
#

where triangle will be facing is dictated by which order it was constructed

#

clockwise and counter clockwise

leaden ice
#

so you're seeing the back of many of the faces when it's flipped

#

which is generally not visible

#

unless using a special material

rancid frost
#

no, im using the sprite defalt

leaden ice
#

you're using a sprite material for a 3d mesh?

#

that's probably part of the issue too

ashen yoke
#

are you saying you made a hexagon out of sprites?

leaden ice
#

the normal mateiral would be Lit or Unlit (or Default in BIRP)

ashen yoke
#

the only way it will work is if the material is opaque

#

or at least cutout

#

otherwise the alpha sort will fail at specific angles

#

im ignoring the fact that this is the weirdest way yet ive seen anyone construct a hex

rancid frost
#

the problem is this
The blue verticals are rendered from TOP to bottom,
so a hex that has a higher Y position will add blue verticals to its side

however, the generated mesh, with default orientation it looks as though the blue verticals are generated bottom to top

rancid frost
ashen yoke
#

read on "winding order"

rancid frost
leaden ice
#

ok so you[re not doing procedural mesh generation

#

you're just using a fuckload of meshrenderers

rancid frost
#

yes

leaden ice
#

btw why are you using Plane

#

instead of Quad

#

Quad would be way simpler

rancid frost
#

ok, will use quad

leaden ice
#

and when you flip it upside down (why?) you won;t be able to see the backs of the planes

#

because you can never see the backs of the default plane mesh

#

(barring a backface shader)

rancid frost
leaden ice
#

Is there a question in here somewhere?

rancid frost
#

I dont get why its flipped, my triangles are rendered clockwise

leaden ice
#

it just looks like your code is positioning things incorrectly

#

it's unclear what data we're starting with to generate this stuff

#

and what the code is actually generating

#

and of course, we haven't seen the code at all

rancid frost
#
if (Position.y > hex.Position.y)
                {
                    (int, int) sData = OppositeCorners[i];
                    (int, int) data;

                    data.Item1 = i;
                    data.Item2 = (i + 1) % 6; // so the last one loops back to the first one
                    
                    // the current hex's side vertices
                    Vector3 pos1 = GetSideVertexPosition(data.Item1);
                    Vector3 pos2 = GetSideVertexPosition(data.Item2);
                    
                    // the surrounding hex's side vertices
                    Vector3 sPos1 = hex.GetSideVertexPosition(sData.Item1);
                    Vector3 sPos2 = hex.GetSideVertexPosition(sData.Item2);

                    int sv = SlopeVertices.Count;
                    int v = Vertices.Count;

                    SlopeVertices.Add(pos1);
                    SlopeVertices.Add(pos2);

                    SlopeVertices.Add(sPos1);
                    SlopeVertices.Add(sPos2);
                    

                    //SlopeTriangles.AddRange(new int[6] {
                    //    sv + v + 0, sv + v + 1, sv + v + 2,
                    //    sv + v + 2, sv + v + 1, sv + v + 3
                    //});

                    SlopeTriangles.AddRange(new int[6] {
                        sv + v + 3,  sv + v + 1, sv + v + 2,
                         sv + v + 1,  sv + v + 2, sv + v + 0,
                    });

                    SlopeColors.Add(SlopeColor);
                    SlopeColors.Add(SlopeColor);
                    SlopeColors.Add(SlopeColor);
                    SlopeColors.Add(SlopeColor);
                }
#

What the code is doing is getting those 4 corners and setting vertices and triangles

#

it does it for each side of a hex

leaden ice
#

so wait you are doing procedural meshes?

rancid frost
#

So in summary,
for each surrounding hex, we check if the surrounded hex is lower than the current hex, if it is draw the height vertice

leaden ice
#

I'm confused because you showed the Plane mesh before

rancid frost
#

I want to replicate the tilemap system

#

but with meshes

leaden ice
#

I mean there's a lot of moving pieces here

copper blaze
leaden ice
rancid frost
#

let me verify that

#

what do you at the very least understand my dilema?

leaden ice
#

I mean I understand that your procedural mesh generation is working improperly

#

I don't really see what you mean as a "dilemma"

#

I know it took me about three weeks to get a working procedural mesh system for building hesagonal pipes in my factory builder prototype

#

procedural meshes are hard

#

I don't really think "bottom to top" or "top to bottom" matters terribly much - either way it's connecting the lower and higher hex

rancid frost
rancid frost
leaden ice
#

no way of knowing from this screenshot if the y values are correct

#

they're certainly internally consistent

rancid frost
#

I see

leaden ice
#

and make sure it matches up with expectations

leaden ice
#

the question is way too vague to be answered honestly

#

it depends on what these things are, what they do, how they interact with the rest of the game

#

answers range from basically... strings to enums to ScriptableObjects

#

it really depends on the needs

#

inheritance is usually not the best way, I'll say that

#

could be

#

that's kinda similar to SOs

oblique spoke
#

You can replace the strict inheritance hierarchy with interfaces. Create item classes based on functionality and add various interfaces based on the features of the item to expose them to other systems in the game.

oblique spoke
#

You could try composing the items with components or by other means, but settings exposed in the inspector can often handle a lot of variants.

twin yoke
#

guys I need help with an error I am getting and I don't why it appears. The issue is that is it is random:ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <4911eca47f294e18a7b3306f02701303>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <73c3b9fa4da644c9a21a8a16d8e2909f>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <ddc34215cb194bc6b42a1ae3b66800fe>:0)

leaden ice
twin yoke
#

I remove a variable that goes a little bit like :
[SerializeField] public Transform parent;
and it seems like the issue is gone for now but I don't why

#

I was dynamically creating sprites and put them as child under a specific parent I wanted

#

at least for now, it seems like it is fix. Sometime, it work fine for hours then later I got errors like this

dusk apex
#

Parent is a property of Transform that you cannot set to null. If you've got your own variable called parent, make sure you're setting that variable and not Transform's parent property.

oblique spoke
#

Updating to the latest patch version might address it

twin yoke
#

ah man thx

#

I will update unity ig

#

I have worked with c++ before so getting errors gave me a trauma with null errors

broken fractal
#

I am using this method to rotate my camera and the new input system, how can I go about clamping this rotation so it doesn't rotate more than -90f, and 90f. thanks!

#

(the value from the input event returns from -1 to 1)

dusk apex
#

Accumulate rotation deltas in a variable and subtract the excess amount from your calculation before rotating.

broken fractal
#

hmm thanks

quartz folio
spark flower
#

how do i get angle diffrence but wit hpositive and negative value?

#

vector3.angle gives just positive

pure cliff
#

Is there any easy/handy way I can add a "test" button as a component in the editor or whatnot, that I can click to invoke methods on mono behaviors and etc?

not a button in the scene, but like one I can click in the inspector? Ideally with as minimal effort as possible just so I can test out that when the method is invoked, it does what I need it to do

#

as an example I wanna test out Kill() methods for dying enemies in my game, so ideally I just click on the enemy in the editor, swap to game view with inspector open, and click a button in the inspector on the component that'll just call the method directly so I can make sure the method does what I want it to do

somber nacelle
#

if you use naughty attributes or odin, both of them have Button attributes to call methods from the component inspector. otherwise you could create your own with some editor scripting

pure cliff
#

do they add any overhead to the actual game I compile or is it purely just editting tools?

lean sail
somber nacelle
#

yeah you keep all your editor scripting in an Editor folder since nothing that uses the editor will actually be compiled in a build

pure cliff
#

gotcha

quartz folio
#

The easy thing to do is just decorate a method with ContextMenu and then you can right-click your component and call it

abstract nimbus
#

it's for a chess application

lean sail
# abstract nimbus https://codeshare.io/mp9RY4 Is this spaghetti code? 🤔

probably, but i doubt anyones really gonna take the time to go through that and try understanding it, this is a pretty bad way of writing it. Its really not readable, not commented, and you definitely dont need to chain so many linqs together. Imagine u are a new developer trying to understand existing code and this code is the first thing you see

abstract nimbus
#

yeah my first version had many nested foreach loops and if statements but I had too many so I tried to use Linq to get less nested stuff but using Linq was also a mess

quartz folio
#

new { variation, move } is this an anonymous type kekwait

abstract nimbus
#

a short explanation of what it does: the string moveNotation as the parameter might look like "d6 Nf3 e5" so what my code does is it looks for a variation that has made all those 3 moves in the same order

lean sail
#

you should just stick to the foreach version, i guarantee it'd be more readable

abstract nimbus
abstract nimbus
lean sail
#

then make a method for some calculation

abstract nimbus
#

yeah I guess

quartz folio
#

anonymous types are truly disgusting, just use a value tuple

abstract nimbus
#

oh I did ToList on the split for no reason 😂

lean sail
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.

lean sail
#

just incase someone decides to put something bad in there

abstract nimbus
#

the foreach version is at least more readable than the Linq version 😂

#

but it has too many nested stuff

#

uh you can't edit that one right?

lean sail
#

i wouldnt say its so bad that you should refactor purely because of the nested statements here. I also dont know what the code is doing so its hard to say if you even need all this, i understand the goal but most of these values dont really mean much to me.

#

yea cant edit

abstract nimbus
#

do you know how chess move notations works?

#

cuz that's part of what my code does

lean sail
#

yes, ive played chess a bit but i dont know what a chapter is

abstract nimbus
#

a chapter contains variations and a variation contains a list of moves

#

so it's like a book kinda

#

so a variation is could be e4 e5 Nf3 Nc6

#

and if moveNotation is e4 e5 the method will return that variation

#

but it will not return that variation if moveNotation is e5 e4 because that's the wrong order

#

so currentComparingMoveNotation makes sure I do it in the correct order

lean sail
#

what are you storing this for, predetermined AI moves?

abstract nimbus
#

the moves are from a book that I've purchased so I pulled all those moves in to my app

#

so this method is like asking "when do I play e4 and d4" for example

#

and it's a Dictionary so it doesn't get multiple variations with the same position

winged mortar
#

Youve definitely misused linq

abstract nimbus
winged mortar
#

For each looks fine to me

abstract nimbus
#

okay

lean sail
#

im still confused what you would actually use that for, sounds like some chess learning app. From the problem it sounds like you do need all the nested statements, but i almost wonder if itd be better storing all the related variations in one collection then searching through that instead of calculating a subset everytime.
Chess related calculations always suffer from performance/memory issues though so you'd probably have issues either way

abstract nimbus
#

the reason I made this method is because while I play chess in the opening stage, I somtimes ask myself "when do I play d6 in this opening?" Or "when do I play both e6 and d6?" and this method gives me all the variations that answers questions like that so it's just a way to find what I'm looking for quicker

lean sail
#

all the sites that do something similar to what youve described just have massive databases, at least from what ive seen

#

its a memory vs performance tradeoff, where these sites have the money for memory

abstract nimbus
#

there are many apps that don't have all the features that I want so I made my own app with a mix of features that I want lul 😛

#

it's also for personal use only

winged mortar
#

Honestly you are rpobably better off doing some regex thing

#

Instead of this

abstract nimbus
#

hmm

#

that's interesting

winged mortar
#

You have a list of all of the variations

abstract nimbus
#

yeah but the list of moves are in the list of variations tho

winged mortar
#

If you are looking for kd4 rf2

lean sail
winged mortar
#

Just find it

#

Yeah basically a big database

#

Which isn't much different from what you have right now

junior delta
#

Hello

abstract nimbus
#

true 🤔

lean sail
#

especially if its just on your pc, memory shouldnt really be an issue

winged mortar
#

Depends on how many pages the book has that he purchased Kekw

abstract nimbus
#

this is my "database" 😂

lean sail
#

you can easily hit 1m+ lines on a database, though with chess i imagine that'll be not much

#

yea thats not much

#

my first job i opened a "database" of 2 million entries with 50 columns each. This is lightwork

#

it was in excel too

winged mortar
#

Ye this shouldn't be a problem

winged mortar
abstract nimbus
#

but I'm using SQLite as well so the first time I run the app I read from the json files and add them to the SQLite database and the next times I don't need to read from the json files

lean sail
#

it did take like 2 minutes to open though so id go get free coffee everytime i had to open it lol

winged mortar
#

And this where your caffeine addiction started...

winged mortar
#

But you can just have it in memory if you have a simple structure

#

Isn't sql lite in memory as well?

#

If it isn't you'd still be dealing with your IO

lean sail
#

ive never used sqllite so i dont really know about it specifically

winged mortar
#

Also if performance is important look into an algo like this one

gray mural
#

Hello, do you guys have any ideas how to make level creator mini-engine in Unity?
Probably like e.g. level creator in Geometry Dash, where players can create their own levels and play them.
Let's not talk about making it multiplayer, how do I implement this so that just I can create levels in my own game?
Everything that is instantiated in the game - stays just in game and doesn't affect editor.
How do I save levels and then make me able to use that levels?

Even e.g. instantiating prefabs on random position when pressing space button. Then when game is finished and prefabs are spawned, this (I think) Scene should be saved somewhere.

Maybe that shouldn't be done in game, just in editor ?

Thanks for reading

winged mortar
#

You wouldn't create a new scene