#archived-code-general

1 messages Β· Page 452 of 1

primal gale
#

why is hmm blocked

#

is it possible to use multilpe layers in an object?

#

im sure I can find a work around but im curious

vestal arch
#

because that's.. not how layers work?

#

if you have an object with 2 layers, A, B, where A should collide with C, and B should not collide with C, then that object hits an object on layer C, what should happen?

primal gale
#

can classes be extended in C#

#

actually couldnt you make that whole thing significantly easier by just using a bool? Like "canPickUp" could just be a bool that you could check on or off then do code based on that

vestal arch
#

"interactable" on the other hand could be used to define that its trigger should detect the player but not anything else

vestal arch
#

you could have the pick up function be another component (that the pick up script you mentioned checks for) or an extension to interactable, yeah

#

unity tends to lean towards composition

primal gale
#

aight cool

#

got into unity from learning java since I heard C# was virtually the same for the most part, its interesting to see what you can do

hoary yoke
#

Hey guys, so I got some code to fire a bullet. I've got a variable which indicates whether the player can move or not (in another script) which is a condition for shooting the bullet. This is the code but somehow it doesn't work... any suggestions?

boreal badger
#

Ive been trying to figure out how to check if 2 booleans are not equal in c# but I can't figure out a good way to do itπŸ˜”
This is the best way I've found

(((Convert.ToInt32(a == b) << 1) ^ 2) < 0) ^ (((Convert.ToInt32(a == b) << 1) ^ 2) > 0)
night storm
#

use debug.logs to see what the variables are

hoary yoke
#

yess thankss i fixed it

boreal badger
leaden ice
#

Whatever you have there is massively overcomplicating it

boreal badger
leaden ice
#

there's no way to tell such a joke from a normal question people ask in here Β―_(ツ)_/Β―

boreal badger
#

πŸ‘

dawn nebula
#

When should I use an abstract Monobehaviour class over an interface?

rigid island
rocky steppe
#

What is the ":" in C#

tardy dove
#

inherits? i think

somber nacelle
#

depends on the context

steady moat
steady moat
boreal badger
#

it depends on context

#

like you could do

class Dog : Animal {}

to make dog inherit from animal or you could do

string myVar = myBool ? "true" : "false";

which is the same as

string myVar;
if(myBool)
{
  myVar = "true";
}
else
{
  myVar == "false";
}
#

and more

analog summit
#

can anyone look at my tetris game and see any ways i could optimize it?

rocky steppe
#
using System;
namespace PlayerInfo { 
public class Program
{
    // Define an enum for different player roles
    public enum PlayerRole
    {
        Warrior,
        Gunner,
        Archer,
        Healer
    }

    public string PlayerName { get; set; }

    public static void Main(string[] args)
    {

        PlayerName player = new PlayerName();
        player.PlayerName = "Inferno";
        // Assign a role to the player
        PlayerRole role = PlayerRole.Warrior;

        // Print role to the console
        Console.WriteLine($"You have selected the role: {role}");

        // Use enum in a switch statement
        switch (role)
        {
            case PlayerRole.Warrior:
                Console.WriteLine("Strong and brave! You deal high melee damage.");
                break;
            case PlayerRole.Gunner:
                Console.WriteLine("You are have control over all the weaponary in the world!");
                break;
            case PlayerRole.Archer:
                Console.WriteLine("Swift and accurate! You excel at ranged attacks.");
                break;
            case PlayerRole.Healer:
                Console.WriteLine("Supportive and vital! You heal your teammates.");
                break;
            }
        }
    }
}

somber nacelle
#

this is a unity server

rocky steppe
#

Can someone aid me in the object instantiation, I came from Java.

#

I'm trying to fix out the error.

somber nacelle
#

if you need help with c# outside of a unity context then perhaps ask for help in the !cs discord

tawny elkBOT
rocky steppe
#

PlayerRole role = PlayerRole.Warrior;

naive swallow
rocky steppe
#

Well, just C#, thanks for guiding me in the right direction.

ocean hollow
#
static void PlayGameF1()
{
    PlayGame();
}

[MenuItem("Edit/Run _F2")]
static void PlayGameF2()
{
    PlayGame();
}

[MenuItem("Edit/Run _F3")]
static void PlayGameF3()
{
    PlayGame();
}

static void PlayGame()
{
    if (!Application.isPlaying)
    {
        EditorSceneManager.SaveScene(SceneManager.GetActiveScene(), "", false);
    }
    EditorApplication.ExecuteMenuItem("Edit/Play");
}```

is there a better/cleaner way of doing this?
rocky steppe
#

Is that recursion?

ocean hollow
#

no?

leaden ice
ocean hollow
#

not having to separate keybinds across unique functions to do the same thing

leaden ice
#

Why do you need 3 functions that do the same thing?

ocean hollow
#

i want f1, f2, and f3 to all do the same thing, but i cant attach a MenuItem attribute to a single function that controls the logic for all 3 keybinds

#

so i was asking if there were alternatives

leaden ice
#

probably not Β―_(ツ)_/Β―

abstract chasm
#

hi, im running into a problem trying to access variables in one script from another.

//script A, not attached to any game object, contains many stats
using UnityEngine;
public class Stats
{
  public readonly int baseHealth = 100;

  public int Health;
}
//script B, attached to the player, should access the baseStats, apply modifiers, and update the stats to use them.
using UnityEngine;
public class DoStuffWithStats : MonoBehaviourGizmos
{
  public Stats stats;

  void Start()
  {
   Debug.Log(stats.baseHealth);
   stats.Health = stats.baseHealth * //player object children with a certain component//
  }
}

it doesnt work, saying an object reference is required and i kinda ran into a wall here

leaden ice
#

I see you have a public Stats stats variable in script B but I don't see you initializing that variable anywhere.

#

So my expectation would be a NullReferenceException the first time you attempt to access one of its members in the Debug.Log(stats.baseHealth); line

#

but if this is pseudocode - you should share the exact actual full error message and the actual script code instead,.

leaden ice
#

stats is your actual variable

#

you would do stats.bIntegrity

abstract chasm
#

yeah, thank you lmao

#

i seem to have overlooked that

leaden ice
#

you will definitely get that NRE issue here as well, unless Stats is serialized in the inspector.

abstract chasm
#

yeah you're right, how would i go about fixing that

leaden ice
abstract chasm
#

im used to just chucking everything needed into one script but the stats need to be accessed by a few different scripts so im new to connecting scripts together

#

yeah adding stats = new Stats(); in start fixed the nre CatDance

#

so i can just do stats.Health = //whatever// in another script, and reading stats.Health from yet another script down the line would return the new value, yes?

leaden ice
abstract chasm
rigid island
#
public class ScriptA : MonoBehaviour
{
    public Stats Stats;
}
public class ScriptB : MonoBehaviour
{
    public ScriptA scriptA;
    private Stats stats;
    void Awake()
    {
        stats = scriptA.Stats; //changing stats from here would affect stats in scriptA
        stats.MyInt = 99;
    }
}```
abstract chasm
#

oh i see.
so i make a script with an instance of Stats, and then have all other scripts that want to use the same stats, reference thatScript.stats instead of Stats.stats

rigid island
#

you are just referencing the same object Stats

#

though if these are meant to be shared stats you could also use a ScriptableObject you can plug into a field for all items that need it

abstract chasm
#

so uh my idea was

//one script to make an instance of Stats
public class StatAccess : MonoBehaviour
{
    public Stats stats;
}


//script a changes a stat
public class ScriptA : MonoBehaviour
{
    public StatAccess access;
    private Stats stats;

    void Start(){
      stats = StatAccess.Stats;
      stats.Integrity = 999;
    }
}


//script B reads changed stat as 99?
public class ScriptB : MonoBehaviour
{
    public StatAccess access;
    private Stats stats;

    void Start(){
      stats = StatAccess.Stats;
      Debug.Log(stats.Integrity);
    }
}
rigid island
#

but yes both would have the same 999 value

abstract chasm
#

i wouldnt change or read the stats in start, that was just for the psuedocode here to be more compact

rigid island
#

btw this is also is specific to Reference types, if it were a Value type ie a struct instead of class then you would only creating a copy and changing the item on scriptA referencing stats from StatsAcess would no affect the one on StatsAcess

abstract chasm
#

i see, thank you for your help, i think i understand the instancing of classes somewhat now

rigid island
#

you would have to assign the new value to stats back to StatsAccess (for struct / value type)

rigid island
#

it would be access.stats

#

access is the variable name you want access the instance of Stats from

abstract chasm
#

StatAccess is the class tho

rigid island
#

yes thats just the type you want to use, not the instance itself

abstract chasm
#

so wouldnt the things i wanna change be StatAccess.Stats.Integrity basically

#

oh nvm i see

rigid island
#

no you're confusing Declared type and instance of that type

abstract chasm
#

yeah i got it xd

rigid island
#

classes are just blueprints

#

unless an item is marked Static it belongs to a specific instance of that object/class

abstract chasm
#

yeah was an error writing the pseudocode, i see it now

rigid island
#

if you had public static Stats stats;
then you could access it with StatsAccess.stats.Integrity

#

cause it belongs to the class instelf

#

this is why normally static is used for a singleton pattern which you might also benefit learning tbh

lean sail
abstract chasm
#

