#archived-code-general

1 messages Β· Page 243 of 1

knotty sun
#
  1. Seralized classes should have a parameterless constructor
swift falcon
#

How do I check if smaller rectangles fit in a rectangle-sized area? Calculating areas doesn't work because the rectangles have different scales, and their rotation must remain the same. I also want these rectangles to be instantiated inside the area.

fervent furnace
#

are the rects AABB?
you said the rotation is the same (though you can still rotate them to be two AABBs then check otherwise you need SAT)

glacial island
#

Does anyone have experience with connecting bluetooth devices with Unity and getting data from the connected devices? I need some help with connecting a Sensor with the quest3

quartz folio
swift falcon
glacial island
swift falcon
#

Is everything I just said nonsense?

fervent furnace
#

always parallel doesnt mean they are axis aligned (the width and height is aligned to x and y axis)

swift falcon
fervent furnace
#

then easy, you have two rects and you only need to check if A.min>=B.min&&B.max<=A.max (min is bottomleft and max is topright) and you need to check then reversely after that since A may stay inside B
you can also change >= to >

swift falcon
fervent furnace
#

the min of smaller rect will fall in special range in order not to go outside the big rect area
from big.min to big.max-small.size (calculated from max-min)

#

or restrict the max, the idea is same

swift falcon
#

I am not sure if I understood everything. Could someone provide example code?

#

i am not sure how to do it with multiple rectangles

fervent furnace
#

Can they overlap?

swift falcon
#

no

#

that was the point of my orginal question sorry for not being clear

fervent furnace
#

i remember a long time ago we have a discussion on how to allocate (and deallocate) AABB space "efficiently"
but i doubt you cant understand it......(my idea is based on k-d tree and free list but i forgot how issue implemented it at the end)
another much simpler approach is to check if the new spawned rect overlaps with other old spawned rects

swift falcon
#

I was thinking if there is a asset for doing it

#

but this is not really that important for my project, I can easily change my level design

coral yew
#

Does anyone know if an XML-Serialization based Save System works on Mobile (Android / IOS)

knotty sun
coral yew
knotty sun
coral yew
knotty sun
coral yew
#

Okay perfect, thank you

cosmic geode
#

hello!
is there any way to detect collision on spawn? i have a gameobject with a trigger collider that is instantiated and another object that detects the trigger and does some actions. the problem is that the gameobject that detects the trigger can sometimes be in a point where the trigger can be instantiated and there is no way to avid this. is there a way to check if it is colliding in the start function or some other trick to ignore collision with objects that are already colliding when created?

cold parrot
neon plank
#

Question:
The other day I opened a Unity project that wasn't mine, and in order to open it Unity told me that automatic recompilation of code was going to get disabled...
But now, when I open my project, code do not recompile if I modify it. How can I re-enable that?

vagrant blade
neon plank
vagrant blade
#

Probably moved then, look it up for your specific Unity version

neon plank
craggy totem
#

Hello devs, i have question - is it possible to somehow use Vector2.dot instead Vector3.dot To reduce calculations ,bcs i have to much of them.
Calculation in X and Z axis is enough for me. no need of Y axis

                    Vector3 DirToTarget = Vector3.Normalize(transform.position - MainCar.position);  
                    DotProduct= Vector3.Dot(transform.forward, DirToTarget);

what can replace Vector3.Normalize to pass it to Vector2.Dot?
thank you in advance

fervent furnace
#

no, casting vec3 to vec2 discard the z

prime ice
#
using System.Collections.Generic;
using UnityEngine;

public class jumpanim : MonoBehaviour
{
    // Start is called before the first frame update

    public Animation jumpanimation;
    public AnimationClip jump1;
    public AnimationClip jump2;
    public float timer;
    public float animno;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) { jumpanimation.Play(); }

        if (Input.GetKeyDown(KeyCode.Space) && jumpanimation.isPlaying)
        {
            jumpanimation.Stop();

            {
                if (timer < animno)
                { timer = timer + Time.deltaTime; }

                else
                {
                    jumpanimation.clip = jump1;
                    jumpanimation.Play();
                    jumpanimation.clip = jump2;
                }

                  
            }
    
        }

        if (jumpanimation.clip == jump1) { Debug.Log("anim2 playing"); }
    }
}```

SOMEONE HELP why no anim playing but still no error
im rly rly new to coding
someone can fix it for me
somber tapir
somber tapir
prime ice
#

no animation is playing

#

it was working perfectly until i added this line

#

if (timer < animno)
{ timer = timer + Time.deltaTime; }

fervent furnace
#

so after you increment the timer, where you decrease it?

somber tapir
prime ice
#

wdymmm

#

i dont understand

#

please im insanely new to coding

#

i just watched a flappy bird tutorial and now im trying to add animations myself cuz the tutorial didnt have

fervent furnace
#

your code:

if(t<T){
  t+=dt;
}else{
  nothing related to t here
}
knotty sun
#

more to the point, how often do you expect if (timer < animno) to be executed?

prime ice
#

oh yeah

#

i thin k i understand

#

there is a problem that

#

the timer is going up

#

rly slow

#

how to fix it

#

its like 0.00001 and next frame 0.000002

#

i need it to go 1 per second

somber tapir
# prime ice wdymmm

In Update() you check if the player presses Space and if he does you Play() the animation. But in the very next line you check again for Space and also if the jumpanimation.isPlaying is true. I assume jumpanimation.Play() would set jumpanimation.isPlaying to true, so when the player presses Space you Play() the animation but instantly call jumpanimation.Stop() as well.

But I don't know if this is the case or not. That's why you should use Debug.Log("Second If Statement") or something to figure out if my theory is correct.

somber tapir
# prime ice oh yeah

you only increase the timer when the player presses space bar, so you would need to increase it outside the if statement

prime ice
#

oh

#

ok

#

but i want the timer to start after the person presses space

#

thats my point

somber tapir
# prime ice oh

toggle a bool in the if statement, only increase timer if bool is true

prime ice
#

like if its been 2 sec after pressing space play anim 2 and if its not then play anim 1

#

thats my goal

knotty sun
#

So,
if space -> Play anim 1 -> start timer
if timer > 2 -> Play anim 2
no nesting required

craggy totem
# fervent furnace no, casting vec3 to vec2 discard the z

@fervent furnace will it work if i pass like this

                    DotProduct= Vector2.Dot(
                    new Vector2(transform.position.X, transform.position.Z).normalized, 
                    new Vector2(DirToTarget.position.X, DirToTarget.position.Z).normalized);

@somber tapir like this?

                    DotProduct= Vector2.Dot(transform.forward.normalized, DirToTarget.normalized);

@somber tapir pardon for interruption

fervent furnace
#

i doubt that copying the value is slower or the compiler can optimize it, though vec2.normalize should be faster than vec3 a lot.....

knotty sun
prime ice
#

if its in if state

rigid island
knotty sun
prime ice
#

but it only goes up when i press space and stops, i need it to keep going after i press space and reset after i press space again

somber tapir
knotty sun
prime ice
#

but then it keeps going even if i dont press space

#

oh wait im dum

#

i understand

#

but wait

#

for the first space

#

like the first space hit the player does

#

i want it to

#

start the timer after that

knotty sun
#
timer = 0;
...
if (space) timer+= deltaTime;
else
if (timer > 0) timer += deltatime;
...
if (timer > 2) // Do stuff; timer =0;
prime ice
#

or is that too advanced for me

rigid island
#

you're in the wrong channel then

prime ice
#

hmmm ok

#

huh

#

i thought this was for any level

#

general

#

sorry

rigid island
#

nah this expects you to already know these basic concepts

prime ice
#

o sorry

rigid island
#

all gud πŸ™‚

prime ice
#

like its at 0 and after each time i hit space it goes up by 0.01

prime ice
#

not like count by itself

#

what does the else do

#

sorry if im being dum again

knotty sun
#

it increments the time if no space has been hit but the timer has been started

prime ice
#

because it is timer+=deltatime in both case

#

hm let me try

craggy totem
#

@fervent furnace @knotty sun @rigid island what about this ? is there something that can be used instead transform.forward. maybe that all stupid but want to try

rigid island
#

it will compile if thats what ur asking

#

looks fine

#

those variable names suck tho

craggy totem
knotty sun
#

you are using a normalized direction as the second argument, that does not make sense for a .Dot calculation

rigid island
#

since the engine is 3d

#

the perfomance is probably negligible

#

whats an extra 4 bytes..

rigid island
craggy totem
rigid island
#

thats like saying i use too many floats

#

rendering and other stuff like that is more performance heavy

prime ice
#

@knotty sun i think i did what u showed me and same issue is happening

prime ice
#

only 1 animation plays everytime

#
        timer = 0;


        if (Input.GetKeyDown(KeyCode.Space))
        {  jumpanimation.Stop();
            jumpanimation.Play();
            timer= 0;

            timer += Time.deltaTime;

        }

        else
        { timer += Time.deltaTime; }

        if (timer > animno) { jumpanimation.clip = jump1;}
        else if (timer < animno) { jumpanimation.clip = jump2;}
        ```
knotty sun
#

ok, the timer=0 needs to be outside the method

rigid island
prime ice
#

huh what do u mean

prime ice
craggy totem
prime ice
#

or send clip

rigid island
prime ice
#

wait let me send clip but it might look stupid im really new

prime ice
rigid island
#

cause seems you can use some sort of animation events

rigid island
#

jump animation or something?

prime ice
#

i want anim1 to play inside of 2 sec of pressing spacebar and anim2 to play if its been more than 2 seconds

#

in between the spaces

knotty sun
#

look it simple

float timer = 0;
void Update () { // Do the Rest }
prime ice
#

ohhh

#

ok

rigid island
prime ice
rigid island
#

are you doing a combo system

prime ice
#

if player press space once and then presses space again in under 2 sec then play anim 1

#

and if player press space once and the next time after 2 sec thenplay other anim

#

@rigid island nah i just watched a tutorial to make flappy bird

#

it didnt have animations

#

i made my own

#

1 animation worked but it looks weird

#

if we press space fast

#

thats why i need 2]

#

ik it sound stupid

#

lemme try send clip

knotty sun
#

you really need to start thinking about your code

prime ice
#

steve there is error

#

showing

rigid island
prime ice
#

if i place outside void update

rigid island
#

what is the error? that has no errors

prime ice
#

oh wait nvm its cuz i already had public float timer; written

#

im super dum

knotty sun
#
if (Input.GetKeyDown(KeyCode.Space))
        {  jumpanimation.clip = jump1;
            jumpanimation.Play();
            timer = Time.deltaTime;

        }

        else if (timer > 0)
        { timer += Time.deltaTime; }

        if (timer > animno) {
         jumpanimation.clip = jump2;
           jumpanimation.Play();
          timer=0;
}
prime ice
#