i think i'll have a look at scriptable objects, they seem like a good choice for these shared stats

lean sail
#

Actually it can be fine to just access the stats in start, but there should ideally be 1 central class which sets up the stats based on your scriptable object

#

Setting up the values should happen in awake

round violet
#

can i make "instanced" classe instances in the inspector work with derived classes?

#

for example public MyBaseClass myClass;
how could i selected MyDerivedClass1 or MyDerivedClass2 in the inspector ?

last quarry
#

If you drag them in it should just work

round violet
#

this works with instances

#

im talking about creating new one, using SerializeReference, which seems not supported by default

#

i found a free plugin that does

#

your seems better that the one i have pulni

little meadow
#

98% of the time it just works. But there are weirdnesses every now and then that I'm usually trying to resolve as I encounter them.

round violet
#

when im nesting stuff, should use [SerializeReference, TypePicker] on the variable that holds the abstract base class ?

little meadow
#

yes

#

mm... if you have a nested abstract thing it would also need the [SerializeReference, TypePicker] on that field/property of course

round violet
#

i was using a serializeddict and then had a list of that base class inside

round violet
#

how does nested coroutine works ?

if i call StartCoroutine(FirstCoro()), and FirstCoro calls NestedCoro(), how would any yield return placed in NestedCoro behave ?

#

i assume it would work like it was inside FirstCoro if NestedCoro returns a IEnumerator

#

or am i forced to do yield return NestedCoro() in FirstCoro

steady bobcat
#

Would behave as normal. If the first coroutine yields the execution of the second then that affects the first only.

round violet
#

and if i call StartCoroutine inside a running Coroutine function, i assume it will be independant ?

paper lotus
#

Hi just a quick question, how can I access the Transparency Sort Axis in the settings? I'm using URP and I'm trying to make a 2.5D game. I can't seem to find it in the graphics settings. I tried looking it up but unresolved

steady bobcat
thorn crane
#

how to fix that

somber nacelle
#

you likely have a duplicate script

thorn crane
#

how to fix

somber nacelle
#

read the error message to find out

steady bobcat
#

Amazing how many people make this mistake and don't read πŸ€”

#

I guess people follow older tutorials using old input on unity 6?

thorn crane
#

How to fix

somber nacelle
#

each one of your errors is #πŸ’»β”ƒcode-beginner level at best. and you should perhaps maybe do any amount of research instead of just dropping a screenshot here like "hOw FIx" every single time you see an error

naive swallow
primal gale
#

havin a brain fart rn, how can I structure this so my player gun knockback & dash will work normally? Right now theyre being affected by my rb velocity still

It worked earlier when I only had one thing to check but now since I got two only one can work

#

oh wait

vestal arch
primal gale
#

already tried that

vestal arch
#

oh wait that's not what the code says

#

the first one should be right

#

the one that's commented out

primal gale
#

hol up

#

brah

#

that wa sliterally the first thing I did

#

im trolling myself

wintry gust
#

Quick question, is it possible to add white to a TextMeshPro text rather than multiply? By default, multiplying white just gives me the same color I started with. But I'd like to add a glow effect to my text so I need to add white to it (Not the border glow option that the default shader gives)

primal gale
wintry gust
#

Ahh, interesting. I'll try that

#

Hmm, I don't see any changes when raising the intensity past 1

steady bobcat
#

You need to describe what you want better

wintry gust
# steady bobcat You need to describe what you want better

I have text that is like this. It's a bitmap font type. I still need to be able to multiply it for different colors, but I also want it to glow a white. Since TMP multiplies color, if you use white, it just gives the same base result. I can try to do a mockup if I'm still explaining it poorly.

still seal
#

does anyone know stuff about like final IK and VR perchance?

#

trying to make a boneworks/lab type game

#

problem is tho

#

the xr rig does fall through floor and come back which is what i want BUT

#

the characters parts trying to target the controllers and stuff dont fall alongside the xr rig

#

also maybe even the jumping

#

when i jump, it doesnt move with the xr rig

wintry gust
#

@steady bobcat I'm looking to do an effect like this

#

Spoiler tag so flashing doesn't bother people lol

naive swallow
#

You could instead make the text's normal color at the brightest it gets, and then turn the color multiplier down for the normal state

#

Otherwise you'll need a shader that supports HDR colors since the default one can't go above 1 intensity

wintry gust
#

That does make sense

#

But hmm, wouldn't that kind of fudge up the contrast?

#

Oh actually, I can just use a mask

ocean hollow
#

my editor script was working perfectly as intended yesterday, but after reopening my project today, im told that it's not possible to do what i already did? even though it was working perfectly before a restart?

static void PlayGameF1()
{
    PlayGame();
}

[MenuItem("Edit/Run _F2")]
static void PlayGameF2()
{
    PlayGame();
}

[MenuItem("Edit/Run _F3")]
static void PlayGameF3()
{
    PlayGame();
}