still doesnt work though :((

#

hmm lemme try that

#

OKAY I THINK U SOLVED THE PROB

#

but like now

#

if i press jump before 2 sec it shows no animation basically delay of 2 sec before the anim shows

#

wait i think i can fix that tho

#

i think it might be cuz there is no animation stop

#

dam nvm still doesnt work

knotty sun
#

then add a if isPlaying -> Stop

prime ice
#

yeah i did

#

but still doesnt work

knotty sun
#

where

prime ice
#

i mean its the same problem as before

#

only 1 anim plays everytime

#

the timer only goes up when i press space

knotty sun
#

show your code

prime ice
#

WAIT NVM TIMER IS GOING UP

#

but the anim still not playing

#

if (Input.GetKeyDown(KeyCode.Space))
{ jumpanimation.clip = jump1;
jumpanimation.Play();
timer += Time.deltaTime;

    }

    else if (timer > 0)
    { timer += Time.deltaTime; }

    if (timer > animno) {
     jumpanimation.clip = jump2;
       jumpanimation.Play();
      timer=0;

}

#

wait no thats not it

#

if (Input.GetKeyDown(KeyCode.Space))
{
jumpanimation.Stop();
jumpanimation.clip = jump2;
jumpanimation.Play();
timer += Time.deltaTime;

    }

    else if (timer > 0)
    { timer += Time.deltaTime; }

    if (timer > animno)
    {
        jumpanimation.clip = jump1;
        jumpanimation.Play();
        timer = 0;
    }
#

here

#

it plays jump2 everytime i hit space

#

but timer works perfectly

#

it resets if space after 2

knotty sun
#

so what is the value of animno in the inspector?

prime ice
#

two

knotty sun
#

show me

#

you have the clips round the wrong way

prime ice
#

no no

#

u had wrong

#

i did right

#

i just wrote 1 and 2 wrong

#

in the like

#

names

knotty sun
#

no, jump1 first then jump2

prime ice
#

it doesnt matter tho its playing the same animation

#

also

#

huuuuuh what

#

it plays the jump1 automatically after timer hits 2

#

even if i dont press jump

knotty sun
#

then animno is not 2

prime ice
#

it is 2

knotty sun
#

show me

prime ice
#

wait lemme send clip of what happening

knotty sun
#

no, that is pointless

prime ice
#

it loading

#

oh ok

#

then lemme just send ss

#

here u go

#

i know there prob a way easier way to do all this by directly doing rotations but i dont know how

rigid island
#

oh god why are you using animation component

#

is deprecated

knotty sun
#

right so the code says
start the timer if space is pressed
if the timer has started increment it
if the timer has reached 2 play the second anim

prime ice
rigid island
#

stick to animator then

prime ice
#

i want to do it

knotty sun
#

so what's the problem?

prime ice
#

if the timer has reached 2 AND spacebar is pressed

#

play 2nd anim

#

its doing it automatically

#

when timer hits 2

knotty sun
#

ah, so add another space check to the timer> anino if

crimson trellis
#

Is there a way to see a class in the inspector without it being based from monobehavior?

knotty sun
prime ice
#

o ok

#

i think i fixed it

#

LES GO

#

IT WORKS

#

THANKS

rigid island
crimson trellis
rigid island
#

why would you always need static ?

fervent furnace
#

global variables lover

crimson trellis
#

I have a script like this public abstract class something<T>: monobehavior if I create a nested class in it,it 'll get really hard to manage

rigid island
#

XY problem

crimson trellis
#

So I decided to the create class somewhere else

eager steppe
#

Hello y'all. In my game I have a level decoration editor that I'm trying to get up and running. Is it better to create a thread so I don't "clutter" this channel?

crimson trellis
#

So I just use a using static classname to access to it

#

But every time I create a new class I have to type that it's get annoying

knotty sun
crimson trellis
#

It's not visible in the inspector

eager steppe
#

or whatever IDE you're using

#

static classes will never be visible in the inspector (?)

knotty sun
#

tbh if typing 1 line of code is 'annoying' then programming is probably not for you

eager steppe
#

its either that or you're doing that specific thing wrong (maybe using static stuff too much?)

prime ice
#

steve there is new problem

eager steppe
prime ice
#

it still plays animation on its on

#

own

rigid island
prime ice
#

wait let me try to fix

knotty sun
eager steppe
crimson trellis
prime ice
#

yes

eager steppe
#

Alright, don't use Animation, right off the bat

rigid island
#

they can't be directly attached to gameobjects though

eager steppe
#

in the Animation window in Unity, just drag the animation clip "Bird" in there, and make a note of it's name

#

and just do jumpanimation.Play("Bird", -1, 0f); inside your script
This is much much less of a headache to work with

eager steppe
#

i'll be so real I don't even know what qualifys as "beginner", "general" or "advanced" concepts

rigid island
#

general IMO you are expected to know all this basic jargon

eager steppe
#

aight bet

rigid island
#

I think this would be good for like Procedual mesh generation and stuff like that

eager steppe
#

i hate 3D procedural generation. that involves so much math

#

Mimicing Unity's Transformation System at Runtime

knotty sun
#

I would say
Beginner - Doesn't know how to read or google
General - Knows how to read and google but can't be arsed to
Advanced - Knows how to read and google but still doesn't understand stuff

rigid island
#

google becoming a lost art 😦

eager steppe
#

I agree, but Idk man. Google hates me today

#

apparently nobody on Unity Forums has attempted what I'm trying to attempt

knotty sun
#

indeed, if it aint a crappy YT tut it doesn't exist

eager steppe
#

but also using Unity Forums requires me to log into Unity ID. and I can't be asked to do that for the 13th time today

rigid island
#

ever heard of cookies?

eager steppe
crimson trellis
#

Hey can you store a Touch as a object?

eager steppe
#

a GameObject...?

#

what exactly are you trying to do

rigid island
#

touch iirc is a struct

#

so it kinda is already

crimson trellis
#

Not a game object

#

Just object

cold parrot
#

why cant you use whatever it is?

knotty sun
#

Touch is already an object

rigid island
eager steppe
#

its a enum :c

rigid island
#

axis.x is enum?

cold parrot
#

that makes no sense

crimson trellis
#

I'm trying to store different things as object and later convert it back,

eager steppe
crimson trellis
#

I don't know why I have a bug that I cannot set it

cold parrot
#

maybe put more information in your posts then

#

feels like there is some sort of misunderstanding going on

knotty sun
#

some code might help

cold parrot
#

you can store anything as an Object type and convert it back to whatever it was before you stored it

#

but thats circumventing they c# type system which is usually a code smell, but sometimes OK (or even neccessary)

eager steppe
# rigid island axis.x is enum?

Okay, so essentially I use an enum to differentiate the different arrow GameObjects and be able to know what axis they are controlling. Not sure why I didn't just use a string tbf but yes

I use that in order to know what property to just change

crimson trellis
#

Line 37 have a null reference problem

rigid island
#

where do you assign baseTUI

eager steppe
leaden ice
#

Everything is always object

last raven
#

is there any problem with having globals for WaitForFixedUpdate/WaitForEndOfFrame? I know potential issues with WaitForSecondsRealtime (it has the time counter inside so yielding from different coroutines will wait until the same time even if started at different moments - I can't say if WaitForSeconds works the same because unlike realtime version its code is native so I can't easily decompile it) but what about fixedupdate/endofframe?

leaden ice
#

However make sure you are using EndOfFrame properly

last raven
#

so why does unity provide them as classes instead of just global yieldinstruction references?

leaden ice
#

Many people use it thinking it means "wait one frame" and it doesn't

last raven
#

I understand what it means

leaden ice
last raven
#

I have my own coroutine library that completely implements coroutines in editor

#

so everything that works in player works in editor as well

#

so I don't have to rewrite a ton of code that relies on coroutines to work in editor

#
  • wrapper for unity coroutines that implements a ton of extra stuff
#

I was just curious about these 2 objects since I can't easily decompile unity coroutine code and I was wondering why they aren't just globals

#

if they are safe to yield from multiple coroutines

heady iris
#

like WaitForSeconds

#

it makes more sense to just be consistent

#

if you want to make your own static fields to hold instances of the non-configured coroutine objects, then that's fine

last raven
#

the thing with it - waitforendofframe doesn't need to be class since it can be just global reference

#

if they don't really hold any data

heady iris
#

Yes, it doesn't need to be

last raven
#

and safe to return

heady iris
last raven
#

then it's a complete waste to have them as classes

#

and tbh I disagree with design decision with waitforsecondsrealtime, i.e. not being able to cache it

#

but w/e

heady iris
#

i'm pretty sure you can reuse it

last raven
#

you can reuse but not while it's in use

#

I decompiled its code and it least in unity 2019 it will not work

heady iris
#

ah, yes, it is mutable

last raven
#

because it stores time when it should stop waiting when you yield it first time and until it reaches that time it will not set new time

heady iris
#

good to know that

last raven
#

not sure about waitforseconds, since it's native code but it's probably same

#

so basically you can reuse it in the same coroutine but it's not safe to reuse in multiple coroutines

heady iris
#

That's probably what I was remembering.

last raven
#

I was surprised one is native code and one is not

eager steppe
#

hey y'all
Honestly I'm just shit at math, but I'm trying to rotate my gameObject using a Z axis sprite that i'm dragging with my mosue.

This is the code for it:

void EditRotation(Ray camRay, float planeDist)
{
    // Calculate the change in mouse position
    Vector3 currentMousePosition = camRay.GetPoint(planeDist);

    // Calculate the angle of rotation based on the mouse movement
    float angle = Mathf.Atan2(currentMousePosition.y - initial.y, currentMousePosition.x - initial.x) * Mathf.Rad2Deg;

    // Apply the rotation based on the axis
    if (axis == Axis.Z)
    {
        Vector3 rotation = Thing.transform.rotation.eulerAngles;
        rotation.z += angle;
        Thing.transform.rotation = Quaternion.Euler(rotation);
    }

    // Update the initial position for the next frame
    initial = currentMousePosition;
}```

But this is the result I get:
heady iris
#

your code is computing the angle between your old mouse position and your new mouse position

#

then adding that angle to your current Z Euler rotation

#

that's wrong; that's like doing transform.position += desiredPosition; instead of transform.position = desiredPosition;

#

Instead, you should compute two angles

#
  • The angle from the center of the object to the old mouse position
  • The angle from the center of the object to the new mouse position
#

The difference between those two will be how much to rotate the object by

eager steppe
#

alright, thank you :)

heady iris
#

You could get rid of the trig by doing this instead

#
Vector3 oldDelta = initial - transform.position;
Vector3 newDelta = currentMousePosition - transform.position;

float delta = Vector3.SignedAngle(oldDelta, newDelta, Vector3.forward);
#

SignedAngle gives you the angle between two vectors, relative to an axis

#

this might be backwards; in that case, negate the result or use Vector3.back

#

I almost never use trig nowadays :p

eager steppe
heady iris
#

the Vector and Quaternion methods usually make it easier to see what the actual intent is

eager steppe
#

i was just going to go ahead and just use Mathf.Abs for no reason, but maybe this would be beter than my math :p

heady iris
#

so the next line would be transform.rotation *= Quaternion.AngleAxis(delta, Vector3.forward);

#

euler angles can surprise you

#

although, in this case, it should be fine

#

you can have problems if you try to clamp them to a range

#

you might have seen all three euler angles change when rotating around an axis before, for example

eager steppe
#

i'm unsure whether to clamp the other axis honestly. I'm not sure if I should take such a decision. I'll test it with players later and see how "limiting" it could possibly be.

hard viper
#

is there a way to force something that implements IMyInterface1 to also implement IMyInterface2?

#

like an extra constraint

rigid island
#

nvm lol

somber nacelle
#

you can't constrain to two types like that

rigid island
#

actually prb not

#

yeah myb

somber nacelle
#

interfaces can inherit from one another though, so if you have an interface that should also always implement another interface for example IUsableItem should also be an IItem then IUsableItem can inherit IItem

hexed wagon
#

hi do you guys know the shortcut to reformat code spaces in visual studio

rigid island
#

cntrl K +ctrl E

hard viper
#

or does that pass it down to whatever class actually implements interface1

somber nacelle
#

the responsibility is on the implementing type

hard viper
#

ok, and if I have multiple interfaces, does that work out? like IA : IB, IC : IB, and class : IA, IC

rigid gull
#

I'm struggeling with a save system / main menu, anyone here have a minute to spare?

hard viper
#

yeah

rigid gull
#

I have the data serializing/de-serializing

#

i have profile id's working

#

i'm stumped on the slave slot menu

#

trying to make the tutorial i am watching work with my main menu which is a little diferent.

#

and it's all so overwealming at this point i feel im in over my head

hard viper
#

break this down a bit to a more specific problem

somber nacelle
rigid gull
#

hold on let me think

hard viper
#

you could make a single save slot a single serializable class, suppose it has an int for how far you are, and an int for save slot ID

rigid gull
#
using TMPro;
using UnityEngine;

public class SaveSlot : MonoBehaviour
{
    // Serialized field to assign a unique identifier for each save slot
    [Header("Profile")]
    [SerializeField] private string profileId = "";
    // Reference to the GameObject that is shown when there is no data for this slot
    [Header("Content")]
    [SerializeField] private GameObject noDataContent;
    // Reference to the GameObject that is shown when this slot has data
    [SerializeField] private GameObject hasDataContent;
    // Text component for displaying the character's name associated with this slot
    [SerializeField] private TextMeshProUGUI characterName;

    // Method to update the slot's display based on the given CharacterData
    public void SetData(CharacterData characterData)
    {
        // If there is no character data (null), show 'no data' content and hide 'has data' content
        if (characterData == null)
        {
            noDataContent.SetActive(true);
            hasDataContent.SetActive(false);
        }
        else
        {
            // If there is character data, show 'has data' content and hide 'no data' content
            noDataContent.SetActive(false);
            hasDataContent.SetActive(true);

            // Update the text to show the character's name
            characterName.text = characterData.Name;
        }
    }

    // Method called when this save slot is clicked
    public void OnClickSaveSlot()
    {
        // Notify the MainMenu to update the selected profile ID with this slot's profile ID
        MainMenu.Instance.SetSelectedProfileId(this.profileId);
    }

    // Getter method to access the private profileId field
    public string GetProfileId()
    {
        return this.profileId;
    }

    public void SetProfileId(string id)
    {
        profileId = id;
    }

}
hard viper
#

you can look through a file directory to find all the files of that type, and now you have several instances of files corresponding to save files

rigid gull
#

it is serializing the data correctly i can see it make save files in my dir

hard viper
#

ok, but you need to populate a menu with save slots, and then go find it

rigid gull
#

I'm at the part where i want the save slot menu to activate when i start the game, and check if ther are save's or not.

hard viper
#

like, a menu with buttons for slots 1,2,3. And if I click slot 2, you need to know to go get file2

#

you can make one file that stores information of which file goes to which slot, and open/edit it.
OR you can open all the files and store a bit of metadata in each

rigid gull
#

not quite, I want it to generate an empty save slot each time you go into the select character menu, but also generate any previously made profiles

hard viper
#

like saveSlots.JSON, which could be like a list of (string filename, int slotID)

rigid gull
hard viper
#

once you make that list, then you can hand that off to the UI script, and do whatever the hell you want

#

but making that list of tuples is the first order of business

#

you could even parse that, with (myClass parsedClass, int slotID)

rigid gull
#
public class SaveSlotsMenu : MonoBehaviour
{
    [SerializeField] private GameObject saveSlotPrefab; // Assign in Unity Editor
    [SerializeField] private Transform saveSlotContainer; // Assign in Unity Editor
    private SaveSlot[] saveSlots;

    private void Awake()
    {
        saveSlots = this.GetComponentsInChildren<SaveSlot>();
    }

    private void Start()
    {
        // Get all save profiles from SaveManager
        Dictionary<string, CharacterData> saveProfiles = SaveManager.Instance.GetAllProfileGameData();

        // Create a save slot for each save profile
        // Create a save slot for each save profile
    foreach (KeyValuePair<string, CharacterData> profile in saveProfiles)
        {
            CreateSaveSlot(profile.Key);
        }

        ActivateMenu();
    }

    // Activates and populates the menu with data for each save slot,
    // updating each slot with corresponding character data if available
    public void ActivateMenu()
    {
        // Retrieve a dictionary of all profiles and their corresponding character data from SaveManager
        Dictionary<string, CharacterData> profilesCharacterData = SaveManager.Instance.GetAllProfileGameData();

        // Iterate over each save slot present in the menu
        foreach (SaveSlot saveSlot in saveSlots)
        {
            // Initialize a variable to hold the character data for the current save slot
            CharacterData profileData = null;

            // Try to get the character data associated with the current save slot's profile ID.
            // If successful, profileData is set; if not, profileData remains null
            profilesCharacterData.TryGetValue(saveSlot.GetProfileId(), out profileData);

hard viper
#

!code

tawny elkBOT
rigid gull
#

            // Update the current save slot with the retrieved or default character data
            saveSlot.SetData(profileData);
        }
    }
    public void CreateSaveSlot(string profileId)
    {
        // Instantiate a new save slot from the prefab
        GameObject newSlot = Instantiate(saveSlotPrefab, saveSlotContainer);
        // Assign a unique profile ID to the new save slot
        SaveSlot saveSlotScript = newSlot.GetComponent<SaveSlot>();
        saveSlotScript.SetProfileId(profileId); // Assign the profile ID
        saveSlots = this.GetComponentsInChildren<SaveSlot>(); // Update the saveSlots array
    }
}```
#

hmm hmm. I need to walk through this from step one

#

including my main menu script

hard viper
#

you should have a few classes

rigid gull
#

and find out what is happening. cus at this point ive just been following a tutorial and now im really confused lol

hard viper
#

one class is the simple serialized save data. One class should be in charge of managing different save slot files (Writing to, openning them, reading them, organizing them...). One class connects that information to UI, and puts requests to the save manager to query contents or change save data

#

a single save slot class should NOT be a monobehaviour

rigid gull
#

@hard viper want to hop in a voice channel?

hard viper
#

nty

#

I'm just pointing out that I think you need to break this up a bit, and that is why you are confused.

rigid gull
#

well, i have a save slot, a save slot menu, a data serializer, a character data, a save manager, and a main menu.

#

all different classes

hard viper
#

well, what is the issue you are having?

rigid gull
#

i just need to walk through my scripts again and find the problem as it occurs. Sorry. Right now I can barely identify what the issue is. I dont understand how to get the save slot menu to work, that's generaly my problem. like i said data serialization is working, my save manager saves and loads data correctly. the problem is finding out how to get my main menu script, and my save slot menu script to play nicley togeather.

#

are save systems some of the most complex parts of game systems?

#

this is definatly the most coplex thing ive done. but this is my first game lol.

leaden ice
#

and lining up your order of initialization of the game world when loading a save

rigid gull
rigid island
#

Don't you hate when in unity you have to fight against the engine for such basic stuff 😦

heady iris
#

or that you don't know how to write data to a specific save slot?

rigid island
#

Only way I was able to fix it is to copy-paste the underlying code of GetMousePointerEventData, ProcessMove, and ProcessDrag into that custom FirstPersonInputModule (instead of just calling the base methods), then removing the code that disables functionality when Cursor.lockState == CursorLockMode.Locked.

#

No idea

eager steppe
rigid island
#

no idea why now my cursor is visible and flickers (im guessing its fighting visible = false)

eager steppe
#

is the script the same script linked in the forum? guess i could take a look through that i guess

rigid island
#

they said Only way I was able to fix it is to copy-paste the underlying code of GetMousePointerEventData, ProcessMove, and ProcessDrag into that custom FirstPersonInputModule
but this is what exactly says in script

rigid island
#

just tryina get my windows XP working ingame 😦

eager steppe
rigid island
eager steppe
#

I'm not quite sure. Unless you're setting the activity of your cursor with the cursor lockstate, maybe it could help..?

eager steppe
rigid island
heady iris
rigid island
#

who knew OS would eventually be spyware and bloatware

eager steppe
#

why does Windows 11 constantly catch strays, this is crazy πŸ’€

#

after initial bloatware uninstall its fine :c

#

i hate this engine

heady iris
#

i'm a certified microsoft defender

#

kind of

#

but this is irrelevant lol

rigid island
#

macos > linux > windows

#

but seriously its so frustrating having to fight the engine's poor design for this stuff ..

knotty sun
eager steppe
#

Does anyone know why using Scale is just... being weird?

Basically, I use two arrows to change the scale OR position of a target. It depends on what mode I'm currently in. The axis I use are X and Y.
I also use 1 ring on the Z axis to change the rotation of the target.
This is the scale function, which works correctly if I haven't changed the rotation of the target:

void EditScale(Ray camRay, float planeDist)
{
    // Calculate the change in mouse position
    Vector3 currentMousePosition = camRay.GetPoint(planeDist);
    float delta = currentMousePosition.y - initial.y; // Use the y component for vertical movement

    // Calculate the scale factor based on the mouse movement
    float scaleFactor = 1f + delta * ScaleMultiplier; // You can adjust the multiplier based on your preference

    // Apply the scale based on the axis
    if (axis == Axis.X)
        Thing.transform.localScale = new Vector3(initial.x * scaleFactor, Thing.transform.localScale.y, Thing.transform.localScale.z);
    else if (axis == Axis.Y)
        Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, initial.y * scaleFactor, Thing.transform.localScale.z);
    else if (axis == Axis.Z)
        Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, Thing.transform.localScale.y, initial.z * scaleFactor);

    // Update the initial position for the next frame
    initial = currentMousePosition;
}```
rigid island
eager steppe
#

However, if i rotate it, using this function:

void EditRotation(Ray camRay, float planeDist)
{
    // Calculate the change in mouse position
    Vector3 currentMousePosition = camRay.GetPoint(planeDist);

    // Calculate the rotation angle based on the change in mouse position
    Vector3 oldDelta = initial - Thing.transform.position;
    Vector3 newDelta = currentMousePosition - Thing.transform.position;
    float delta = Vector3.SignedAngle(oldDelta, newDelta, Vector3.forward);

    // Apply the rotation based on the axis
    if (axis == Axis.Z)
    {
        Thing.transform.Rotate(Vector3.forward, delta);
    }

    // Update the initial position for the next frame
    initial = currentMousePosition;
}```

Then, it just stops working. After rotating, if i try to drag an arrow, it just goes to the opposite side of the object. Here's the visualized issue:
eager steppe
rigid island
#

its like a 70s OS

knotty sun
#

children

eager steppe
knotty sun
#

small child

eager steppe
#

it isnt even my fault. i like old things

#

like uh

#

ok no its not old but its annoying because its old

#

assembly

#

6502 assembly specifically

rigid island
#

< big child at 30 πŸ₯²

eager steppe
#

i cannot imagine being thirty years old. it just sounds like something that just happens

rigid island
#

its all downhill from there xD

knotty sun
#

nah

rigid island
#

we get wiser but our body hates us

spring creek
eager steppe
#

CPM is just task manager?

knotty sun
#

CPM is what drives your windows computer if you did but know it

eager steppe
#

vroom vroom?

#

is tht not TPM? or am i thinking of the other thing that my computer just randomly has for no reason at all

rigid island
#

Having to lock a player just to control UI in FPS will be so ugly... why can't unity just allow this to work..

winter gale
rigid island
#

hopefully better music..

winter gale
#

yeah there is better music

#

quality

#

and also better sprites

rigid island
#

same shitty song but remastered

#

lol

winter gale
#

this game is on all versions on rhythm heaven

#

lemme show you the best one