static void PlayGame()
{
    if (!Application.isPlaying)
    {
        EditorSceneManager.SaveScene(SceneManager.GetActiveScene(), "", false);
    }
    EditorApplication.ExecuteMenuItem("Edit/Play");
}```
#

so i changed my code to the following but i'm still getting the same warnings about f2 and f3???

ocean hollow
dusk apex
ocean hollow
#

i checked for duplicates and this is the only one. i even tried deleting and remaking the script under a different name and i still get the same warnings. i also tried restarting but i still get the same warnings after every restart and domain reload

ocean hollow
dusk apex
#

You've simply changed the hotkey but the menu item names are the same

ocean hollow
#

im not sure what you mean

dusk apex
#

Try "Edit/Run1 _F4"

ocean hollow
#

ah, that fixed it, but why was my script working properly yesterday despite this?

dusk apex
#

Not sure, it shouldn't have with the above lines of code as you've got two functions wanting to be the same menu item but simply with different hot keys

ocean hollow
#

just went back to check to see if everything was the same when i asked a different question regarding the same script yesterday, and everything was the same... #archived-code-general message

#

im truly at a loss

dusk apex
#

It's only a warning, not an error

ocean hollow
#

also, the warnings do stop my f2 and f3 keys from working as intended

#

only f1 was working properly when the warnings started showing up

ocean hollow
dusk apex
#

I'm not sure, just stating that it's simply a very reasonable warning (duplicate name etc)
Why it wasn't visible yesterday or why it's producing an undefined behavior could be due to anything. You'd need to show us what Play Game is actually doing.

dusk apex
hoary yoke
#

Hey guys, I've got two scripts: one for player health and another for movement. Now the movement script should disable movement once the player is dead (which is determined in the other script) but it won't work! Any suggestions?

dusk apex
#

Verifying if:

  • they're referring to the same player
  • health is the expected value
steady bobcat
#

inb4 alive is not the static var they are checking elsewhere

naive swallow
tawny elkBOT
lyric barn
#

Does anyone have tips on how to use NavMesh for 2D alongside rigidbody operations? Like implementing enemy navigation and dashing into the player.

rigid island
lyric barn
rigid island
#

what is supposed to mean

lyric barn
# rigid island what is supposed to mean

I tweaked my code, now the enemy behaves mostly fine, but when chasing a moving player the enemy dashes and bumps into air, so they can't quite catch up to the player (this is without the kinematic rigidbody method)

rigid island
lyric barn
sick hawk
#

curious on the differences between return and yield return in this instance:

public IEnumerator WalkCoroutine1()
{
    while (true)
    {
        yield return StepCoroutine(controller);
    }
}

public IEnumerator WalkCoroutine2()
{
    while (true)
    {
        return StepCoroutine(controller);
    }
}
            
public IEnumerator StepCoroutine()
{
    yield return new WaitForSeconds(stepDelay);
    Step();
}
#

the one difference im sure of is that return will end the coroutine? and it seems like you can't have yield return as well as return?

naive swallow
#

WalkCoroutine1 will repeatedly run StepCoroutine(controller) over and over again forever

#

A coroutine yield returning another coroutine will wait for that coroutine to finish

sick hawk
#

my guess is top returns an ienumerator iteratating over each value returned by yield return, while bottom returns whatever Ienumerator StepCoroutine has

naive swallow
#

A normal return effectively replaces this coroutine with the new one

sick hawk
#

ok ok

leaden ice
#

The while loop in the return one is pointless

sick hawk
#

yeah I know I was just trying to set up a generic example

leaden ice
#

Yeah but it's key to understanding the difference

sick hawk
#

yes

leaden ice
#

return exits the function

#

Yield return is a "pause here and come back"

sick hawk
#
public static IEnumerator ShootFanEnum<T>(T prefab,Vector3 position,Vector2 direction,int projectiles,float angle,Transform anchor) where T : Projectile {
        for (int i = 0; i < projectiles; i++)
        {
            float currentAngle = 0;
            if(projectiles != 1) {
                currentAngle = i*(angle/(projectiles-1)) - (angle/2);
            }
            var shootPosition = position;
            if (anchor)
            {
                shootPosition += anchor.position;
            }
            yield return ObjectPooler.main.Shoot(prefab, shootPosition, Quaternion.Euler(0, 0, currentAngle) * direction);
        }
    }
    
    public static IEnumerator ShootFanEnum<T>(T prefab,Vector3 position,Vector2 direction,int projectiles,float angle) where T : Projectile {
        return ShootFanEnum(prefab, position, direction, projectiles, angle, null);
    }

    public static void ShootFan(Projectile prefab, Vector3 position, Vector2 direction, int projectiles, float angle)
    {
        var shootFan = ShootFanEnum(prefab, position, direction, projectiles, angle);
        while (shootFan.MoveNext())
        {

        }
    }

ok this was the reason this came up

leaden ice
#

The regular return is just delegating to another coroutine entirely

sick hawk
#

I wanted to have a function that can shoot in fan, but also can be used by a coroutine to delay one shot after another

leaden ice
#

Just make a coroutine with branches

#

(if statements)

#

You can put your yields in conditionals

sick hawk
#

I originally had the second overload just have yield return ShootFanEnum(...) but that never ran the original overloaded function

#

if I ran it from the bottom non-enumerator function

#

so I changed it to return and it worked

leaden ice
#

You have to use StartCoroutine to run a coroutine

sick hawk
#

yield return StartCoroutine?

leaden ice
#

Only if you're trying to make one coroutine pause and wait for another

sick hawk
#

lets say I want that

leaden ice
#

Then yes that will work

sick hawk
#

ok I guess my confusion lies in how yield return works

leaden ice
#

Or just yield return the other coroutine

sick hawk
#

where does it go

#

is it returned by movenext?

naive swallow
#

If that condition is WaitForSeconds, it'll wait until that amount of time has passed

#

if that condition is a StartCoroutine, it'll wait until that coroutine finishes

leaden ice
#

Depending on what you yield return it will come back to that coroutine at a certain time

#

But you should not be iterating it manually

sick hawk
#

what are the functions you use to wait? Like what are you even returning? I always assumed WaitForSeconds() was itself an Ienumerator but I guess that doesn't make sense

sick hawk
leaden ice
sick hawk
#

YieldInstruction it seems

leaden ice
#

Yes

sick hawk
#

is the waiting not even inside WaitForSeconds it just checks the type you return

#

and does predefined things

leaden ice
#

The waiting is in the engine itself

#

The source code for which is closed

sick hawk
#

I guess we dont know then

#

you can make custom yield instructions it seems

leaden ice
#

Suffice to say it just checks once per frame until the amount of time has elapsed

sick hawk
#

which is interesting

#

you could probably do 99% of the same thing with a coroutine

#

anyway thank you for your ienumerator and coroutine insight

#

they are a very weird thing that you learn as a beginner and just go "huh thats odd" but just kind of compartmentalize the knowledge without understanding how/why they work

cosmic rain
#

As for nesting coroutines, I'd avoid doing that precisely because we don't know how it works under the hood.

#

Use async if you need complex asynchronous logic.

sick hawk
#

I think understanding IEnumerator functions is like 80% of the understanding, its just a more advanced topic

#

most of the weirdness is from that

#

i remember wondering what the hell yield return was but never looked much into it

steady bobcat
#

Its meant for IEnumerable collection itteration

sick hawk
#

i think for a while I thought it was a unity specific thing

#

but that didn't rly make sense

#

since it was a special keyword

#

just the reality of being a beginner using a very complex system most advanced users don't even understand completely

steady bobcat
#

If you understand async it helps but async took too long to work nicely in unity (UniTask is still better πŸ˜† )

cosmic rain
#

Programming is dealing with abstractions

sick hawk
#

pretty much nobody is going to understand from the ground up how ever single layer of every single program works

#

except for very specific instances

#

also nesting coroutines seems fine actually, my code wasn't actually using one in the nesting bit. I was manually iterating another IEnumerator manually inside a coroutine, and the nested IEnumerator didn't work

steady bobcat
#

you can yield the execution of another just fine if started correctly otherwise yea the unity magic is not gonna work

sick hawk
#

I think because it was returning the IEnumerator to .MoveNext() instead of nesting them

#

im still kinda confused why yield returning an IEnumerator does not just start iterating over that? It seems like it should looking at examples

#

no maybe not

steady bobcat
#

the returned result is used to tell when to next execute the IEnumerable so you just confuse it

#

you return something from another coroutine which is gonna fuck what you want it to do

sick hawk
#

there is one example that says doing yield return OtherCoroutine() works to nest them but thats probably just unity doing that

#

I think thats where my confusion came from

steady bobcat
sick hawk
#

thats my guess

steady bobcat
#

you can do yield return StartCoroutine(Foo()) to make it actually work

#

anything else wont because again this is just lucky abuse of yield

sick hawk
#

I do remember trying this and it working as well

#

is it documented anywhere why this is "wrong" and the other way is "right"?

steady bobcat
sick hawk
#
// Start function WaitAndPrint as a coroutine. And wait until it is completed.
// the same as yield return WaitAndPrint(2.0f);
yield return StartCoroutine(WaitAndPrint(2.0f));
print("Done " + Time.time);
#

seems like both are valid

#

in fact, are equivalent

sweet raft
#

Anybody ever ran into an issue where when trying to build you get errors saying that "type or namespace doesn't contain a definition for"...but it actually DOES contain it?

leaden ice
#

Or, sometimes you just have a plain old compile error

sweet raft
#

Don't know if you can help me from these screenshots.

#

If it helps...everytime the Build process fails, the scene that I have opens gets marked as if there are changes in it that need to be saved...even though I haven't touched it.

cosmic rain
leaden ice
sweet raft
#

Prime example of the risks you take when working late.

lyric veldt
#

guys is this a good way to implement a zoom feature

hybrid wagon
mild goblet
#

Hey friends. Has anyone got crashes on Editor open? I'm not exactly sure what to do with the 'attached files' in the bug report, namely the dmp file. I sent it off anyway. I'm struggling to understand the crash log.

round violet
#

Im using multiple NativeArrays for the OverlapSphere command, and using Allocator.Temp to init these.
Since the size of the array is different each frame, im calling this at each new fixed frame, so im wondering if there is a more optimal way to allocate the memory needed

#

Also for stuff as these physics commands that are executed as a job, im currently doing:

  • Fixed Update 1
    • allocate arrays, fill with commands, wait for complete, read and dispose
  • Fixed Update 1+?
    • ...
  • ...

I saw some people waiting for completion and reading the results on the next frame, is there any reason ?

buoyant oyster
#

Does anyone know if Unity supports Microsoft.Toolkit.HighPerformance in newer versions? I think they brought in Span etc so I assume it works, but I cant find anything specific around this, I mainly want to use Span2D

thin aurora
#

If the feature works and it's overly complex I'd say it's generally good

#

If you want to know if it's the best approach, that's a different question

river hamlet
#

why can't i use IPointerClickHandler to detect click on a nonUI-gameobject

#

added physics2draycaster on the camera but still doesnt work

thick terrace
#

do your objects have colliders on them?

river hamlet
young yacht
#

blocksraycast to false

river hamlet
#

its solved. but i have no idea why having rigidbody make the collider not detect mouse input

#

oooh i turned off simulated. thought it just turn off the physic

sudden ruin
#

h im wondering why i shouldnt store json save data into playerPref but into a seperate text file

cosmic rain
sudden ruin
#

would it be the same as storing other preferences ?

oblique spoke
#

PlayerPref API is also quite limited and awkward in more complex saving setups.

cosmic rain
sudden ruin
#

i just had a senior say he been doing it all along in a interview, so trying to figure this out

#

is there a scenario where the file works but the playerpref doesnt

cosmic rain
#

I'd imagine there's a size limit to the registry entries, so you won't be able to save strings if they are too long.

sudden ruin
#

max size 1mb, indeed

cosmic rain
#

But just avoid it as a good practice. If you overdo playerprefs, it's not much different from being a malware

sudden ruin
#

ah no

steady bobcat
#

Im going to presume services like steam cloud saves do not work with registry values so that should be a good reason to never use it

last quarry
#

You can also do versioning and backups if you save JSON files

#

Highly recommend putting a version in there from your first iteration

steady bobcat
#

Yes i always have a version in saves i handle, very useful later to perform automatic upgrading

dusky niche
#

does using yield return break; execute any remaining code in the coroutine?

leaden ice
#

yield break; exits the method immediately

dusky niche
#

but does it execute any remaining code in the coroutine?

leaden ice
#

No, that's what I mean by exiting immediately

dusky niche
#

I see thanks

dusky niche
#

if breaking doesn't make the variable which is holding the coroutine to null, then would this work?

    if(!isGrounded)
       {
         yield break;
         reduceSpeed = null;
       }
leaden ice
#

yield break exits immediately

#

We just established that.

#

You need to do it the other way around

dusky niche
#

other way?

leaden ice
#

Assign it to null first

#

Then yield break

dusky niche
#

if i assign it to null first wouldn't it cause an error bcuz the variable just removed the coroutine?
well ig I can try first & see

mellow sigil
#

The coroutine doesn't need to be stored in a variable for it to run. The variable has nothing to do with it

dusky niche
#

I see

leaden ice
dusky niche
#

I understand

round violet
#

how often does the inspector redraw its content ?

#

when showing the content of a scriptable object, im loosing around 80fps

night harness
#

how are you doing it

round violet
#

im using two plugins, one to serialize and edit dictionnaries, another one for a subclass picker

#

the combo of both ruins the perf

night harness
#

one of those might be doing something goofy

round violet
#

i only have a few entries lol

#

yeah, a single empty entry in the dict is enough to nuke the editor perf

night harness
#

yeee

round violet
#
public SerializedDictionary<int, LevelDataEventEntry> events;

[Serializable]
    public class LevelDataEventEntry
    {
        [SerializeReference, TypePicker] 
        public List<LevelGenerationEventBase> eventList;
    }
leaden ice
#

What's this "TypePicker" thing?

round violet
little meadow
#

(Busy atm, will ping you in a bit)

round violet
#

well nvm, sorry for the ping, a standalone [SerializeReference, TypePicker] public List<LevelGenerationEventBase> eventList; doesnt lag

#

the nesting in SerializedDictionary does

night harness
#

(doesn't mean its not the typerpickers fault, just depends)

round violet
night harness
#

this does not change what i said

round violet
#

what would cause a lag inside TypePicker

#

only when nested in a dict

#

a list of LevelDataEventEntry doesnt lag either

#

lag only appears in SerializedDictionary<int, LevelDataEventEntry>

night harness
#

i understand why your making this conclusion

#

but without knowing what specifically is causing the problem you can't say for sure

#

eg. the typepicker might be doing something ideal that's only problematic when the code is pushed by the dict stuff

#

not saying thats the case but can't know until someone looks into it

round violet
night harness
#

ok

round violet
#

but i have to admit that the initial plugin i was using has a better inspector

eager tundra
#

or you can always open up the wallet and pay for Odin

night harness
#

Though odin dicts get abit weird with prefabs no?

eager tundra
#

no idea, never used much of the editor serialization part

tender ice
#

does anyone know how to make a script that uploads images onto game objects? I have this tv I made by stretching 2 cubes through scales (one is a parent that is selectable, hence its green, and one is the plasma child)
I have multiple sizes (this one is 86 inches) and they all share the same materials for the plasma and the borders, any tips on how to make it work, if its even possible

thick terrace
tender ice
thick terrace
#

well, what images?

#

drag a texture into the texture slot on the material or something more than that?

tender ice
#

FHD images

thick terrace
#

material.mainTexture = myTexture?

tender ice
#

and I want a feature that when I upload my image (in context it'd be like a ad) when I have a TV selected (highlighted in green) it'll output the image in the plasma

gleaming falcon
#

Hello

tender ice
#

where would those images/gifs go? into a cache folder that would get deleted after leaving the application

#

im not really aiminig for videos but it could also be an option

tender ice
thick terrace
gleaming falcon
#

Sorry for bothering you, but could you please tell me what type of device you haveβ€”desktop or laptopβ€”and what model it is?

tender ice
#

unless you're not talking to me but yeah 😭

thick terrace
steady bobcat
tender ice
#

it opens my files, lets me browse and asks for only pngs and jpgs and once I select them, it just yields my debug log that I setup in case its sucessful, but nothing really happens

thick terrace
#

can you share your code then?

lean sail
tawny elkBOT
gleaming falcon
#

Just questions

gleaming falcon
lean sail
safe flame
tender ice
tender ice
#

like i said, since i didnt have much of a clue on this i kinda did rely on chatgpt for this one

gleaming falcon
#

When I take the mesh and want to combine it with a floor piece but it doesn’t work, what’s the reason?

#

You mean the floor piece is distorted, do you understand what I mean?

lean sail
thick terrace
gleaming falcon
#

Do you use Unity in developing your games?

tender ice
#

its a complete mess at this point but i can send you it if you want ig

gleaming falcon
#

I think I'm stupid for coming here.

tender ice
gleaming falcon
#

πŸ‘βœŒοΈ

tender ice
#

and ""simple""

lean sail
last quarry
tender ice
tender ice
last quarry
#

Torque3D of course

tender ice
#

who tf am i decieving ofc i want lmao

thick terrace
tender ice
#

I could just clone them anyway and have them essencially look the same

thick terrace
#

you're having it make a new material each time this gets called so that shouldn't really matter

gleaming falcon
#

I was searching in ChatGPT for a Unity game developers group, and it gave me a link that brought me here.

Hahaha

thick terrace
#

chatGPT rots the brain y'all πŸ˜‰

tender ice
#

so im just going to learn it like a normal person, with chatgpt around, ppl who actually know how to code will be way more valorized

lean sail
#

do you even need to create a new material there? accessing renderer.material should create a new one for you

tender ice
#

and thats why it maybe doesnt show up at all

gleaming falcon
thick terrace
#

you're assigning that material back to the renderer so it should be using it

#

if you want to keep track of it more easily, make your code rename the new material after creating it so you can be sure it's the new one

atomic whale
#

is it possible to make any variable readonly just for the inspector?

lean sail
tender ice
#

the way I handle my TVs is a bit finicky, so I dont really spawn them, I clone a existing prefab on the scene, maybe that has something to do with it? I did just check the original prefabs and they are fine (no pic tho), but I don't think it should be any different if it wasnt cloning so yeah

restive heron
#

I've been coding for a while, but since I just learned by watching tutorials and finding out what was what along the way and then finding out what they are needed for, I have a very big lack of knowledge in a lot of areas in C# because of that I have trouble trying to code more complex stuff by myself, Idk what to do to get more knowledge in C# without having to buy a course, but I don't have any money because I'm a teen/:

thick terrace
#

for example, does the material used have a texture property that can be set by mainTexture

tender ice
thick terrace
#

what are you expecting it to do then?

#

if you don't have a texture slot on your material it won't grow one lol

tender ice
#

thats fair, well back then I didn't design them around having an image and thought a plasma texture would be pretty pointless

tender ice
#

except that now I do have a course

lean sail
rain sonnet
#

I really don't understand the point of serializing datatypes that "otherwise can't be serialized" using this method: https://docs.unity3d.com/6000.1/Documentation/ScriptReference/ISerializationCallbackReceiver.html
I mean isn't the code example not just looping through two serialized lists and then it adds it to a non serializable dictionary and that way you have the benefit of adding values to variables in the inspector? Why not just loop through the serialized lists in the OnStart() method and add it to a dictionary?

thick terrace
rain sonnet
#

hmm, i dont think i understand

thick terrace
#

if you wanted to store 10 dictionaries, would you want to write 20 list fields and 10 loops in start, or just 10 serialized dictionary fields?

lean sail
lyric veldt
#

What is the best approach of making a zoom feature

midnight hollow
#

i want to create a roguelike game, i already hav a boss and when i kill him, a canvas appears with 3 randomly chosen cards(it has 8), the cards its an ui buttons. in-game, it works all except the cards buttons, it doenst work at all, some advices? i alr put the OnClick() functions and all, i really dont know what to do...

mint zenith
#

Hello, im having an issue where:

when i click my cursor disappears (not clicking the button) and i have to click esc to bring the cursor back otherwise it just dont exist

#

and yes i have connected my click function

#

to the button

naive swallow
#

You should be able to check the bottom part of the inspector on your event system to see what object is hovered. There might be something invisible blocking the button from being clicked on

#

Since the button doesn't seem to be responding to hover either

mint zenith
#

how do i check that?

#

im kinda new sry

naive swallow
#

Select the Event System while playing. It'll be the same place that preview is in your current inspector

#

It should show what object it's hovering over

mint zenith
#

the event system?

#

where is that

naive swallow
#

The object named Event System

mint zenith
#

i dont see mine

#

i think i gotta make one one sec

#

maybe thats why

#

well i added one in the canvas but idk how to use it now

#

or does it automatically apply itself

naive swallow
#

It shouldn't be on the canvas, it just needs to exist as an object in the scene

#

It gets created when you first create any UI object

mint zenith
#

ye i created one

#

idk why there wasnt one earlier

#

idk

#

its still happening

#

no hover reaction either

simple saffron
#

Having an issue with some code, but in a really odd way.

        capsule.enabled = true;
        Debug.Log($"enabled capsule - {capsule.enabled}");

        ToggleRenderers(true);
        Debug.Log("enabled renderers");

        ToggleHitboxes(true);
        Debug.Log("enabled hitboxes");

This code is being executed, since I'm seeing the messages in the consoles, but the code inside those other methods isn't being executed in the way I want it to

#

And the code inside ToggleRenderers

    public void ToggleRenderers(bool enabled)
    {
        for (int i = 0; i < allRenderers.Length; i++)
        {
            allRenderers[i].enabled = enabled;
        }
    }
round crow
#

i have the fastscriptreload plugin so i dont need to wait for the compile each time, its not updating public floats tho

#

Can i manually update float maybe?

lean sail
simple saffron
#

its not re-enabling the renderers

naive swallow
simple saffron
#

allRenderers has 4 entries on each of the characters present in my game, each of them referencing one part of the character's body
I'm in the process of doing that bit, digi

naive swallow
#

That does not mean they are the renderers you expect them to be, and it does not mean they stay enabled

simple saffron
#

I've got a log in the following places

  • player dies
    • colliders disabled
    • hitboxes disabled
  • player revived
    • colliders enabled
    • hitboxes enabled

They're all executing in the correct place. I'm certain that they're not being modified in any other place

lean sail
#

your logs right now are hardcoded strings, they don't actually tell you anything. i feel like you skipped over the important part of what i wrote
"Maybe your list doesn't have all the elements you think it does, or maybe something else is disabling it"

naive swallow
#

So, each iteration of the loop is giving you a log? If so, then whatever is in that list is definitely getting enabled

steady bobcat
#

Did someone mention a debugger yet?

simple saffron
#

not yet, im about to do that bit

    public void ToggleRenderers(bool enabled)
    {

        Debug.Log($"toggling renderers - {enabled}");
        for (int i = 0; i < allRenderers.Length; i++)
        {
            allRenderers[i].enabled = enabled;
            Debug.Log($"toggled hitboxes - {allRenderers[i].enabled}");
        }
    }
    public void ToggleHitboxes(bool enabled)
    {
        for (int i = 0; i < playerHitboxes.Length; i++)
        {
            playerHitboxes[i].enabled = enabled;
            Debug.Log($"toggled hitboxes - {playerHitboxes[i].enabled}");
        }
    }

this is what they look like right now, just about to test this

steady bobcat
#

I don't mean logs but using an ide debugger

simple saffron
#

might be silly maybe, but im unfamiliar with ide debugging in unity

naive swallow
#

A debugger would certainly help

lean sail
#

meh its hard to suggest it in every case. sometimes you want to just let the code run first and see if the logs line up with what you expect
if there are more values you want to see like the name of the object, length of list, etc then it makes sense to do

round crow
#

I have something spawn but its spawning every frame currently, i read u have to do time.deltaTime but it still does the same
how do i make it wait like a second or whatever

simple saffron
#

is this likely to add a lot of stuff into my workflow? I've got like, 2 days to finish this project and im stuck on the damn revives lol

lean sail
simple saffron
#

ah, alright, thank you

#

gonna try the log statements i posted above

lean sail
#

its a good tool to learn but truthfully id be adding logs here myself. because all you really need to see is how many elements are getting toggled, maybe the names, and that they are being enabled. With the debugger you would be "stepping through" every breakpoint and imo doesn't really make sense to need here. You dont need to pause to look at the list length or object name everytime

#

the main thing we're trying to tell you here is that if the code is running, everything in those lists are getting enabled. Those lists might have the wrong (or no) objects for all you know.

simple saffron
#

The arrays are definitely assigned correctly as well. I can inspect them in the editor, and they point to the correct things
ok yeah, the logs are saying they're disabled when i pass false, and im directly reading the collider.enabled value

#

the annoying thing is, all of this was working as expected earlier/yesterday
I've made some changes to an unrelated script and now its uh... now its not

steady bobcat
simple saffron
#

Do spherecast jobs hit disabled colliders?

#

OH

#

no im stupid oh my god, im disabling the hitbox component, not the associated collider...

#

ok so that solves the hitboxes not behaving as expected

lean sail
simple saffron
#

But it doesn't solve the renderers not being re-enabled all the time

#

oh.
this thing has to be against me. Renderers are now being re-enabled correctly

#

hitboxes should be fixed, added a reference to the collider they're attached to

lean sail
lean sail
simple saffron
#

Perhaps. Either way, it seems like its working right now?

#

I shall re-evaluate if something is not working later on, but i want to move on from this for now

steady bobcat
#

Tbh I didn't read their code closely I just think it's wise to use a debugger when helpful

round crow
#

my unity keeps refreshing after the first second

leaden ice
#

Opening the project?
Running your game?

round crow
leaden ice
#

Not sure what that means, doesn't sound like an answer to what I asked.

chrome trail
#

I'm not sure if it would technically be considered a singleton, but is there a way to write a constructor so that it can be instantiated with parameters and everything, but any attempt to instantiate it after that first attempt results in absolutely nothing? My first thought is that it would look something like this

{
    public static Actor1 instance = null;

    public string name { get; private set; }

    public Actor1(string inName)
    {
        if (instance != null)
        {
            name = inName;
        }
        else { return; }
    }
}```