rigid island
#

find a way to match the BPM

eager steppe
winter gale
rigid island
#

or use an audio analyzer and get the frequencies to determine where you want the hits (usually peaks like Kicks or Snares)

#

dynamic games do similar when you have custom tracks (ie AudioSurf, BeatHazard)

eager steppe
#

create an animation that throws objects out

spawn the objects on 60/(bpm) (and if you want, multiply that value by 1, 2, 3 or 4 to wait a certain amount of beats per throw)

but this is super important, minus the time it'll take to get to the player too, so that it'll get to the player on TIME

winter gale
#

im not like an expert or anything im sorta a beginner

#

so i dont understand stuff

#

just send a tutorial

rigid island
winter gale
#

yeah ik

#

i thought this was for any type of unity gamemakers sorry

#

anyways lets move there

rigid island
#

I guess would it be better just raycasting onto a collider on screen to determine if you're on UI interaction and only then enable the FirstPersonInputModule ?
Seems like ugly workaround , if anyone knows a better way I'd love to hear it

neon plank
#

In Unity 2022, how can I get the current NavMeshLink that an NavMeshAgent is traversing?
The NavMeshAgent.currentOffMeshLinkData.owner is only available in >= 2023. In 2022 there is NavMeshAgent.currentOffMeshLinkData.offMeshLink but that is for OffMeshLink, bot NavMeshLink. ΒΏHow do I get the second one?

carmine gust
#

why am I just now getting this, and how can i remove collab?

#

fixed

somber nacelle
#

not a code issue, but the answer is to stop using collab and switch to plasticSCM instead (or some other version control)

carmine gust
#

yes i knew that

#

i just forgot how to get to collab settings to remove it

somber nacelle
#

was your google not working?

carmine gust
#

couldnt find a solution

#

found it on my own

#

none of these helped

somber nacelle
#

next time don't skip the first result that tells you how to turn it off form the Services window

#

but this is still not code related

carmine gust
#

mb

calm talon
#

how would you instantiate a gameobject at the point of a particle colliding with a gameobject in the scene?

calm talon
#

I've tried something like this:

    private void OnParticleCollision(GameObject other)
    {
        List<ParticleCollisionEvent> pColls = new(); 
        system.GetCollisionEvents(other, pColls);
        for (int i = 0; i < pColls.Count; i++)
        {
            GameObject acid = Instantiate(acidPool, pColls[i].intersection, Quaternion.LookRotation(Vector3.forward, pColls[i].normal));
            acid.transform.parent = gameObject.transform;
            acidPools.Add(acid); 
        }
    }

however the code ends up killing performance

rigid island
#

you're creating a new list every particle collision

#

thats already huge garbage

#

and also how many particles do hit ?

calm talon
#

I've got it set to 30 total

rigid island
#

btw see how unity caches the list

calm talon
#

can't you just do

public List<ParticleCollisionEvent> collisionEvents = new();
rigid island
#

yes

#

try cache first then keep iterating and profiling

#

also check how many are hitting

#

one time I had a blood splat that would draw decals on each splat, I ended up making thousands for some reason because forgot to delete once it hit

lean sail
rigid island
#

and also pool your acidPool (funny sounding)

#

dont use Instantiate

#

if you want perfomance

calm talon
last raven
#

is it possible to make custom audio effects that I can add to mixer groups?

#

I know I can add effect to source with OnAudioFilterRead but is it possible to do with mixer group like built-in effects

#

if I want to apply effect to all sources in a mixer group

cosmic rain
#

There's another result that seems promising if you Google custom dsp effects for unity.

last raven
#

seems like another thing that unity promised and never delivered because I can't find anything other than onaudiofilterread

#

unity native api doesn't seem to have anything other than some really basic stuff

solemn bridge
#

Hey guys. I am trying to position a line renderer the same origin and direction as my raycast. When the child object of the VR rig is at 0/0/0 it lines up correctly as you can see in the image (the blue line inside the green line is the ray being logged). However, when the object moves up and down the the line stays the same but the ray moves up. Does anyone know why this is happening? Here is my code.

tough gulch
#

i need help with an error, heres the error I need help with

spring creek
tough gulch
#

no

#

its not from an asset, its just one script by its own

spring creek
tough gulch
#

yeah

spring creek
# tough gulch yeah

You're really making it hard to help lol.
Yeah what? There is a namespace?

Can you show the script maybe?
Show where the error is coming from? Do you have errors in the compiler?

tough gulch
#

no there is no errors in the compiler

#

and yes there is a namespace

spring creek
tough gulch
#

ok

spring creek
#

Do you have FaskIKFabric anywhere in your own scripts?
If you do, do you have using FastIKFabric; at the top?

tough gulch
#

no

spring creek
#

Well, without getting complete information, all I can say is that either there are compiler errors, or you are trying to use FastIKFabric without using the namespace.
The file name and class name seem to match, and that is all I was able to confirm

leaden ice
#

an appropriate position here would be like:
returnPosition.position + returnPosition.forward * 5

solemn bridge
quartz folio
#

this isnt unity
Then it shouldn't be in this Discord

ionic ruin
#

internet mods are wild in their reasoning skills

quartz folio
#

yeah it's wild that the Unity discord only takes Unity questions

rigid island
#

Anyone know why my texture comes out black?
:\

    if (newTex == null)
        newTex = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBAFloat, 8, false);
    Graphics.CopyTexture(renderTexture, newTex);
    met.mainTexture = newTex;```
quartz folio
#

Is the RenderTexture marked as isReadable?

rigid island
#

Random Write?

hexed pecan
#

enableRandomWrite = true; when you create it

hexed pecan
#

Random Write in the inspector

rigid island
#

I tried it, still doesn't put RT on texture :\

craggy veldt
#

happens on android only ? try change the depth stencil format to D16-something(forgot which one)

rigid island
#

no I'm not on mobile

#

didn't do much though

craggy veldt
#

yeah, thought it was android, had similar issue awhile back and that fixed it

rigid island
#

not sure what I could be doing wrong :\

hexed pecan
#

And some other texture formats like RGBA32

#

Though it looks like it should work

rigid island
#

i read 3 threads and all said the same, I just copied

#

yeah basically If i change color formate I get this

#

then i have to go on this thread I found that tells me each format group πŸ˜†

hexed pecan
#

I have used this, try itcs public static Texture2D RenderTextureToTexture2D(RenderTexture renderTexture) { RenderTexture activeOriginal = RenderTexture.active; int w = renderTexture.width, h = renderTexture.height; Texture2D tex = new Texture2D(w, h, renderTexture.graphicsFormat, 0); // I had 'Texture2D tex = new Texture2D(w, h);' but you probably need the format here RenderTexture.active = renderTexture; tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); tex.Apply(); RenderTexture.active = activeOriginal; return tex; }

rigid island
#

I will try it. I was just wary because of that thread said ReadPixels is expensive since it has to put data from gpu back to cpu

hexed pecan
#

Yeah it's probably not very fast, I used it to save a rendertexture to a texture2d as a sub asset

#

So it needs to be on CPU

rigid island
#

I was going to use it almost every second or less continiously :\

hexed pecan
#

Try it just to test, maybe it will give some clues on what's wrong

rigid island
#

will do!

rigid island
# hexed pecan Try it just to test, maybe it will give some clues on what's wrong

would this be it ?

   private Texture2D RenderTextureToTexture2D(RenderTexture renderTexture)
   {
       RenderTexture activeOriginal = RenderTexture.active;
       int w = renderTexture.width, h = renderTexture.height;
       Texture2D tex = new Texture2D(w, h, renderTexture.graphicsFormat, 0); // I had 'Texture2D tex = new Texture2D(w, h);' but you probably need the format here
       RenderTexture.active = renderTexture;
       tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
       tex.Apply();
       RenderTexture.active = activeOriginal;
       return tex;
   }
   private void Start()
   {
       newTex = RenderTextureToTexture2D(renderTexture);

       yield break;
   }```