But I'm worried that writing it this way DOES still technically instantiate a second object but with no information. Am I correct in this assumption and how would I go about making sure the second instance straight up can't be created ever?
naive swallow
leaden ice
chrome trail
leaden ice
#

What you can do is make the constructor private, and expose a static function to create/get the single instance instead.

chrome trail
chrome trail
leaden ice
#

Why wouldn't you be able to pass parameters in?

#

I mean it's weird/confusing that you would want to, but I'm not sure what you're worried about

naive swallow
#

How about instead of using a constructor, you use a static variable that calls a constructor if the instance doesn't exist

leaden ice
#

In fact the name Actor1 for a class is a red flag in and of itself

vestal arch
leaden ice
#

WHy is it numbered?

#

The numbered class name implies the existence of an Actor2 and Actor3. And the differences between those classes should almost certainly just be data in different instances of a single class, not different classes.

#

These are OOP crimes you are committing

naive swallow
#

Also, if it's supposed to be a singleton, why are more things creating it? This probably shouldn't be that common of an occurrence

chrome trail
leaden ice
#

oh gosh

#

BinaryFormatter?

#

That's yet another red flag

chrome trail
#

I don't want to be importing in a mountain of numbers

chrome trail
leaden ice
#

By using BinaryFormatter you are putting anyone who plays your game at risk of their computer being taken over by malware.

chrome trail
leaden ice
#

literally any other serializer

chrome trail
#

I don't know any others

leaden ice
#

protobuf, messagepack, various json serializers, etc.

steady bobcat
#

bebop but not sure if that requires newer c#

mint zenith
#

guys, any idea why when i click my mouse disappears? (not letting me click ui buttons) i acn show a video too

steady bobcat
#

probably intended, using some other first/third person character?

mint zenith
#

im using

#

a first person

#

ye

#

i disable the player in the start

#

which has player cam and all the scripts

#

so how can that interfere

median trail
#

im using this in in FixedUpdate in a script on my main camera but the camera seems to lag behind a bit sometimes? is that an issue with my code or how ive got my scene setup?

            transform.position = cameraPos.position;
            transform.rotation = cameraPos.rotation;
#

ill attatc a video showing what i mean

steady bobcat
#

fixed update is not executed every frame so it will cause that

median trail
#

oh ok

mint zenith
#

just do it on

#

normal update

#

thats what i did for fp controller

median trail
#

for some reason i thought fixed update ran after update

#

like lateupdate

#

oops

#

okay ill try it in upate

mint zenith
#

it just wont let me

#

click

#

at all

#

my mouse disappears

median trail
#

can i move the rest of this codde to upddate too then??

    void FixedUpdate()
    {
        Transform cameraPos = camPositions[camPosIndicator];

        if (camPosIndicator == 0)
        {
            smoothTime = Mathf.Lerp(baseSmoothTime, 1f, Mathf.Clamp01((carScript.speed / 100) - 1));
            transform.position = cameraPos.position * (1 - smoothTime) + transform.position * smoothTime;
            transform.LookAt(lookTarget);
        }
        else
        {
            transform.position = cameraPos.position;
            transform.rotation = cameraPos.rotation;
        }
    }
#

first part is for a smooth car following camera

#

the smooth follow becomes very jittery in Update()

#

so ill juust keep that in fixed

mint zenith
#

hey so @steady bobcat i tried disabling and enabling the fps contrtoller script but that also didnt rlly do anything

steady bobcat
vestal arch
# median trail like lateupdate

LateUpdate runs after Update
though generally camera positions are updated in LateUpdate already, so... yeah there isn't anything that runs after that unless you use script execution order

median trail
#

yeah its fine i dont really need it to run later. i just misunderstood my own code lol

vestal arch
median trail
#

yup everythingg works as intended now, thanks for the help guys

#

so what is Lateupdate actually used for aside from camera tracking? i havent needed to use it yet for anything

vestal arch
#

anything that needs the updated state of stuff in the scene, i guess?

#

stuff related to camera stuff like background parallax

median trail
#

oh okay

mint zenith
#

the cursor.visible part on what u said doesnt make sense, bc when i click its like my cursor is centered, when i click esc it comes out the center no matter how much i move it around

steady bobcat
#

locked cursor state does this, hides it and locks it to the center

#

something is still changing this state

vestal arch
mint zenith
#

my bad

#

oh i found it

naive swallow
#

Okay, I have a fairly large problem and I have no idea how to fix it.

Situation: I have a runtime-loaded mesh that defines a "room". It's just the walls, no top or bottom caps. It's a mesh collider that just makes up the faces on the outside of it. I need to determine when the player is inside the room for a post-processing volume. As such, the room has a Trigger Collider, which necessitates a convex mesh collider.