ionic ruin
# quartz folio yeah it's wild that the Unity discord only takes Unity questions

the code is nearly identical to what it would be in a unity script, and the problem it solves is very common for beginners to face in unity. it harms no one and is relevant enough that it can only be helpful. a reasonable person would go "yeah that's not exactly unity, but anyone doing unity game dev could benefit from looking at it or give a solution that could help unity users reading it.". It is weird for you to be so fussy about this

#

there are not many game dev servers

#

thats why i went here for help

hexed pecan
#

Or replace the format with whatever you want

#

But try that first and see if its still black

rigid island
#

still black

ionic ruin
#

stanford prison experiment

rigid island
hexed pecan
#

Yes but I create my rendertextures from script

rigid island
#

Ahhh..

#

the Start method

#

it don't likie

#

put it in Update and it works

#

so maybe the other thing works too..

#

wow..cannot believe it was this simple..

#

2 hours gone

#

ty @quartz folio @craggy veldt @hexed pecan
apparently It needed to be in at least Update and not Start..

hexed pecan
#

Makes sense, Start runs before Update so your RTex hasn't rendered yet

rigid island
#

yeah still getting familiar how the gpu renders πŸ˜…

hexed pecan
#

You could probably just WaitForEndOfFrame from Start and then do the texture copy

#

So that it renders first

rigid island
quartz folio
#

To be clear, you can make Start a coroutine

rigid island
#

Oh yeah I had it like that but changed to void after thought coroutine was messing with it

quartz folio
#

Oh, sorry, misread

rigid island
#

all good !

#

really intellisense..??

#

you couldn't tell me this 2 hours ago

#

wtf happening

storm thorn
#

Hello! just asking if I save via player prefs, do I need to save it on firebase too? or other database

rigid island
leaden ice
storm thorn
storm thorn
leaden ice
#

playerprefs is saved locally on the device

rigid island
leaden ice
#

if you want it somewhere else, it needs to go somewhere else

#

An online game with currency definitely needs to save currency in the cloud somewhere

storm thorn
#

What if we don't have an online purchase? but just simple shop where the user can change their characters if they buy

leaden ice
#

it's entirely up to you

#

if you care about cheating etc

#

it's your game

storm thorn
#

Their bought characters when they log out, will it still be there when they logged back in? or the number of coins they have

leaden ice
#

That's entirely up to you and your code

#

and where you store the data

storm thorn
#

We only store it via playerprefs

leaden ice
#

then it will persist as much as playerprefs does

storm thorn
#

okay! Thank you so much! 😊

crimson trellis
#

Anyone knows how to fix? It only print ok good 1 and line 41 have a null reference

#

T is Touch

#

Does that mean Touch cannot be stored as object?

fervent furnace
#

i tried to cast list<int> to list<object> in online compiler and it gives error directly, i dk why in your case your code still run....

leaden ice
#

Whatever that thing is it's not a baseTUI<object>

fervent furnace
#

it even give out an error, and i have no idea why his code doesnt result on any exception

glass fossil
#

This looks like a console app mixed with unity.

quartz folio
#

Where's the Unity part...

dense swan
#

Hello, I'm trying to make Steam Achievement. but it said Steamworks is not Initialized.

The error is inside function TestIfAvailableClient()

InvalidOperationException: Steamworks is not initialized.
Steamworks.InteropHelp.TestIfAvailableClient () (at Assets/com.rlabrecque.steamworks.net/Runtime/InteropHelp.cs:34)
Steamworks.SteamUserStats.GetAchievement (System.String pchName, System.Boolean& pbAchieved) (at Assets/com.rlabrecque.steamworks.net/Runtime/autogen/isteamuserstats.cs:72)
AchievementManager.Start () (at Assets/__Source/Scripts/AchievementManager.cs:76)

I already have steam running, logged in with account that has the game, edit steam_appid.txt

what else do I miss?

rigid island
dense swan
dense swan
rigid island
dense swan
# rigid island hmmm well I'm not sure why are you attempting to use `Steamworks.SteamUserStats...

hmm.... looks like it's because I'm a lazy idiot. I was following this tutorial but missed the part that said attach the SteamManager script to a GameObject in your starting scene.

Medium

So, you’re working on your Unity game and you’re getting ready to release it on Steam. But the Steamworks API can be intimidating. It’s…

rigid island
#

i just usually look at the documentation

dense swan
# rigid island you got it working ? πŸ˜›

I'm not sure if it's working yet, but it doesn't throw error anymore.

I usually also look at documentation but for some reason I didn't do that this time. Probably because I got intimidated by this, and then proceed to find tutorial to hold my hand.

I'll read this for now. Thank you for the reminder. Now I'm gonna go hit myself with a broom.

peak raptor
#

Hello, I have a code block as follows.
Everything is working correctly but "ConnectionApprovalCallback" is never called, what could be the reason?

NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.OnServerStarted += OnServerStarted;
NetworkManager.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.OnTransportFailure += OnTransportFailure;
NetworkManager.OnServerStopped += OnServerStopped;

knotty sun
peak raptor
#

Also, my question is very logical. Each delegate works, one does not work, these delegates are related to each other.

primal wind
#

Is there a way to load an AudioClip without a coroutine? I need to load a .ogg on disk and i want to do that through a function to make it easier to use, doesn't matter if the game freezes for a bit

maiden junco
#

async void Start()
{
    // build your absolute path
    var path = Path.Combine(Application.dataPath, "Audio", "sounds", "myAudioClip.wav");
    
    // wait for the load and set your property
    CurrentClip = await LoadClip(path);

    //... do something with it
}

async Task<AudioClip> LoadClip(string path)
{
    AudioClip clip = null;
    using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.WAV))
    {
        uwr.SendWebRequest();

        // wrap tasks in try/catch, otherwise it'll fail silently
        try
        {
            while (!uwr.isDone) await Task.Delay(5);

            if (uwr.isNetworkError || uwr.isHttpError) Debug.Log($"{uwr.error}");
            else
            {
                clip = DownloadHandlerAudioClip.GetContent(uwr);
            }
        }
        catch (Exception err)
        {
            Debug.Log($"{err.Message}, {err.StackTrace}");
        }
    }

    return clip;
}

primal wind
#

That could work, thanks

ocean river
#

where can i find good c++ plugins? i want to try to avoid using unity's physics

solid chasm
ocean river
#

ah

#

i was actually advertising my own question

solid chasm
#

lol

solid chasm
ocean river
#

lemme read the code then

solid chasm
#

ok

ocean river
#

so is this script activated when you want to change skin or something

#

cause that script will only execute once if it starts

solid chasm
#

yes it activated when change skin

#

when i click here

ocean river
#

oh ok
im not too intermediate myself just saying

solid chasm
#

I'm new on code

ocean river
#

maybe try doing Debug.Log() and see if it even reaches that code

ocean river
#

damn

#

so its the code in start not working or that function

solid chasm
#

debug its here

#

idk if good here

ocean river
#

sorry cant help you with 2d or playerprefs

solid chasm
#

Okay

ocean river
#

but that means enableselectcharacter is disabled

solid chasm
ocean river
#

yeah idk try changing it i guess

cold egret
#
  • I'd like to get the logarithmic rolloff curve from audio source without having an instance of audio source. I.e. some way to make one on the fly, through a constructor or a static method. Anything on this?
ocean river
#

bezier curve? no idea

eager steppe
#

Hey y'all, I have an issue where, after rotating the object with the circle, trying to scale it up with the arrows gives a weird 'flipped' result.

I don't know if it is because my calculations are weird, but this is what I'm experiencing:

#

This is the function to scale up, and this is put on a script that is on each arrow:

void EditScale(Ray camRay, float planeDist)
{
    // Calculate the change in mouse position
    Vector3 currentMousePosition = camRay.GetPoint(planeDist);
    float delta = currentMousePosition.y - initial.y; // Use the y component for vertical movement

    // Calculate the scale factor based on the mouse movement
    float scaleFactor = 1f + delta * ScaleMultiplier; // You can adjust the multiplier based on your preference

    // Apply the scale based on the axis
    if (axis == Axis.X)
        Thing.transform.localScale = new Vector3(initial.x * scaleFactor, Thing.transform.localScale.y, Thing.transform.localScale.z);
    else if (axis == Axis.Y)
        Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, initial.y * scaleFactor, Thing.transform.localScale.z);
    else if (axis == Axis.Z)
        Thing.transform.localScale = new Vector3(Thing.transform.localScale.x, Thing.transform.localScale.y, initial.z * scaleFactor);

    // Update the initial position for the next frame
    initial = currentMousePosition;
}```
#

Let me know if you need more code, but I'm bad at math and honestly don't know why this is happening πŸ₯²

heady iris
#

Don't you want to measure mouse movement along the direction the scale handle points in?

#

You're measuring vertically

#

also, you're using initial.x, initial.y and initial.z when calculating the scale

#

that doesn't make any sense

ivory pasture
#

how would i make a draggable object, collide with a rb2d, but not move the rb

heady iris
ivory pasture
#

yes

heady iris
#

I think 2D physics let you control whether rigidbodies apply force on a per-layer basis

#

I'm pretty sure I saw that before, at least..

open charm
#

Does Queue have a contain function?

open charm
#

sceneQueue.Contains(selectedScene)

#

like does this work

heady iris
#

is there a reason you can't just try it? sounds like you already have a queue :p

open charm
#

Ye i am

#

But im trying to find the return value rn

#

And like how to make it work so I thought id find like those site that contain the functions parameters

#

But I cant find one for some reason

heady iris
#

here's the documentation

#

For C# stuff that isn't Unity-specific, the Microsoft .NET documentation is what you want

#

One thing to watch out for is that some stuff only exists in newer versions of .NET

#

ones that Unity doesn't support yet

#

In this case, it's fine; this class has existed for ages

#

but I know that PriorityQueue isn't available to use in Unity, for example

#

(very different from a regular Queue)

heady iris
#

and also record the original scale

#

then, every frame, compute the delta and use that to compute a scale factor

#

and then set the current local scale based on that delta and the original scale

open charm
#
public string SelectRandomScene()
{
    string selectedScene = null;

    while (selectedScene == null || sceneQueue.Contains(selectedScene))
    {
        selectedScene = PlayMaps[Random.Range(0, PlayMaps.Count)];
        print(selectedScene);
    }

    Enqueue(selectedScene);

    return selectedScene;
}

public void Enqueue(string value)
{
    if (sceneQueue.Count >= maxQueueLen)
    {
        sceneQueue.Dequeue();
    }
    sceneQueue.Enqueue(value);
}
#

Sorry Im having a bit of a fever rn and maybe my brain is not braining but is there smth in my code that might cause an infinite loop

#

sceneQueue always starts with one element inside and the maxQueueLen is vurrently at 2 so Enqueue shouldnt break anything

#

And rn there is no error

#

It just freezes the game

fervent furnace
#

always bound the loop if you are not sure

open charm
#

bound?

fervent furnace
#
int iteration=100;
while(true&&--iteration>0){
  work;
}
open charm
#

oh ok

heady iris
#

basically, give up if it's stuck

open charm
#

Ye let me try it

heady iris
#

I would suggest logging whatever is going on

open charm
#

Ok so i found out whats the issue

#

But im not sure why it is

#

For some reason sceneQueue.Contains always returns true even if the element I randomly selected is not in there

pliant sapphire
#

Hi guys, I have a dialogue system in my game for npcs and it works like when distance is 2.5m or less and I press E it should pop up dialogue according to NPC Im talking to but for some reason distance keeps being 0 and when I press E it doesnt do anything. Here is DialogueManager script: https://hastebin.com/share/izoziwepew.csharp and here is NPC script: https://hastebin.com/share/ulaxoyekak.csharp

heady iris
open charm
#

Yes I found out why

#

another group member used the function elsewhere

#

So it caused an infinite loop since currently we have 2 maps only

#

And they both got loaded into queue

heady iris
#

Yeah, you should add a safeguard for that

#

If the number of available maps is less than or equal to the number you want to keep in the queue, throw an error

swift falcon
#

What's the most efficient logic for when a menu has for example 14 items but only 10 buttons, when you scroll above the max number of buttons all the buttons change the item they hold. Like an inventory

maiden lodge
#

Vivox is an offical unity package tough

icy herald
#

I'll need to add some force along the rigidbody x-axis to the player for wall jumping, but my code for acceleration and deceleration is interfering with this. Any ideas?

#

Full code. I'll trying to do this with AddForce function, but that shit doesn't want to work

hexed pecan
#

If you still want some control while the walljump timer is active, you can use AddForce, or velocity with MoveTowards

pliant sapphire
hexed pecan
pliant sapphire
#

problem is that this video screen recorder only lets me record in wmv

#

no option for mp4

hexed pecan
#

@icy herald It's not very complex, have you made a timer before?

icy herald
hexed pecan
#

What's that?

spring creek
pliant sapphire
hexed pecan
#

You should describe it even if we see the video

pliant sapphire
#

okay sorry

hexed pecan
pliant sapphire
#

so when I press any key to move(W,A,S,D) my character doesnt move he leans in that direction and he will then eventually fall...here is a pic when Im holding W:

hexed pecan
swift falcon
#
  • how to get ITilemap

Argument 2: cannot convert from 'UnityEngine.Tilemaps.Tilemap' to 'UnityEngine.Tilemaps.ITilemap'

pliant sapphire
fading cobalt
#

How do I deserialize json files with overlapping brackets?

hard viper
#

is there a way to make a tile sprite by composition? Like a tile which is the sprite for two tiles overlaid on each other?

spring creek
icy herald
spring creek
icy herald
round violet
#

i got a question, but first : "does anyone knows php ?", if yes my question could be more easily understood

#

in php you can evaluate something and choose bewteen two "things" depending of the result

somevar ? takeThisIfTrue : takeThisIfFalse
#

is there something similar in c# ?

knotty sun
#

exactly the same

round violet
#

oh

#

great :D

#

ty

fervent furnace
#

ternary operator

round violet
#

in some languages i had to make a function to imitate its behaviour

dusk apex
#

But it isn't as simple as a ? b : c

hexed pecan
round violet
dusk apex
#

You'd want an if statement over a ternary if that was your only goal. Ternary was meant to be used as var d = a ? b : cwhere there is a need for a return value

round violet
#

i would like to use it inside a new vector to avoid making many lines

hexed pecan
#

Yeah, you can use it in a vector constructor

icy herald
round violet
#

because depending of a enum im switiching what value to pick

dusk apex
#

Single line statements shouldn't be a goal but since you're using the return value, it'd be fine.

hexed pecan
round violet
#

but ty for the tip

eager steppe
#

Found my issues with the stupid scaling thingy just a second ago after actually reading my code :3

Okay, does anyone know how to calculate the mouse delta, relative to the current axis i'm moving, while also relative to the current rotation of the obejct?

For example, this is an object at 0 on the Z, and the blue arrow is facing the right way. I can calculate the delta correctly on the z using:

if(axis == Axis.X)
delta = currentMousePosition.x - initial.x;```
But as soon as i go 180 on the Z, the blue arrow faces the left way. The delta is still being calculated correctly, but I know that I need to invert the delta.

I don't want to hardcode this every 90 degrees, as this would just be inaccurate. So... how would I handle this?
icy herald
hexed pecan
eager steppe
round violet
# round violet its also for my brain <:BlobFishyCookie:875470068086104124>
transform.position = new Vector3(
                                            (_movement == SpeedTextMovement.playerX ? _player.transform.position.x : transform.position.x),
                                            (_movement == SpeedTextMovement.playerY ? _player.transform.position.y : transform.position.y),
                                            transform.position.z
                                 );