Problem: The convex collider cuts across corners (as it's designed to do) and is therefore detecting the player as in the room when they're not actually inside it. I need to detect when the player is inside this closed, concave polygon.

Attempted solution: I got an addon that can decompose a mesh into convex shapes, the plan was to make a bunch of child objects of those decomposed meshes with trigger colliders, so this object's rigidbody could still detect them. But the mesh isn't actually filled in, it's just walls. So the decomposed polygons are just sections of wall, and don't contain the space inside the room.

How can I (procedurally! I can't just eyeball this I'm loading it in at runtime) detect when something is inside this polygon and not also detecting the corners

steady bobcat
naive swallow
#

But that's just kicking the can down one more road, if I could break down the internal space into triangles, I could just build a mesh out of those and be done with it

#

Any method of triangulation I could find produces a convex polygon

leaden ice
#

I e. Start with a "filled in" mesh

#

Not sure where the mesh comes from in the first place

naive swallow
#

I don't have a filled in mesh, and if I could triangulate the caps from the edge meshes I'd be golden on that front

leaden ice
#

You can probably programmatically fill in those holes

#

Blender can do that, why not you

naive swallow
#

So I just have the lines, but taller

leaden ice
#

If you can get the vertices in perimeter order, you can programmatically triangulate the ceiling and floor

#

If that makes sense

naive swallow
#

I'm not sure how. Everything I've tried to look up for how came up with triangulation algorithms that either failed to cover it all or made the mesh convex

leaden ice
#

(plugins exist for that too)

#

It's two phases basically, triangulate to get the ceiling and floor for the concave mesh

#

Then decompose into convex pieces

naive swallow
#

I don't know how to get the concave caps though. Delaunay Triangulation is giving me polygons that look like this:

#

If I could find a way to generate these, then that would be my problem solved but I don't know how

#

Everything online for filling in a polygon just says "Use delaunay triangulation" and that just doesn't work with this shape

#

If you have a plugin or even just an algorithm name I could make progress but I'm just stuck on this one

steady bobcat
#

If it doesn't require faces you should be able to filter and get the verts for the top or bottom only right?

naive swallow
#

I have them all. But how do I fill them in

#

I guess there's the brute force method of make a triangle between every single vertex and every other pair of vertices, but I am gonna have a whole lot of these and I'd prefer my graphics cards not on fire

#

And I'm pretty sure VHACD would just give up at that point

steady bobcat
naive swallow
#

I guess I'll give it a shot and see if this one can manage

hexed pecan
#

I had a similiar situation and I used the ear clipping algorithm to split the shape into triangles and made a collider out of each one

#

Can optionally combine the tris into convex shapes if possible

fierce tundra
#

I have a problem that I dont know how to handle. I have a project that has a camera movement, a player movements and some other scripts. In Game Editor once I pressed play, the sensivity was the same with the one that I have in the build app. But after some changes in another script, nothing about the camera settings or player movement, nor camera movement, the sensivity on the game editor became very very slow, but in the build it was the same. Luckily, I had a backup and once I loaded the new scene and the new assets, everything became good again. So its not from the scripts, neither the scene. It's not my first time I encountered this type of problem and a resolve to it would be very helpful. Thanks in advance!

true heart
#

Are you using Git? Firt thing I would check is exactly which files were changed

fierce tundra
fierce tundra
true heart
#

if something changed after you did some code, and then revert to normal after you removed the code, then its the code

#

I can't think of something else

round violet
#

how should i play once an animation on a object that overrides (as long as it runs) the active animator ?

#

making a new animator state for each "one shot" animations isnt the correct way

fierce tundra
rocky arch
#

why am i have such hard time making a sphere roll and steer like a unicycle ?

My setup is an empty game object the steering which rotate on Y, inside that a sphere that rotate on X

but the sphere keep changing orientation weirdly.

i tried locking axis wont work, any clues ?

mellow sigil
#

You'll have to show the code and describe the issue in more detail than that it changes "weirdly," maybe show a video

steady moat
grand elm
#

Who here felt like an intermediate level dev until they realized there was a data structure that lets you avoid unsafe and unnecessary code?

vestal arch
#

...and then you felt like a beginner or an expert level?

grand elm
#

Good question. Since it's the first time I should replay the tutorial

last quarry
vestal arch
#

arrays/lists so you don't have to do item1 item2 item3 item4

last quarry
#

Upon hearing this the novice was enlightened

#

Is that actually it? πŸ˜…

vestal arch
#

no, im just guessing lol

#

it seems like the most useful revelation lol

lean sail
#

i thought they meant unsafe like the keyword and had no idea what data structure could relate to this problem lol

strong spindle
#

Any possible fix with these?

naive swallow
unkempt meadow
#

Guys, why does the particle system sometimes play and sometimes doesn't? It seems to be based on a die roll

#

should I use .Emit instead of .Play? Is that more consistent

#

people online have been saying this has been the case with the particle system for at least a decade lol

steady moat
#

You should not use Play -> Stop as a way of emitting a single particle.

unkempt meadow
steady moat
#

If not, then no.

unkempt meadow
steady moat
#

Usually, you do not care about that.

#

It plays, end of the story.

#

In some case, you want to emit precisely a number of particle

unkempt meadow
#

Let's say for the sake of the argument, the effect is an explosion.

When stuff happens, I play the explosion once. Once that stuff happens again, I play the explosion again.

What is right in that case? From what you're saying, it should be play

steady moat
#

If the system is not emitting, you might have an issue with it.

#

Maybe it is not working as you expect.

unkempt meadow
#

but I don't want to stop it before playing again. Could that be causing an issue?

#

It seems like literally a random number generator on whether it works or not

steady moat
unkempt meadow
#

maybe it's to do with the fact that I childed another particle system on the parent particle system.

But if that were something to consider, then it should either always play or never play. Sometimes only the parent plays, sometimes only child, sometimes both and sometimes none

steady moat
#

It should stop itself if it is not looping.

steady moat
#

Which is quite a lot given that I do video game professionally.

unkempt meadow
unkempt meadow
#

ok thanks

#

I have a suspicion on why it might not work, will solve tomorrow probably

round crow
#

if (transform.position.x >= -15.3 | transform.position.x <= -15.2)
This doesnt work. If i make it just the position.x >= -15.3 then it functions but adding the or statement makes it bug

rigid island
round crow
#

oh i did that

#

both didnt work

round crow
rigid island
somber nacelle
# rigid island ~~you probably want `||` `|` ~~

in this context it's still a logical OR operator, not a bitwise OR. but unlike the conditional logical OR || it always evaluates both sides. that shouldn't change the logic, just the amount of work it does

#

i'd bet there's some other context we aren't getting here that would indicate why it isn't working the way they expect

vestal arch
round crow
#

so || is if i want it to work if any of those 2 function?

round crow
somber nacelle
#

you should show the full context because adding that second condition won't magically make it not work if the first condition is true

sweet raft
#

I'm getting mixed answers when I try to Google this. Unity's byte.Parse... Can it take a whole string, or is it just a single character? The docs seem like it can take a whole string, but C# talk says it can't because each character in a string is a byte, so it would need to be turned into a byte[] not just a byte.

leaden ice
#

it's just like int.Parse

#

but it parses to byte instead of int

#

byte and int are the same thing, except that byte only has 8 bits, where int has 32.

#

(also byte is unsigned, so it's kinda more like uint)

sweet raft
#

Okay. So I was using it incorrectly, but I think my followup question belongs in -advanced

rigid island
vague slate
#

I have a transform at A (global pos)
And point at B (global pos)

How can I calculate local vector AB for transform A?

#

I need to account for rotation of A

#

No need to account for scale as it's guaranteed to be uniform 1

mellow sigil
vestal arch
#

or B.position - A.position, if you want to know the math

subtle path
#

hey so i keep having this problem. I try to load saved data. when saving it should check if entry exists and if highscore points are higher. if so, then it should overwrite the old one, if not, it should do nothing. i tried a lot of things but i cant make it right. I even experimented with sortedlist, ilist and hashsets, but keep running into other problems with them.
can you say where the problem is?

#
c#
        /// <summary>
        /// creates new single entry OnLevelDestroyed
        /// </summary>
        public void CreateHighscoreEntry(string _name, float score, int id)
        {
            var Entry = new HighscoreEntry{Score = score, Name = _name, ID = id};
            HighscoreEntryToCurrentList(CurrentHighscore ?? new CurrentHighscores(), Entry);
        }

        public CurrentHighscores CurrentHighscore;
        /// <summary>
        /// adds new or overwrites old entries
        /// </summary>
        private void HighscoreEntryToCurrentList(CurrentHighscores scores,                   HighscoreEntry newEntry)
        {
            /////if list is empty 
            //if (scores.Entries.IsNullOrEmpty())
            //{
            //    scores.Entries.Add(newEntry);
            //    return;
            //}
    
            ///if entry exists and points are higher
            foreach (var existingEntry in scores.Entries.ToList())                                           
            {
                if(existingEntry.Name.Equals(newEntry.Name) && 
                   existingEntry.Score <= newEntry.Score)
                {
                    scores.Entries.Remove(existingEntry);
                }                           
                return;
            }
            scores.Entries.Add(newEntry);
            
            /////if list is not empty, but entry does not exist
            //if (scores.Entries.ToList().All(loadedEntry => loadedEntry.Name ==                     newEntry.Name)) return;
            //scores.Entries.Add(newEntry);
        }

        [Serializable]
        public class CurrentHighscores
        {
            public List<HighscoreEntry> Entries;
            //public SortedSet<HighscoreEntry> Entries;            
        }

        [Serializable]
        public class HighscoreEntry
        {
            public int ID;
            public string Name;
            public float Score;
        }```
steady bobcat
# subtle path ``` c# /// <summary> /// creates new single entry OnLevelDestroy...
foreach (var existingEntry in scores.Entries.ToList())                                           
{
    if(existingEntry.Name.Equals(newEntry.Name) && 
       existingEntry.Score <= newEntry.Score)
   {
        scores.Entries.Remove(existingEntry);
   }                           
   return;
}
scores.Entries.Add(newEntry);

This seems sound and should work just fine, but why do .ToList() on a list? (its wasteful)
You can do it faster by itterating backwards with a for loop and doing RemoveAt() instead.

#

Oh hangon, you RETURN when you find a match... did you mean break?

#

that would explain it 😐

vestal arch
#

wouldn't you want a leaderboard to be sorted?

subtle path
#

there is no leaderboard. no sort needed

vestal arch
#

oh wait this is like a map of names to individual high scores?

#

why not use a dict?

steady bobcat
#

@subtle path fix the logic error i pointed out and see if it acts as you desire now πŸ™

subtle path
steady bobcat
vestal arch
#

oh needs to be serializable

subtle path
#

it didnt fix it

#

i still get two entries

vestal arch
#

you should probably have the Add also beside the Remove

#

you're just adding unconditionally here

subtle path
#

i also need to cover adding new entries

vestal arch
#

also perhaps some built-in methods could make this easier

vestal arch
#

then you'd need to be able to check whether or not you should add if the existing entry is higher

vestal arch
steady bobcat
#

I would recommend a reverse for loop doing the same check so it can be removed quicker via index.

sudden ruin
#

whats the right way to make character wear stuff that change appearance
is it just hat and armor as prefabs and throw it on the bone spot ?

subtle path
steady bobcat
#

use a debugger to check whats happening

#

if you had earlier you would have found that return a lot sooner

subtle path
#

i am on this for month now πŸ˜–

vestal arch
#
var existingEntry = scores.Entries.Find((entry) => entry.Name == newEntry.Name);
if (existingEntry == null) {
  // new player - add `newEntry`
} else {
  // existing player - check for score, if new score is higher then remove `existingEntry` and add `newEntry`
}
steady bobcat
#

HighscoreEntryToCurrentList(CurrentHighscore ?? new CurrentHighscores(), Entry);
This looks sus btw, new CurrentHighscores() is not assigned to anything...

vestal arch
#

(then you'd have to make sure actual ids aren't 0)

subtle path
#

ill try your suggestions. will take a bit

cosmic rain
#

Take a byte

vestal arch
#

take a buffer

steady bobcat
#
for (int i = scores.Entries.Count - 1; i >= 0; i--)
{
    var existingEntry = score.Entries[i];
    if (existingEntry.Name == newEntry.Name && existingEntry.Score <= newEntry.Score)
    {
        scores.Entries.RemoveAt(i);
        break;
    }
}

What I would do

vestal arch
#

if you loop yourself you'll need an extra variable to see if the matching name was found

#

well you could pull i into the outer scope and check if it's -1 i guess

steady bobcat
#

we can just set a bool or yes move out i to the outer scope. This way we don't need to loop twice which is just more costly with a list of pointers.

vestal arch
#

you already do loop twice though lol

steady bobcat
#

tis not the same

vestal arch
#

it is though..?

subtle path
#

good to see you are as confused as i am

vestal arch
#

oh well i guess my Find/Remove method would iterate slightly more but if you're worried about that you can just swap it out with FindIndex and RemoveAt for sometimes more, sometimes less iteration

eager tundra
vestal arch
subtle path
#

yea... that would destroy all entries

vestal arch
#

FindLastIndex/for -- + RemoveAt: distance to the end of the list, twice
FindIndex/for ++ + RemoveAt: full size of list
Find + Remove: distance to the start of the list + full size of list
FindLast + Remove: distance to the end of the list + full size of list

steady bobcat
#

Yea my point is to itterate and compare once, then remove a faster way (via index). few ways to do that yes

eager tundra
#

ah sorry πŸ˜…

vestal arch
#

it really wouldn't make too much of a difference in the grand scheme of things though lol

#

premature optimization go brrrr

#

just get something that makes sense and is readable, imo

steady bobcat
#

we game devs must optimise everything!!!!! /s

subtle path
#

i dont need to optimize.

#

i need it to work

#

i am literally saving at one set point. and its a tiny bit of data

steady bobcat
#

well we told you how to make it work and for it to be fast!

subtle path
#

speed is not important

vestal arch
#

yeah we're basically discussing theoreticals

#

you don't have to worry about/apply the extreme micro-optimization

steady bobcat
#

I dont know where you use this or how often so i wanted to provide a solution that I deem to be good

subtle path
#

this game is supposed to release next week 😭

#

i just need it to work

vestal arch
#

we've given multiple suggestions on what you could do

subtle path
#

and i am currently testing

vestal arch
#

not sure what you're complaining about

steady bobcat
#

less complain more fix-y

round crow
#

Guys when i change a simple thing in unity 2d it legit takes 10 seconds before i can run it again

#

when its not even big, i have 4 scripts and 5 items

#

Why does it take so long

trim schooner
#

"a simple thing" - you mean code, yes?

It has to recompile, it doesn't care how "simple" the change is

round crow
#

yea but why does it take so long

vestal arch
#

depends on a ton of factors

round crow
#

i have a good pc setup and a friend of mine has a worse setup and 3d game with more and its faster when he changes a simple script with 10 lines like me

cosmic rain
round crow
#

where are logs?

vestal arch
#

but also if it's a "simple thing" - is it just a number value or something? if so, use the inspector lol

night harness
#

unity 2d and 3d aren't like different things btw, just a different project preset

cosmic rain
tawny elkBOT
#
πŸ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

thick terrace
#

disk speed and processor power is a big factor, also worth checking if you can set an exclusion on the project folder in your antivirus so it's not scanning files as you work

round crow
round crow
# tawny elk

what do i send or check now, its just alot of random things for me

trim schooner
round crow
thick terrace
round crow
#

like it reloads domains, and compiles

thick terrace
#

oh you said unity folder, you don't want to exclude the unity install path itself haha

round crow
#

is it supposed to do both those

trim schooner
#

yes

#

ofc

vestal arch
safe flame
#

Yeah unity just kind of does that

round crow
#

but like why does mine take longer when i have a better setup

#

it feels so odd

safe flame
#

Well it might not even matter that it's a better setup

Some hardware doesn't mesh with unity as well as others

#

There's like a million things this could be

small pollen
#

Good day people, i am in need of some help

trim schooner
#

low disc space?
bigger project (more classes) - this includes plugins and packages?
too much running?
unit project stored in a cloud storage folder (dropbox, etc)?

trim schooner
tawny elkBOT
small pollen
#

So basically, i've been using Spine (animation software) for months now, and updated yesterday.

#

For some reason, ALL of the IK constraints don't work anymore

trim schooner
#

this is a code channel, is this a code question?

round crow
small pollen
#

I think so

#

cause i have no clue why

#

it works in Spine, but not at all in unity

trim schooner
#

so .. what code are you using with it?

safe flame
vestal arch
round crow
round crow
small pollen
vestal arch
small pollen
#

sorry

vestal arch
#

just so it won't automatically recompile

#

but it'll still need to recompile and domain reload before you hit play

round crow
#

then how will i recompile when i wanna test it

vestal arch
#

manually, via ctrl/cmd+r

thick terrace
#

you can turn off a) automatic reloads when you make a change, and b) the domain reload that occurs every time you hit play

vestal arch
#

if you're on mac

round crow
#

where do i disable it

#

project settings or preferences

safe flame
round crow
#

cus now i legit have to wait 10 seconds before i can even use unity

night harness
#

the point they we're trying to make is its not 1 simple word being changed

#

its the entire thing being redone

vestal arch
round crow
vestal arch
#

if that's how long it takes to recompile, yeah

night harness
#

if it makes you feel better 5 seconds is pretty fast compared to how people used to have to do things πŸ˜„

thick terrace
#

man i can only dream of a 5 second domain reload per change

vestal arch
thick terrace
#

i think the rider plugin often triggers it in the background when you hit s ave though, so it's ready by the time i tab back in

round crow
#

rider plugin? i alreayd tryed a plugin named fastscriptreload and it works but wouldnt load functions when i edited it

#

does ctrl+r reload functions aswell?

vestal arch
#

they're referring to the ide integration package

#

what do you mean by "reload functions"?

#

it's the entire recompilation

round crow
#

uh like public float

#

sorry lmao

vestal arch
vestal arch
#

i know what a function is

#

im asking what do you mean by reload functions

round crow
#

Like these

#

When i used that plugin and removed for example the spawn rate float

vestal arch
#

those aren't functions

round crow
#

it wouldnt update and i had to relaunch the unity program

vestal arch
#

those are fields

round crow
#

well anyway i had to relaunch unity for it to update

#

would ctrl+r update those?

vestal arch
#

that's probably a thing with the "fast script reload"

vestal arch
round crow
#

i mean it kinda does if u used the plugin

#

It would make it so u didnt haev the recompiling thing but still updated it

vestal arch
#

see, a plugin is a separate thing. this isn't

#

ctrl+r isn't a magic button
it's just the default shortcut to trigger a recompilation

thick terrace
#

hot reload plugins often have limitations when it comes to changing the structure of a class (adding/removing members)

vestal arch
#

or well, more accurately, refresh assets

subtle path
#