this was the goal
(a lot of other things will be added in the futur so rn its quite simple

dusk apex
round violet
#

?
its an enum

dusk apex
#

0.1f == 1f/10f can yield false

round violet
#

well SpeedTextMovement is an enum so i am not comparing floats ?

eager steppe
dusk apex
#

Unless playerX and playerY were assigned said values specifically and not calculated.

dusk apex
hexed pecan
#

It's an enum apparently

eager steppe
eager steppe
#

i would never compare floats. I don't know in what situation I would ever need to do that anyway

dusk apex
round violet
#

how do you guys name an enum ? just curious

#

or is it the "speed" that made you thought it was a float

hexed pecan
#

_movement really doesn't sound like an enum either

dusk apex
#
if (fish == Fish.Catfish)
    ...```
knotty sun
round violet
eager steppe
#

so using Axis.X, Axis.Y and Axis.Z makes everybody cry

round violet
hexed pecan
eager steppe
#

when really, I just don't want to compare strings. I want to use fancy dropdowns in the editor.

round violet
#

well this script is for my eyes only so if i can understand it im fine ig

heady iris
dusk apex
# round violet ```c# transform.position = new Vector3( ...

Every call to the position property of Transform will return a new Vector 3. An alternative to this is to cache and modify a single Vector 3 then reassign it back using the position property.cs var position = transform.position; if (_movement == SpeedTextMovement.playerX) position.x = ... if ... position.y = ... transform.position = position;

#

Could probably cache to bool results for x and y as well and avoid any of the operations above.

rigid island
#

Anyone know this, for some reason Reading Colors on my new texture made from RT is not working(only reads 1 color and its gray?)
Any ideas what could be the issue ?
The colors are properly read on my other color texture

heady iris
#

GetPixelData returns raw data

#

It's not decoded into a Color

rigid island
#

this one?

heady iris
#

I'm pretty sure you can use any type you want -- I see you picked Color32 there

#

It's possible that's the wrong type for your texture

rigid island
#

its a TextureFormat.RGBAFloat, is that different ?

heady iris
#

Definitely

#

Color32 is 8-bit RGBA

#

So you're trying to reinterpret 32-bit floats as bytes

#

It'll give you gibberish

#

Color might work

#

since that's RGBA 32-bit floats

rigid island
#

ah shoot

#

I see

heady iris
#

So it would work fine with RGB8 images

#

maybe

#

those aren't RGBA

rigid island
#

unfortunatly var pixelData = newTex.GetPixelData<Color>(0);
just give me black

#

same 1 element tho

heady iris
#

Color might not be a valid choice at all

rigid island
#

is there anyway to convert this texture to rgb8

heady iris
#

So which texture is being read from there?

#

The one on the left?

rigid island
#
   newTex = new Texture2D(
       renderTexture.width,
       renderTexture.height,
       TextureFormat.RGBAFloat,
       0, false);

   Graphics.CopyTexture(renderTexture, newTex);
heady iris
#

Try asking for floats and see if the values make any sense

rigid island
#

if I dont put RGBAFloat there CopyTexture gives mismatch error so thats not an option

heady iris
#

so this is not the render texture you're copying from

#

that's just a texture you had that works correctly

rigid island
#

sorry

heady iris
#

That would let you change the format, yeah

#

If you want to keep using Color32, that's your way

#

RGBA32 SFloat should be four 32-bit signed floats

#

(big!)

#

yeah, 128*128*16 is 262KB, and I guess mipmaps add some extra size

rigid island
#

so i would need to use sfloat ?

heady iris
#

If you want to use Color32, convert it to whatever has been working for you so far

heady iris
#

I suspect that's going to give you the next pixel's red channel in the alpha

rigid island
#

hopefylly nothing gets smashed xD

heady iris
#

then the next entry in the native array will be GBRG, then BRGB, then RGBR, ...

#

GetPixelData doesn't care what the actual encoding is, AFAIK

#

It just reinterpets the memory as whatever type you give it

#

That's why you got this funny color

rigid island
#

Ahh

heady iris
#

is this really correct either?

#

notice the random alpha values

#

the order also doesn't make sense to me

rigid island
#

yeah the alpha noticed were strange

#

but maybe cause im only using 1 of the pixel and prob grabing an edge where its like Filtered or some weird effect in unity

#

like Filtering

heady iris
#

If you just want color data, without worrying about the format, use GetPixels

heady iris
#

but that should throw an error

#

Actually, did you calculate an offset into that big 9-color image?

#

Oh yeah, that's exactly what happened

#

Notice how dark gray has a low alpha

#

Red has 100% alpha

#

Green has 0%

#

You interpreted RGB8 data (3 bytes per pixel) as Color32 (4 bytes per pixel)

#

there might have been enough extra space for that to work out mostly correctly

rigid island
heady iris
#

oh, right, you sent code

#

🫠

#

okay that makes sense

#

I was wondering how you didn't go out of bounds at the end

heady iris
#

and interpreted those four values as RGBA

rigid island
heady iris
#

It's slower, I guess

#

but that would get around this hackery

rigid island
#

is this wrong format?

     var newtex = new Texture2D(
         renderTexture.width,
         renderTexture.height,
         TextureFormat.ETC2_RGBA8,
         0, false);```
heady iris
#

I don't know a lot about texture formats tbh

#

TextureFormat.RGB24 sounds like it would match your existing data

rigid island
heady iris
#

but you're also interpreting the existing data wrongly

#

so it's a wash lol

#

you could make structs that store either bytes or floats in the correct order

#

you might need to add attributes to make the compiler respect the layout you specify

rigid island
#

I was gonna do the hacky way and just put all their alphas to 1 xD

heady iris
#

then you could ask for pixel data in the appropriate format

heady iris
#

imagine you get to the border between two colors and you're not aligned correctly

#
public struct ColorRGB {
  public byte red;
  public byte green;
  public byte blue;
}
rigid island
#

I'm mainly trying to average these colors if thats makes sense

heady iris
#

I forget the attributes you need to force this to be laid out exactly as specified in memory

#

haven't done that before

#

of course, reinterpreting the colors yourself is probably just as expensive as letting Unity do it

#

although, I guess you can avoid allocating an array

rigid island
#

yeah these colors thing is confusing as hell

heady iris
#

well, you're trying to directly interpret texture data

#

and there are a lot of ways to store texture data

#

just remember that you will not get an error for using the wrong data type with GetPixelData

rigid island
#

because it takes nativearray?

heady iris
#

well, not strictly

#

but it is true that NativeArray is a way to directly expose native memory to your code

#

It only works with unmanaged types, because you don't have the C# runtime keeping track of references and stuff

#

It's like reinterpreting a char * as an int * in C

#

same memory, different view

rigid island
#

would be better if I just use ReadPixels?

heady iris
#

i'd just use GetPixels and profile it

#

interesting: you can't use GetPixels on a crunch-compressed texture

rigid island
#

will do that actually

rigid island
# heady iris i'd just use GetPixels and profile it

hmm any reason why I would get 90000

public static Color[] ReadPixelColors(this Texture2D texture)
{
    Color[] cs = texture.GetPixels();
    for (int i = 0; i < cs.Length; i++)
    {
        cs[i].r = cs[i].a;
        cs[i].g = cs[i].a;
        cs[i].b = cs[i].a;
        cs[i].a = 1.0f;
    }
    return cs;
}```
#

I can't even scroll it crashes the window editor xD

twin sigil
#

I have a problem with my AI movement system. I recently rewrote my movement system to physics based, because when I moved the characters with transform they bugged across obstacles. I solved this issue with physics but when I have a lot of characters instantiated the game instead of lagging, gives higher speed to all characters moving with physics. Does anyone knows how to fix this?

//Update
private void Update()
{
    //Get All Enemies
    List<GameObject> enemies = new List<GameObject>();
    enemies.Clear();
    Component[] humanoids = Humanoids.GetComponentsInChildren<Component>();

    foreach(Component hum in humanoids)
    {
        if (hum.gameObject.CompareTag("Enemy"))
        {
            enemies.Add(hum.gameObject);
        }
    }

    //Get The Closest Enemy
    if (enemies.Count != 0)
    {
        Target = enemies.OrderBy(enemy => Vector3.Distance(transform.position, enemy.transform.position)).FirstOrDefault();
        Vector3 TargetDirection = (Target.transform.position - transform.position).normalized;

        //NewPosition
        Vector3 newPosition = lastPosition;

        //Move Towards Target (Physics)
        newPosition = TargetDirection * Speed * Time.deltaTime * 100f;

        if (Vector3.Distance(transform.position, Target.transform.position) > 1f && Vector3.Distance(transform.position, Target.transform.position) < 30f)
        {
            rb.velocity = new Vector3(newPosition.x, rb.velocity.y, newPosition.z);
        }
        else if (Vector3.Distance(transform.position, Target.transform.position) >= 30f)
        {   
            animator.SetBool("IsMoving", false);
            return;
        }

        //............

        //LastPosition
        lastPosition = newPosition;
    }
    else
    {   
        animator.SetBool("IsMoving", false);
    }
}
hard viper
#

my unity build caps frame rate to 60 FPS. is there a way for me to get some metric to see how much time is left between frames in dev build?

solemn bridge
#

Unity Profiler

hard viper
#

profiler works in build?

#

I thought it was unique to editor mode?

solemn bridge
#

Why does it need to be in build

#

the same delays will be in editor

rigid island
solemn bridge
#

Do you want it capped at 60?