still cannot get it to run and cover all cases..... notlikethis

   {
       var Entry = new HighscoreEntry{Score = score, Name = _name, ID = id};
       HighscoreEntryToCurrentList(CurrentHighscore ?? new CurrentHighscores(), Entry);
   }

   public CurrentHighscores CurrentHighscore;
   /// <summary>
   /// adds new or overwrites old entries
   /// </summary>
   private void HighscoreEntryToCurrentList(CurrentHighscores scores, HighscoreEntry newEntry)
   {


       //if no entry exists => add first entry
       if (scores.Entries.Count == 0)
       {
           scores.Entries.Add(newEntry);
           Debug.LogWarning("NEW ENTRY: " + newEntry.Name + "/ " + newEntry.Score);
           return;
       }

       //iterating backwards and 
       for (int i = scores.Entries.Count - 1; i >= 0; i--)
       {              
           var existingEntry = scores.Entries[i];
           if (existingEntry.Name == newEntry.Name)
           {
               //if entry exists and score is higher than new => do nothing
               if (existingEntry.Score >= newEntry.Score){return;}
               else //if entry exists and score is lower than new => remove
               {
                   scores.Entries.RemoveAt(i);
                   Debug.LogWarning("Removed: " + scores.Entries[i].Name + "/ " + scores.Entries[i].Score);

                   //overwriting entry
                   scores.Entries.Add(newEntry);
                   Debug.LogWarning("Added: " + newEntry.Name + "/ " + newEntry.Score);
                   break;
               }
           }

       }

       //if entry does not exist => add new 
       if (scores.Entries.ToList().All(loadedEntry => loadedEntry.Name == newEntry.Name)) return;
       scores.Entries.Add(newEntry);
       Debug.LogWarning("Added: " + newEntry.Name + "/ " + newEntry.Score);
   }```
#

im running in circles

#

i keep getting double entries

mellow sigil
#

All checks if all entries in the list have the same name. You need Any instead

#

or just return in the loop when an existing entry is found, no need to check it twice

subtle path
#

ok that fixed the double entries. but now it deletes old entries when points are higher, but doesnt save the new one lol

#

i might see why....

#

that was the final thing... i fixed it.... its working now.
thank you very much guys

mellow sigil
#

The whole thing is quite overcomplicated. You could just do

int index = scores.Entries.FindIndex(loadedEntry => loadedEntry.Name == newEntry.Name);

if(index == -1) {
    scores.Entries.Add(newEntry);
}
else if(scores.Entries[index].Score < newEntry.Score) {
    scores.Entries[index] = newEntry;
}
subtle path
vestal arch
steady bobcat
#

we still on this score thing dang

dusky niche
#

How do I create a dashbar where you can reduce the image fill amount using lerp where the bar is split into 3 equal parts?
I can do it with bar by giving specific values in the lerp but the bar eventually fills up by time. I need something that checks the current fill amount so that I can store it in a variable to use it in the lerp.

vestal arch
#

you would generally have all the logic and variables in your script and then just set the value onto the image fill

#

all the values would be managed there, you wouldn't have to read back the current fill amount

pulsar dune
#

I need help with adding boimes to my procedural world generation

faint tree
#

anyone having issues with package manager timing out ?

rigid island
fiery bough
#

Soo, I have a perspective camera

How I calculate the "bounds rect" of the camera in for example
Z: 5

fiery bough
#

amazing

#

thanks

tender ice
#

how do y'all manage health for your games? I have one script for all entities and just sort it out through tags, if its a player its a different function from if its a enemy

#

I dont know where to begin optimizing my code, and since I had some jank code going on health, I figure I'd start from there

night harness
#

A lot of people use an interface in some form or way

tender ice
#

let me show you my code

#

but first imma comment each thing

night harness
#

example of interface usage

public interface IHurtable
{
    public int GetHealth();
    public void RecieveHealthModification(int difference);
}
public class MyHealthThing : MonoBehaviour, IHurtable
{
    int health;
    public int GetHealth()
    {
        return (health);
    }

    public void RecieveHealthModification(int difference)
    {
        health += difference;
    }
}
public class MyDamagingThing : MonoBehaviour
{
    int damageToDeal;

    private void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out IHurtable hurtable))
            hurtable.RecieveHealthModification(damageToDeal);
    }
}
tender ice
#

are you talking about an UI?

night harness
#

nah, interface is the name of a specific c# feature

tender ice
night harness
#

it's basically a contract/promise, where in the interface you can say what will be included, but the thing implementing the interface has to actually fulfill that contract/promise and implement the functions in that interface

tender ice
night harness
#

kind of, there's two reasons why you'd want an interface for something like this

  1. You can try to get the interface from a monobehaviour the same way you'd check for tags. instead of checking for "player" or "enemy" you can directly check (and get) the IHurtable interface if it has one

  2. the point of the interface is the thing damaging it's victim doesn't need to care how that victim recieves its damage. in this case you just call hurtable.RecieveHealthModification. buttt the thing that implemented the interface doesn't have to recieve that damage the same way as something else might, eg.

public class MyHealthThing : MonoBehaviour, IHurtable
{
    int health;
    public int GetHealth()
    {
        return (health);
    }

    public void RecieveHealthModification(int difference)
    {
        health += difference;
    }
}
public class MyOtherHealthThing : MonoBehaviour, IHurtable
{
    int health;
    int shield;
    public int GetHealth()
    {
        return (health);
    }

    public void RecieveHealthModification(int difference)
    {
        if (shield > difference)
          shield += difference;
        else
          health += difference;
    }
}
tender ice
night harness
#

basicially your health system right now handles the way it recieves damage based on what its connected two inside that single class

imagine if you could just handle that per usecase in each of the usecases directly, rather than trying to figure out what it is

night harness
tender ice
tender ice
night harness
#

The idea is that you shouldn't have 1 script that explicitly handles the health logic for both players and enemies, because as im sure you know most of your script is doing a bunch of checking to be like "if this is the player do that" "and if this is the enemy do that".

So from there the solution would be to split that 1 script into 2 scripts of some sort, one that handles player health and one that handles enemy health

But when you want to actually give those scripts the damage or tell them to die your gonna have to check if it's the player health system or the enemy health system etc. which is what we wanted to avoid in the first place

that's why we can use an interface thats implemented on both scripts (eg. PlayerHealthSystem and EnemyHealthSystem) where the interface basicially says (hey, you can send this thing damage, i have no idea what that actually means but it does support recieving damage)

tender ice
tender ice
vestal arch
#

a method to deal damage, and perhaps a health property, presumably

#

anything that implements that interface can be damaged

#

see batby's example of IHurtable above

tender ice
#

where would I make invincibility frames? on the interface aswell?

vestal arch
#

not saying this is better, just offering an alternative:
combining things in most programming languages boils down to either inheritance or composition
batby's example is inheritance, but you could also do composition
i have an Entity component that handles core stuff about any entity (both players and enemies) that manages health and getting hit (as well as the related UI), set up as a prefab
then it exposes a UnityAction for getting hit, so other components can subscribe and be notified when they get hit, so it can stun or whatever accordingly

#

an interface would specify what can be none, not how to do it exactly. if there's shared functionality, perhaps use a base class instead?

tender ice
#

i seem more interested in the interface method because it'll make it easier to work with multiple people, I like to think of it that other entity health scripts are branches and the tree being the interface itself

#

im cleaning up the project because im the lead coder but my other two buddies are also joinning in, and so I need something easy to work in

round violet
#

how do you remove multiple packages that are dependent to each other (remove button is grayed out) ?

old adder
#

Hi guys i need some help about some code and im not quite sure in which channel i should post this question. Even chatgpt+ couldnt help and 4+ hours of debugging

trim schooner
old adder
#

Alr thank you

vestal arch
round violet
#

basic ECS packages do

#

for example

round violet
mellow sigil
#

Those don't depend on each other

night harness
old adder
#

but its probably better than me at gamedev

round violet
mellow sigil
#

What dependencies does that one have?

round violet
#

whats showed on previous screenshots

#

for example the Entities package is used by CC and Unity Physics, im obviously not removing those

trim schooner
#

CC isn't an obvious keep

mellow sigil
#

If you don't want to remove those then you can't remove this package either

#

CC and Physics stop working if you don't have all their dependencies installed

round violet
#

but i never had the entities packages before ?

#

and CC worked fine

trim schooner
#

things change and get updated

round violet
#

unless i never paid attention when using the CC packages

#

im used to unity 2022 maybe thats why

#

im curious why CC NEEDS entities to work

mellow sigil
#

Probably for compatibility with ECS

round violet
#

well thats dumb IMO, such features should be in a third package "CC & Entities"

trim schooner
#

You won't notice a difference if it's there or not

round violet
#

i do when i have 10 packages i dont want

#

at the first 2 week of my project

trim schooner
#

only when you look at the PM

round violet
#

anyways, i think we agree that on a deisgn POV it shouldnt be done like so

#

but yeah, doesnt do much harm

#

other than more compilation times

wraith spear
#

Is there a way to exclude code from tests only? So for example in a normal class:

#if TEST_CASE
// some code
#endif

I've been eyeing Player settings' Scripting Define Symbols, but I haven't found a way to make it work yet (have the symbol off when playing in Editor, but on while running Edit mode Tests)

night harness
#

initial nitpick, does it have to be instantly? because that sounds like something you can fit into more than one frame

leaden ice
#

Have you tried just doing it? Did it actually result in a framerate dip?

wraith spear
night harness
#

it's heavily intergrated into the cc package