#archived-code-general

1 messages ยท Page 232 of 1

polar marten
#

there's no solution for this

#

i am sorry

#

simply do not align

radiant marten
polar marten
#

then you will have no issues

radiant marten
#

everything is solved right there

polar marten
radiant marten
#

that's only because I'm very zoomed in and slowed the movement down

#

to show that pixels are properly aligned globally

polar marten
#

hmm, whereas in the earlier screenshot, where you did not align

#

i didn't really noticed the alignment zoomed out

radiant marten
#

unlike the example where the camera is rotated:

polar marten
#

everyone will notice the movement pacing issues

#

my subjective opinion, which is the right opinion, is that the movement pacing issue at normal speeds is going to be a lot worse than non-alignment at normal zooms

radiant marten
#

it's not though? I'm not sure why no one is listening to the fact that rotating the world solves all of my issues with pixel alignment

#

I don't need help with that

polar marten
#

i mean your background grid is anti aliased, and the pixels aren't square...

radiant marten
#

I need help finding a way to resolve workflow issues

polar marten
radiant marten
#

I'm not asking for help with that

polar marten
#

that are objectively a lot more noticeable

#

i can only help you with objectives that make sense. it doesn't make sense to gain pixel alignment in exchange for really bad movement

#

like i said, you cannot resolve both simultaneously with naturalistic physics

#

i feel like i am repeating myself. i have shipped a lot of pixel art games. i am trying to help you

#

including in dimetric views, using naturalistic physics

radiant marten
#

I'm sorry, but you're focusing on the wrong details that I'm asking for help with

dull glade
#

How do I make my ship take damage from bullets but not react to the physics

polar marten
#

the shader will not help

radiant marten
polar marten
#

the shader will not align one art against another

radiant marten
#

I don't need a shader to align art

somber nacelle
radiant marten
#

I'm asking for how to rotate the world in a way that does not effect game objects or scripts. Shaders can do that so that's my logical first idea but I'm not sure how to achieve that

polar marten
#

gb studio went very viral

swift falcon
radiant marten
#

there's a lot of things I can't share due to NDA, but there's a reason I have chosen the things I have done, and a lot of it involves integrating with a 3d world and 3d effects

dull glade
swift falcon
#

trigger / none colliding

somber nacelle
polar marten
#

@radiant marten he doesn't align

#

actualyl there's a different user who is authoring an SRP

#

but has no motion lol

#

for reasons that are clear to me

hidden flicker
#

How could I run a method continuously once called, then stop running once it's over? (Eg. ChangeFov() is called, it runs until the fov is at the desired value, then stops running)

swift falcon
#

invoke repeating then break on accept

hidden flicker
hidden flicker
#

Thank you, although it needs to run with parameters

swift falcon
#

or tbh you could just use the OnValueChanged on the fov slider if it has it

leaden ice
#

For example:

IEnumerator SetFov(float target) {
  while (theCam.fov != target) {
    theCam.fov = Mathf.MoveTowards(theCam.fov, target, speed * Time.deltaTime);
    yield return null;
  }
}```
swift falcon
#

or do the professional approach and put everything in an if else statement in Update ๐Ÿ˜Ž

leaden ice
#

Or use DOTween / any other tween library

vestal geode
#

Application.targetFrameRate doesn't seem to carry over to a windows build, is it meant to?
I could also use vsync options but I'm not sure if that can be used to get a specific target framerate
I'm looking for just a hack to mitigate wild framerate dependencies before they can be fixed properly

leaden ice
#

it also gets overridden by vSync

vestal geode
finite prawn
#

NullReferenceException: Object reference not set to an instance of an object
EnemyMovement.Update () (at Assets/Scripts/EnemyMovement.cs:26)

I am getting this error and I think the Start() function in this subclass is causing which it, because if I remove it, it works fine, which I very much do not understand

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

public class LeapingEnemyMovement : EnemyMovement
{
public float leapForce = 20f;
public float startDelay = 1f;
public float repeatInterval = 1f;
private void Start()
{
// InvokeRepeating("Leap", startDelay, repeatInterval);
}

/*
private void Leap()
{
    GetComponent<Rigidbody2D>().AddForce(relativePlayerPosition.normalized * leapForce);
}
*/

}`

also how do i format code in discord

tawny elkBOT
leaden ice
knotty sun
finite prawn
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{
    private Transform playerTransform;
    protected Vector2 relativePlayerPosition;
    protected Rigidbody2D rb;
    public float moveSpeed = 20f;

    // Start is called before the first frame update
    void Start()
    {
        // Get the transform component of the player
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;

        // Get the rigidbody2d component of this
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        // Calculate the relative position of the player
        relativePlayerPosition = playerTransform.position - transform.position;
    }

    private void FixedUpdate()
    {
        rb.AddForce(relativePlayerPosition.normalized * moveSpeed);
    }
}

the content of update is line 26

leaden ice
#

it's becauxse you're doing playerTransform = GameObject.FindGameObjectWithTag("Player").transform; in Start but when you add Start to the child class that means the parent Start won't run anymore

#

the way to fix this is to use proper C# method overriding

#

e.g. the parent class should do protected virtual void Start() and the child class should do cs protected override void Start() { base.Start(); // Call the base version of Start // the rest of the child class Start code }

finite prawn
#

i think he cant find the start method of the base class

leaden ice
#

the parent class should do protected virtual void Start()

finite prawn
#

sorry didnt see that also what is virtual

leaden ice
#

virtual allows it to be overridden

finite prawn
#

tsym

agile rock
#

Hello, I have a question. Some players of our games reported a bug that after some time spending in our game the games stop working. We received a logs with that bug reports and we find this (screenshot). Can someone please tell me if this is memory leak or something bad?

#

This is in build (game is on steam). We have no clue what cause this problem ;/ any help will be very helpfull โค๏ธ

leaden ice
hard viper
#

i would only even start worrying about memory leaking if your peak allocated memory is in the gigabyte range. youโ€™re still at most around 270 MB

#

youโ€™d need more info to diagnose

swift falcon
#

do you have a garbage collection system?

woeful depot
#

!code

tawny elkBOT
rigid island
#

Anyone know , how can we write a start rotation into a Keyframe of an animation ?
can't find it on google somehow..

#

Im trying to get a better video.. but basically when My chicken is dropped on the floor or in KO, I want animating from current resting rotation as the starting Keyframe so it doesn't flip from a direction is not facing

hidden flicker
#

My fov doesn't change even when the method is called

rigid island
hidden flicker
rigid island
#

ima take a wild guess at that sketchy != which is probably on a float

#

but should work ig, your condition doesn't seem it was true though

hidden flicker
#

weird

#

the IEnumerator doesn't even run, not just the while loop

rigid island
#

so much for

even when the method is called
lol

rigid island
#

how are you calling it anyway

hidden flicker
#

Alr

#

Here's the method that calls changefov though, everything else in it works fine

simple egret
#

Missing StartCoroutine to start a coroutine properly

hidden flicker
#

where/how would i add that

simple egret
#

StartCoroutine(camControlScript.ChangeFov(10, 1))

rigid island
#

You see the 3 DOTS

#

its tryina tell you

simple egret
#

Oh yep they're barely visible in light mode lol

rigid island
#

light mode ๐Ÿค•

hidden flicker
#

also i switched to dark mode thanks for the reminder lmao

#

last thing, how would I make it change to the desired fov over the given amount of time

#

i don't want to use lerp because it never fully gets to the actual value

simple egret
#

Look for these dots (they also appear as a white square in your vertical scroll bar on the right) often, they're analyzers that can simplify the code or fix bugs

rigid island
#

I would do this

#

just replace vector3.lerp to mathf.lerp

hasty canopy
#

In dotween you can use Dotween.To to interpolate between float values and use that value for whatever purpose over time

rigid island
hidden flicker
#

not familiar with those

rigid island
rigid island
hexed pecan
hexed pecan
rigid island
#

I was thinking of just animating it with code but had no idea how to make that flip look smooth so i just animated it

hexed pecan
#

Ffs, nevermind, it's editor only

rigid island
#

dang.. I saw that one but yeah noticed editor only

#

idk if this helps this is my animation

#

so he always starts on his back belly up

#

which looks unnatural ofc if I drop the chicken and falls on its head for example

hexed pecan
#

You could start a coroutine that lerps to a given rotation with a t value that decreases over time

thick socket
#
public class EnemySpawner : MonoBehaviour
{
    [SerializeField] List<GameObject> EnemiesToSpawn;
    [SerializeField] float spawnCooldown;
    TimeSpan spawnCooldownTimespan;
    [SerializeField] int numSpawns;
    int alreadySpawned;
    int spawnInt;
    void Start()
    {
        alreadySpawned = 0;
        spawnCooldownTimespan = TimeSpan.FromSeconds(spawnCooldown);
        SpawnEnemy();
    }

    void SpawnEnemy()
    {
        if(spawnInt >= EnemiesToSpawn.Count)
        {
            spawnInt = 0;
        }
        Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
        if(alreadySpawned < numSpawns)
        {
            WaitThenSpawn(spawnCooldownTimespan);
        }
        alreadySpawned++;
        spawnInt++;
    }
    public async void WaitThenSpawn(TimeSpan waitTime)
    {
        await UniTask.Delay(waitTime);
        SpawnEnemy();
    }
}

Should I be calling a wait to spawn more enemies like this? Or would you throw that into an Update loop?

simple egret
#

haha the last 20 frames

rigid island
#

he get chonky xD

hexed pecan
#
yield return new WaitForEndOfFrame(); // ?
chiken.rotation = Quaternion.Slerp(chiken.rotation, theRotation, t);```
rigid island
#

i'm bad at animating anway I might just try to replicate it in code but I want that same weirdness if possible lol

hasty canopy
rigid island
#

somehow I thought this rotation was Cool ๐Ÿ˜‚ ill prob just remake it..fkit

hasty canopy
simple egret
#

That poor animal, probably takes a good 15 G's with that rotation

rigid island
#

lmao and thats after he got smacked with a wooden staff

hasty canopy
rigid island
#

will do! ty for suggestions

hasty canopy
#

Select all frames and shift to right by like 15-30 frames

hexed pecan
#

Might have to uncheck Write defaults on the anim state too ๐Ÿค”

rigid island
#

basically I'm trying to mix Ape Escape with Chikens and farm lol

rigid island
#

I think when animator start , it overrides transform

hasty canopy
rigid island
hasty canopy
#

As long as there's nothing on early frames position and rotation shouldn't instantly snap

rigid island
#

oh wait i think its starting from here not at frame 0

hasty canopy
#

Show the animation?

rigid island
#

i try add empty animation event to it start at 0 but still same problem

hasty canopy
# rigid island poor fella

When you added the empty event, it did interpolate between initial position to 35th frame, but both positions happened to be exact same

#

Try to play animation again after changing its rotation to upright

hasty canopy
#

Also poor duck training to be an astronaut with those g force levels notlikethis

hasty canopy
# rigid island wdym by this

Have your duck be standing normally during 0th frame, and have the animation be played "normally" from 0th frame

rigid island
hasty canopy
#

It should work, I don't know why your animation is starting from 35th frame tho

hasty canopy
rigid island
#

let me try again maybe I unchecked the wrong one

rigid island
#

gonna jus try to animate it with code later instead.. animator is a pain to deal with

hasty canopy
#

Ayee animation looks good ngl, except the initial fall

rigid island
#

the initial fall is rigidbody

#

so its dynamic

hasty canopy
#

Ahh

#

Good luck good luck

rigid island
#

ty! ๐Ÿซก

left wasp
#

when i check the length by code it says 11

#

its 15 frames

rigid island
#

ah nvm its seconds

rigid island
left wasp
rigid island
#

whats anim

left wasp
rigid island
#

uhh this is why you show context of your code

#

thats 11 characters ๐Ÿ˜

#

you should've specified its a string

#

was wondering why it was Length and not length

#

strings are just array, so .Length is how many items in array of char

left wasp
rigid island
left wasp
rigid island
left wasp
left wasp
rigid island
left wasp
rigid island
#

do you have blend trees or any of that?

left wasp
rigid island
#

idk I never find using clip lengths very good

#

i just use Animation events

broken zodiac
rigid island
#

holy hell no

rigid island
tawny elkBOT
left wasp
broken zodiac
rigid island
left wasp
#

didnt even screenshotted it

rigid island
#

you want to run the function at end of animation ?

lean sail
left wasp
# rigid island swing function last wdym ?

so there is a swing animation when it ends it goes back to idle so i need the length of the animation to invoke the function that makes it go idle
i guess i can use events or just hardcode it

spring creek
# broken zodiac

Line 39 should be an error...
That startcoroutine isn't in a method

rigid island
#

perfect code, uses .tag instead of compare tag

spring creek
#

Also takedamage doesn't have an end brace

#

Ahhh that is why

lean sail
broken zodiac
#

๐Ÿ’€ why aren't errors coming up

spring creek
broken zodiac
spring creek
broken zodiac
#

Ah

#

So what should be changed?

#

My bad I'm Abit slow

spring creek
#

There are quite a few issues with the code. It'd be nice to see all of it in a paste site

broken zodiac
left wasp
#

takes screenshot with a phone ,has andrew tate as pfp, uses skull emoji, doesnt know what a brace is

broken zodiac
spring creek
left wasp
left wasp
spring creek
broken zodiac
naive swallow
broken zodiac
naive swallow
#

I can do both

broken zodiac
rigid island
#

mate you need to learn basic c# (stop relying on gpt its only doing you harm)

naive swallow
#

That's not something you should be doing without a good reason

broken zodiac
#

ive got no clue mate , i just did whatever worked

rigid island
#

coding isn't a guessing game lol

left wasp
#

it didnt work i guess

naive swallow
#

Also, I don't even see a question, I just see someone windmill slamming phone pictures of code with no question

broken zodiac
#

alright gimmie a second lemme explain

rigid island
#

also you have this

#

hidden

broken zodiac
rigid island
#

ohh probably coming from A*

naive swallow
#

Oh christ it's networked

lean sail
#

im surprised you're even using A* (and networking?) when you havent done even the basics of c#

#

is this your project

rigid island
#

might be the package failing to fetch updates?

naive swallow
#

Possible, maybe the package was added from a non-secure source?

#

If that's the case then it's probably not worth dealing with at the moment

broken zodiac
#

so since adding the A* pathfinding projectmy enemy has just started dying whenevr it collides with the player. Even though the player doesnt even have a weapon yet. The enemy is supposed to just keep trying to collide with the usersprite until the health of the user sprite is 0 or the user picks up a weapon and attacks the enemy sprite so its health reaches 0 and it destroys itself.

#

i hope this makes sense

thick socket
#
    async void SpawnEnemy()
    {
        EffectType effect = EffectPooling.instance.effectPools[effectType].Get();
        effect.transform.position = transform.position;
        effect.ClearParticlesAftertime(particleLength);
        await UniTask.Delay(animationLengthTimespan);
        if (spawnInt >= EnemiesToSpawn.Count)
        {
            spawnInt = 0;
        }
        Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
        if(alreadySpawned < numToSpawnEnemy)
        {
            WaitThenSpawn(spawnCooldownTimespan);
        }
        alreadySpawned++;
        spawnInt++;
    }
    public async void WaitThenSpawn(TimeSpan waitTime)
    {
        await UniTask.Delay(waitTime);
        SpawnEnemy();
    }
#

is there a way to interupt the "WaitThenSpawn" so if all enemies are dead)found with a isEnemies bool it stops the delay and immediately called SpawnEnemy

rigid island
#

cancellationtoken i think

broken zodiac
thick socket
#

will see if its horrible wrong ๐Ÿ˜„

rigid island
#

๐Ÿ˜ฎ

#

i would trust ms docs

thick socket
#

thats probably better ๐Ÿ˜„

thick socket
#

wonder if I should just not use the UniTask

naive swallow
thick socket
#

and use a different way to do it so I dont need to do cancellation tokens

rigid island
#

I just never used UniTask so not sure if that affects it

#

Unity has their own version of it basically

thick socket
#

Im thinking maybe just an old timer that checks each time in update might be better

rigid island
broken zodiac
#

@naive swallow does this help?

naive swallow
thick socket
#

this is how I should just do a basic timer right?

float elapsedTime=0;
public void Update()
    {
        elapsedTime += Time.deltaTime;
        if(elapsedTime >=spawnCooldownSeconds || GameManager.instance.EnemyList.Count == 0)
        {
            SpawnEnemy();
            elapsedTime = 0;
        }
    }```
#

or should I be storing initial time, and current time and doing math based on spawnCooldownSeconds

lean sail
broken zodiac
thick socket
naive swallow
thick socket
#

how would that be more consistent?

#

isn't that just
elapsedTime = elapsedTime - spawnCoolDownSeconds which would be doing math each time it checked that?

lean sail
broken zodiac
broken zodiac
thick socket
#

hadn't thought about that!

naive swallow
broken zodiac
naive swallow
broken zodiac
#

but at the start of the game the user doessnt pick up any weapons yet

thick socket
#
 void Start()
    {
        //disable the sprite
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
        spriteRenderer.enabled = false;

        GameManager.instance.EnemySpawnerList.Add(this);
        alreadySpawned = 0;
        animationLengthTimespan = TimeSpan.FromSeconds(animationLength);
        particleLength = TimeSpan.FromSeconds(animationLength + 0.5);
        first = false;
        spawning = false;
        elapsedTime = 0;
    }
    public void Update()
    {
        if(alreadySpawned>=numToSpawnEnemy) 
        {
            Destroy(gameObject);
        }
        elapsedTime += Time.deltaTime;
        if(!spawning && (elapsedTime >= spawnCooldownSeconds || GameManager.instance.EnemyList.Count == 0))
        {
            SpawnEnemy();
            elapsedTime = 0;
        }
    }

    async void SpawnEnemy()
    {
        spawning = true;
        //do animation
        EffectType effect = EffectPooling.instance.effectPools[effectType].Get();
        effect.transform.position = transform.position;
        effect.ClearParticlesAftertime(particleLength);
        //spawn enemy after delay
        await UniTask.Delay(animationLengthTimespan);
        if (spawnInt >= EnemiesToSpawn.Count)
        {
            spawnInt = 0;
        }
        Instantiate(EnemiesToSpawn[spawnInt], transform.position, transform.rotation);
        alreadySpawned++;
        spawnInt++;
        spawning = false;
    }
#

When the first enemy is spawning

#

a second one immediately spawns after

#

and I can't figure out why that is

#

adding spawning bool which should prevent that?

naive swallow
rigid island
thick socket
#

just not a fan of how I have to call Coroutines so async just feels better ๐Ÿ˜„

#

I could see how that might break it though thanks

naive swallow
hard viper
#

does making a method virtual make it take longer to run in any way?

latent latch
#

probably slower on the compile but otherwise doubtful

broken zodiac
naive swallow
#

that shows where it was called from

hard viper
#

do you know what a stack trace is?

broken zodiac
naive swallow
#

when you click on any console message

broken zodiac
simple egret
#

It's a bunch of lines that tell you where, and what exactly was executing at the time the exception/log was printed

#

Super useful stuff

thick socket
# broken zodiac sorry but what does this mean?

ex) click the error, CTRL+C and then it will print like this

NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <f94752164e14499c83c250d9839d9e96>:0)
naive swallow
broken zodiac
naive swallow
broken zodiac
#

wish i could programme using pseudocodenotlikethis

naive swallow
#

Well, let's see if it's TakeDamage that's doing it. Add this line to the top of TakeDamage:

Debug.Log($"{gameObject.name} is taking damage");

and see if it logs right before this destroyed line

broken zodiac
naive swallow
# broken zodiac

This seems to be unrelated. If the log is inside TakeDamage, then that's not the thing that's destroying it

rigid island
# broken zodiac

btw where did you get the A* from , did you get some outdated package or something lol

naive swallow
#

Now, put another log inside of MeleeAttack:

if (collision.gameObject.CompareTag("Enemy")) {
    Debug.Log($"{collision.gameObject.name} is being destroyed");
    Destroy(collision.gameObject); // Destroy the enemy
#

Keep the other log there too

broken zodiac
#

@rigid island

naive swallow
# broken zodiac

Did you just paste my half-a-function into somewhere in the script? Only the log should be added

#

the rest of it is showing you where to add it

broken zodiac
wispy herald
#

ive got a problem in my game, where im trying to use a box collider to start an animation on collision through script, but hes starting his animation as soon as i start running the game

naive swallow
#

Meaning the object is not destroyed

wispy herald
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimTrigger : MonoBehaviour
{
    [SerializeField] public GameObject player;
    [SerializeField] private Animator anim;

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject == player)
            anim.Play("LiamWalk");
    }
}```
broken zodiac
naive swallow
naive swallow
# wispy herald how

Debug Log should literally have been the first line of code you ever wrote

wispy herald
#

it was 3 years ago

#

i took a big hiatus

#

let me find how to write debug log1

broken zodiac
naive swallow
broken zodiac
naive swallow
#

Did you change anything other than putting in the log

#

and did you fix whatever you did that broke compilation the first time

broken zodiac
naive swallow
broken zodiac
naive swallow
broken zodiac
#

Got no other resources so chatgpt is my last and only place

naive swallow
#

Clear errors, run it again, see if it actually runs

broken zodiac
#

It's late now, I'll fix it at school tomorrow ๐Ÿ‘๐Ÿพ

#

Appreciate the help

wispy herald
#

its been so long

wispy herald
#

thank you

naive swallow
#

so you didn't even try to look it up

#

It's literally the first result for "debug log"

wispy herald
#

OH

#

i was looking up console

naive swallow
#

It's the first result for that too

wispy herald
#

i looked "how to write debug log in c#"

naive swallow
#

Second result

wispy herald
#

ok mb mb

#

it didnt get called

naive swallow
wispy herald
hard viper
# broken zodiac isnt it like a report?

You write:
Run() { MoveCharacter(); }
MoveCharacter() { rigidbody.MovePosition(nextPos); }

The way the program executes is: it tries to call Run(). In the middle of calling Run, it needs to call MoveCharacter(), so it freezes time right now, and opens a new level of the program. In this lower level of the program, it is going to go do whatever you do in MoveCharacter(). Then it reaches MovePosition, so it freezes everything in place again. Then we make ANOTHER level of the program, were we are doing MovePosition.
These are called stack frames.

#

Every "level" is a stack frame. A stack trace is printing everything we have on the stack right now.

#

If you are in the middle of executing MoveCharacter, the stack currently looks like
1 - MoveCharacter()
0 - Run()

#

If you are in the middle of executing MovePosition, the stack currently looks like
2 - MovePosition()
1 - MoveCharacter()
0 - Run()

#

Understand?

hard viper
#

go learn about the stack

#

it's core to how programs work

broken zodiac
#

Alright

hard viper
#

it's known as THE stack

#

A stack is a type of data structure. THE stack is A stack that is used for THE execution of the program.

broken zodiac
#

Also any advice on how to get really good at programming in a 6 month period (specifically Pseudocode and Python?)

hard viper
#

take a class

#

go to school

#

get an education

#

that's literally the reason schools exist

#

it's very easy to teach yourself to program like shit. Only a teacher can teach you how to program properly

broken zodiac
#

So basically I've got my exams in like 6 months and one of the papers requires a decent amount of coding, ik Abit of python and I've just recently started using unity with C# , Should I stick to Python or try convert to C#?

broken zodiac
hard viper
#

then why is your teacher asking you to code

#

the blind leading the blind

broken zodiac
loud wharf
#

If your teacher is only asking you to code.

broken zodiac
loud wharf
#

I'd suggest making a discord bot on python.

#

Or something you can readily demonstrate.

broken zodiac
hard viper
#

that is some bullshit. even my chemistry professors, when they asked for code, it was always something they and all the TAs could do with ease

loud wharf
#

You don't have to bend over to learn C#, if you already know python it should be able to get faster.

broken zodiac
loud wharf
#

Even more with Unity C# since they break some conventions.

hard viper
#

my man doesn't know about the stack. He needs more than a little bit of help.

loud wharf
#

Yeah that's why python is probably the easier way to go.

hard viper
#

that doesn't address the core issue

broken zodiac
#

We have to make a project, I chose a game, so it was either pycharm, unity or defold or unreal, and I chose unity

hard viper
#

if this is a programming class, then it is expected that your teacher is a master

broken zodiac
loud wharf
#

For a college school, it's an embarrassment to have a teacher to not even know programming on a programming class.

hard viper
#

the stack is a stack, but not every stack is the stack

#

anyway, you need to strike at the core issue: complain, or swap classes. This sounds like a shit class

broken zodiac
loud wharf
hard viper
#

my physical chemistry professors all had coding projects, which they could do like the back of their hand

#

no excuse

loud wharf
#

@broken zodiac If your deadline is like a month, you don't really have a lot of time to make a sizable game.
I'd probably think of a dyno or flappy bird clone which is easy to do in a day.

lean sail
loud wharf
#

And those games don't need unity at all.

broken zodiac
lean sail
#

I figured as much based on what you were saying

hard viper
#

anyway, back to this channel's original purpose:

I have my own infinite stack trace problem:
Stack overflow: IP: 0x159c00edd, fault addr: 0x7ffee7629ff8
Stacktrace:
at <unknown> <0xffffffff>
at ForestGraph1<TStored_REF>.SortTree (System.Comparison1<TStored_REF>) [0x00000] in <...>

This happens when I call this public method:

    Comparison<TreeNode> nodeCompare = new Comparison<TreeNode>((TreeNode x, TreeNode y) => compare(x.self, y.self));
    SortTree(compare);
}
protected virtual void SortTree(Comparison<TreeNode> nodeCompare) {
    rootNodes.Sort(nodeCompare);
    foreach (TreeNode node in EnumerateBackwardsGraph())
        node.children.Sort(nodeCompare);
}```

Before I had:
```public void SortTree(Comparison<TStored> compare) {
    Comparison<TreeNode> nodeCompare = new Comparison<TreeNode>((TreeNode x, TreeNode y) => compare(x.self, y.self));
    rootNodes.Sort(nodeCompare);
    foreach (TreeNode node in EnumerateBackwardsGraph())
        node.children.Sort(nodeCompare);
}```
and the same exact call was working fine. Any idea why I'm currently getting a stack overflow?
loud wharf
#

Ok, high school is definitely a different standard.

lean sail
# broken zodiac Nah I'm not at uni lol, highschool

your teacher might've never learned to code in the first place, i wouldnt blame them. they're just filling the position but its a shitty situation. If you can, swap to something easier. If you do want to do unity game dev in the future, then consider continuing with this project but really make it simple. You're trying to learn c# and unity at the same time, its a lot harder than learning unity while already knowing c#

broken zodiac
hard viper
#

high school is different. high school teachers are underpaid, and not like the top of their discipline. no offense to high school teachers

broken zodiac
loud wharf
#

He was probably put into that position.

hard viper
#

college professors literally do research. they have to be at the cutting edge just to do their base job properly. And then they teach as a side responsibility

#

sometimes you get instructors being brought in, but a real good school should have most of your professors being actually accomplished researchers.

lean sail
loud wharf
#

If you don't use unity here, I'd suggest making collisions out of circles.
Which is only determined by distance of object a to object b.

broken zodiac
#

I think I already do that

hard viper
loud wharf
#

Very simplified but suffice for a supposedly simple game.

hard viper
#

I thought I was calling the protected virtual method because type, but I wasn't

#

ty bawsi

broken zodiac
#

I'm just going to get good at Pseudocode and smash the CS exam in 6 months, then off to uni to study Finance and mathematics ๐Ÿ˜

loud wharf
#

U have 6 months before deadline?

broken zodiac
loud wharf
#

Ah.

hard viper
#

you don't get good at pseudocode lmao

#

you get good at regular coding, and then express yourself to real people using pseudocode

broken zodiac
hard viper
#

sir, you are extremely confused

broken zodiac
#

I disagree

hard viper
#

pseudocode isn't like a real skill that you hone

#

pseudocode is just a way to talk about a program

#

which doesn't work if you don't know shit about programming

broken zodiac
hard viper
#

pseudocode is not a programming language

latent latch
#

pseudocode is what math professors use when they are forced to teach a computer alg class

hard viper
#

pseudocode does not follow rules

#

because it isn't real code

broken zodiac
#

Well ig the whole UK education system is wrong cause it starts that in our syllabus

hard viper
loud wharf
# broken zodiac So far I've created a top down game, which a Has a character that can pick up di...

Anyways, here's a quick way to do this for the combat side of things.

  • Bullets don't have collision.
  • Characters get hit when a bullet is close enough to them. (Use a distance calculator)
  • New bullets should add to a global list of bullets. (Which are then used by all characters to check if all bullets are close enough to them)
  • Bullets that hit immediately get removed on the game. Don't add piercing mechanics, if you add piercing mechanics, it will just complicate it.

This should allow you to make that game even if it's not Unity under month.

scarlet kindle
#

Hey how can I stop the console editor from stacking same debug statements on top of each other?

hard viper
#

there is a collapse button

broken zodiac
scarlet kindle
#

o ty hehe

hard viper
#

if this is for a class, you should focus on learning the fundamentals of programming

#

jumping straight into programming without knowing anything is just going to be a trainwreck

loud wharf
#

Bro code C# tutorial.

#

He didn't tackle polymorphism tho.

hard viper
#

especially if your teacher is incapable of teaching you proper style, proper documentation, self-documenting code, etc etc

#

these are important skills that you don't normally learn from a random youtube video. these are things you learn in school

broken zodiac
broken zodiac
#

In this Harvard course I trust

hard viper
#

just for reference

#

this is what garbage tier code looks like:

    var r = ((int)o << rb[(int)b])
        + ((int)o >> (4 - rb[(int)b]));

   r = r & 0b_1111;
    if (b >= 4) {
        r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);
    }
    return (Cardinal) r;
}```
#

same code but in proper style:

public static Cardinal RotateCardinal(Cardinal original, Rotation rotateBy) {
    Debug.Assert((int)original >= 0, "Tried to rotate a NEGATIVE cardinal value! Cardinals should be 0-15!");
    Debug.Assert((int)original < 16,"Tried to rotate a cardinal that was >15! 15 is the max for having the total # of directions!");

    // Bitshift to represent rotation. Moves all 4 cardinals into right spot in flags
    int rotated = ((int)original << rotationBit[(int)rotateBy])
        + ((int)original >> (4 - rotationBit[(int)rotateBy]));

    // Now the main 4 bits are right. Get rid of out-of-range bits.
    rotated = rotated & 0b_1111;
        
    // More bitmath. That operation above rotates by 2, so L/R are flipped. now isolate U/D and add back in
    if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
        rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);
    }

    return (Cardinal) rotated;
}```
#

this is the sort of thing you need to learn

#

style

broken zodiac
#

๐Ÿ’€ I'm so thankful I chose not to do computer science at university it looks terrible

hard viper
#

good style allows you to actually know wtf it does

broken zodiac
hard viper
#

like how would you know wtf this does: if (b >= 4) { r = (r & 0b_0101) + (r << 2 & 0b_1000) + (r >> 2 & 0b_0010);}

#

comments are just one tool. a tool you need to use the right amount

broken zodiac
hard viper
#

ok. what does it actually do

hard viper
#

you told me what the math says it's going to do

#

but you did not explain what it is doing, and why it is there

#
if (rotateBy >= Rotation.sigma) { // Need to do a mirror plane
   rotated = (rotated & 0b_0101) + (rotated << 2 & 0b_1000) + (rotated >> 2 & 0b_0010);}```
Oh look, an actual explanation
broken zodiac
#

The purpose of this code could be to alter certain bit patterns within 'r' depending on the condition, possibly for specific bit-level operations or optimizations within the program.

hard viper
#

this whole function takes in cardinal input, which is a combination of bits in an integer corresponding to up-down-left-right.

#

the function tries to rotate this cardinal

#

that line checks if the rotation (an enum type) is set to flag for a mirror plane

#

then the actual bitmath applies a mirror plane to flip

broken zodiac
#

๐Ÿฅฑ good night speak some more tomorrow

hard viper
#

point being, learn style. good night

loud wharf
long scarab
#

I'm having some issues with script inheritance.

    {
        GameObject projectileGO = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);
        TrackingBulletBehavior projectile = projectileGO.GetComponent<TrackingBulletBehavior>();

        if (projectile != null)
            projectile.Seek(target.transform);
    }

I'm using this function to fire a projectile from a tower, but I'm trying to generalize it so that the tower can instantiate any type of bullet and still get ahold of its script component.

#

my bullet scripts extend off each other like this

rigid island
long scarab
#

But I'm trying to search for any "ProjectileBehavior" and just use the overwritten "Seek" function

#

yeah

#

its not inheriting

#

and im not sure why

long scarab
# rigid island is there a question there?

I changed it to ``` void Shoot()
{
GameObject projectileGO = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);
ProjectileBehavior projectile = projectileGO.GetComponent<ProjectileBehavior>();

    if (projectile != null)
        projectile.Seek(target.transform);
}```
#

and it doesn't compile

rigid island
spring creek
tawny elkBOT
spring creek
#

but I can see you are not using override, so that may be the issue? Can't tell without seeing more

rigid island
#

also what is the error

spring creek
#

Or just show the error

long scarab
spring creek
rigid island
#

btw OnDisable is not capitalized properly

long scarab
long scarab
spring creek
#

the parent won't have it

long scarab
#

correct

spring creek
#

If seek was in the PARENT of BulletBehaviour, it would work
Not the other way around

long scarab
rigid island
spring creek
long scarab
#

reflection?

rigid island
#

skip the get component, spawn it as whatev you want directly

long scarab
spring creek
long scarab
rigid island
#

thats casting

spring creek
#

Sorry, I mean BulletBehaviour
You need to cast it to TrackingBulletBehaviour, which DOES have Seek

rigid island
#

you can also just do C instanceC = Instantiate((C)a); ofc

spring creek
#

Seek is ONLY known by TrackingBulletBehaviour and any class that inherits FROM it. No parents know about it. So cast to TrackingBulletBehaviour or a child.

That is all

long scarab
#

just making sure I understand, my code currently is grabbing the TrackingBulletBehavior but it's treating it as just a ProjectileBehavior, right?

long scarab
#

I understand the part you guys are explaining

spring creek
#

It is treating it as exactly what you call it

long scarab
#

gotcha

#

so it's got the right script, I just have to specify by casting so it knows to look for Seek()

rigid island
#

change ur prefab type first

long scarab
#

but then wouldn't I have to hardcode that in for any projectile that does or doesn't use that method?

rigid island
#

public GameObject projectilePrefab; should be ProjectileBehavior no?

long scarab
#

no

#

ProjectileBehavior is a script attached to the game object

rigid island
#

im aware

spring creek
# long scarab no

I would say yes. You can always do .gameObject from the script reference. But you have to do GetComponent going the other way

rigid island
#

ProjectileBehavior would mean you can put any of the child classes you shown

long scarab
long scarab
#

but I plan to cut down on it because there is too many layers as is

rigid island
#

almost never a need for GameObject instead of the actual type you need

long scarab
#

then how would I pass the prefab into the tower?

spring creek
#

That will spawn the whole gameobject with all other components and values

#

You almost NEVER need a gameobject reference

scarlet kindle
#

If I Instantiate UI objects in a particular parent, is it's SiblingIndex able to be pre-determined? Should it always be the highest?

spring creek
rigid island
scarlet kindle
#

got some bugs with me cards ordering, like when I draw a card, I instantiate it into my hand.

but it appears that the siblingIndex it's instantiated with is random ...

spring creek
long scarab
rigid island
#

GameObject creates the instance of your scripts sitting on it

long scarab
#

huh

rigid island
#

its like a container ig

rigid island
long scarab
#

wdym by sit on

rigid island
long scarab
#

as in a component?

rigid island
#

sure all scripts on gameobjects are components

#

any monobehaviours can do .gameObject inside the script and its property in the monobehaviour class

#

of the object that contains that component

#

basically was saying just do ProjectileBehavior projectile = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform);

#

but you have to change projectilePrefab from GameObject

long scarab
#

ohhhhhh

rigid island
#

since you're trying to spawn it as ProjectileBehavior

#

otherwise you get type mistmatch error

long scarab
rigid island
long scarab
#

yes sorry, I meant the script on that instance of the prefab

rigid island
#

the prefab will turn into that yes

long scarab
#

gotcha, thanks

long scarab
#

now it gets mad if I try to cast

rigid island
#

what type is projectilePrefab

agile rock
# leaden ice What does "stop working" mean exactly?

My bad. I forgot to desc this. The game loses whole input. I mean whatever player Press it does nothing. The game its not freeze (there are sounds, animations of Birds).
There is one moment in game where they are stuck in this but we tested it and everything is fine. Zero errors or nulls in logs. Its appear when they play for a couple of hours.

long scarab
#
    {
        ProjectileBehavior projectile = Instantiate (projectilePrefab, firePoint.position, firePoint.rotation, gameObject.transform) as ProjectileBehavior;

        if (projectile != null)
            projectile.Seek(target.transform);
    }```
rigid island
long scarab
#

ah

agile rock
long scarab
#

yeah, I forgot to change it up top

#

ty ty

agile rock
rigid island
agile rock
hexed pecan
#

C# is garbage collected, so not sure what they mean with that

latent latch
#

we memory manage now

long scarab
#

just gonna shift stuff around and fit it into the project

#

tysm

latent latch
#

if you're using unmanaged arrays and stuff like that if you don't dispose then you can leak

#

or w/e I've just been using them and blew up unity a few times

vestal surge
#

Does anyone have any experience with hand tracking with MediaPipe? I'm using it for a project and I'm having trouble implementing both hands.

leaden ice
polar marten
tender haven
#

how can i change an int's value with a slider im trying to make a volume thing

somber nacelle
# tender haven how can i change an int's value with a slider im trying to make a volume thing

you can set your slider to whole numbers, but since slider really only deals with floats you'd have to get its value then cast or round it to an int.
however if this is for volume you'd be better off making your slider go from 0.0001 to 1 and just display it formatted as a percent. Then you can just use Mathf.Log10(sliderValue) * 20 to get the value in decibels for your audio mixer

tender haven
#

ok thanks

cold egret
#
  • I'm doing a bottleneck optimization here. The game creates around 2-4k objects, each of which fetches components in their hierarchy and sorts them. This is the second most time consuming operation done by these objects. Hence, there are several questions of mine:
  1. My tests seem to confirm that the order of the returned array is always identical. However i'm told not to rely on this. Is there any reason not to? I could cut the sorting time 10 times already if i cached the permutations after performing a sort on the prefabs.
  2. Not really scripting, but if the 1st point is valid and i should not expect to get the same order in get components method result, how much of an impact will de/serializing references to the components be? Is it any faster than fetching components in children?
  3. And lastly, if both previous point fails, is there any internal magic that enhances the execution time of the built-in method that i could not achieve while making my own version of it?
fervent furnace
#

yep, why dont just serialize the reference to prevent 2-4K calls to getcomponent after you spawn it, btw i have no idea what you means by "sorting the components"?
i remember the return order is based on the scene tree, if you dont modify the scene that you can rely on the order, but it is impossible for you not to modify the scene

cold egret
somber nacelle
cold egret
#
  • Also, re: scene tree. Does it include instantiating objects at runtime, or just moving things around in the editor?
fervent furnace
#

oh, sorting when a new object spawned?????
you just need a sorted set (red-black tree ) or skip-list to maintain a sorted order
insert and remove takes O(log n), pretty fast

#

i think you should talk it to your partners or whoever, to change the data structure

cold egret
#
  • Well, it happens on every spawned object now, but i'd very much like to avoid this nonsense. All it does is repeats the same sorting task thousands of times. I seek to cache it, or at least rework it so doesn't have to happen to each object individually
sullen fern
#

I'm trying to pause my game with timescale but for some reason my event triggers im using for my UI arent working

soft shard
agile rock
tribal glacier
#

Im trying to use CreateAssetMenu and ScriptableObjects for a making cards for a card game. Is there any way with the asset menu to make something like "if the (damage card) boolean check box is clicked show the make a damage card menu" within the asset creation menu. (sry if this is explained poorly)

cold egret
#
  • Conditional context menus are not a thing unless you find something related in the asset store. You're better off creating your own editor window at this point
lapis nexus
#

Heya - Working with Unity's ECS, and having some extremely weird problems with empty components.
When I apply a large number of empty components to entities all the other systems seem to act in a bizzare way as if there is a memory leak although there is no leak?

I'm declaring the component as follows. When using the component like this it's causing the above issue.

public struct CCompletedIntercept : IComponentData { }

When declaring the component with a dummy field the above issue is gone?

    public struct CCompletedIntercept : IComponentData
    {
        public bool dummy;
    }
buoyant raven
#

Hi, does anyone know how to replicate this type of thing in a custom script?

buoyant raven
# lean sail That is a unity event

Ah, perfect! Thanks! Another quick question if you don't mind. While I was searching on how to replicate this I tried digging inside the Button.cs script but couldn't find the member variables such as the UnityEvent or any of the colors for button interactions, bools, etc... that we can see in the editor inside a button. Is there a way to find these by chance so that next time I can analyze how something is done without having to ask questions?

storm thorn
#

Hello! I want to implement this reward system on my app, but I'm using firebase authentication with login and registration, if I follow this, will this still be save on the user's account? or should I incorporate firebase to the reward system? I'm planning to just follow the tutorial ๐Ÿ˜…

https://youtu.be/ZoNDcgacF2M?si=cYUMuXaQ9asrkM6R

In this video, I'm going to show you how to create a simple reward system for your hyper or hybrid casual game, you might be wondering what the benefits of adding the reward system are in summary, this feature will increase engagement and the chance of players watching rewarded ads. Ok, let's get to it

State.io Clone tutorial:
https://www.youtu...

โ–ถ Play video
lean sail
buoyant raven
lean sail
buoyant raven
sullen fern
flint apex
#

So this is not 100% related to coding but what I have is one main camera rendering everything except the hands and the gun and one camera that renders the hands and the gun (btw forgot to say I am making fps) so the problem is I am making a bullet line but it comes from the gun tip but the weapon camera fov is different and it is causing it to be shifted to the left .What should I do ?

soft shard
# sullen fern when i pull up my pause menu i am setting timescale to 0 at the same time, but w...

AFAIK, animations on the UI might depend on time scale being above 0 (if they are not set to "unscaled time" for their animator components), for interactions though, are you sure there is no other UI elements blocking your buttons? Do you have a event system in your scene that is enabled and setup for the input system you are using? Are you using a Canvas Group on any of your UI/canvas? Do you have "raycast target" turned OFF for those buttons? If so, you may want them ON, these things may typically prevent mouse events like clicking, if you havnt already checked all of them

hexed pecan
#

Idk if this makes it any clearer, but here's a sketch.
It's top view. White lines are the camera direction/frustum, red is the gun, blue is the projectile
Yellow is just the center of the view

sullen fern
soft shard
soft shard
sullen fern
#

I'll try that out

#

thanks!

forest linden
#

serialized unity array looks like this for some reason

the variable in code
[SerializeField] private int[] bonesToWalk;

forest linden
#

nothing

#

just gives an error

somber tapir
forest linden
#

nope

hexed pecan
#

The code you posted is fine

forest linden
#

Assets\HumanAI2.cs(38,33): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

#

there was an error after I typed in 1

hexed pecan
forest linden
#

thats an entirely different variable

hexed pecan
#

Ah damn, I thought that's the array size field

#

It should just show like this

#

Do you have compiler errors?

#

And what kind of object is this on? Maybe the share rest of the code

#

Because the line you shared is correct

#

Resetting the editor layout could help, if it's some GUI bug

forest linden
#

I've completely restarted the project, there are no compiler errors.

hexed pecan
#

That doesn't reset the layout. But other than that, no idea

forest linden
#

didn't fix it

hexed pecan
#

What if you initialize the array, does that change anything?
Next thing I would try is changing the array's name completely and see if it helps

forest linden
#

wierd thing is that there are other unity arrays in my scripts above this one that work but all the ones below dont

hexed pecan
#

What else are you drawing in between? Like what fields

forest linden
#

that array in my variable declaration

#

wait, no, thats not it

#

WTF

#

every unity array I close turns into this

hexed pecan
#

๐Ÿค” What unity version?

forest linden
#

this is no longer a code problem

hexed pecan
#

Yeah definitely a bug

forest linden
#

this is an entirely a new script

hexed pecan
#

You aren't using Odin or other custom inspector stuff, right?

forest linden
#

nope

#

happens on every custom script

leaden ice
forest linden
#

in progress

#

updated to 2022.1.16f, still broken

leaden ice
#

Is your inspector in debug mode?

open wasp
#

idk if im just being pepega, but for some reason, this code (which is in update) keeps randomly forcing the rotation of the camera to be forward center as long as the targetRotation is 0,0,0. And I mean instantly, hard setting it and cause the camera to stutter. i dont get why this happens. the vid i stole this from has only this code and it work perfectly and it does work perfectly as long as targetRotation > Vector3.zero.

young bluff
#

both of these should result in the same thing right as classes are copied by reference or i'm i worng

hexed pecan
#

Neither is Slerp

#

This would be more appropriate Quaternion.Slerp(Quaternion.Euler(someEuler), Quaternion.Euler(anotherEuler), speed)

#

Or Quaternion.identity instead of the Vector3.zero

#

Another option is to use Mathf.LerpAngle for x, y, and z

open wasp
#

that did not fix the issue

#

this still causes the stutters i mentioned. not sure if i did it wrong

hexed pecan
#

You are still using Vector3.Lerp for a rotation

#

I'm not even sure if I understand your problem fully - that's just what stuck out for me

leaden ice
open wasp
#

well the targetRotation is what the recoil amount gets plugged into. my issue is that if targetRotation is greater than 0, than it causes my camera to stutter and try to force itself to look center screen on only the x. i dont get what it's happening

flint apex
open wasp
#

actually, i think i found the conflicting code and now i just go to figure out how to get them both to work.

flint apex
flint apex
#

Bro such a simple thing but of course it's going to be the hardest thing on earth

hexed pecan
hexed pecan
#

I chose to implement weapon collisions instead

#

I prefer that anyway

#

Bit less artistic freedom since you can't adjust FOV separately, but a lot of problems gone too

rigid island
#

yeah the no shadows on fps weapon is a real turn off from camera stack

hexed pecan
#

I think Tarkov managed to do it somehow

#

Like the weapon FOV doesn't change if you change your FOV

#

But their render pipeline is probably very customized

flint apex
#

I duplicated every object I want shadows and just made it only render shadows

hexed pecan
flint apex
#

Ok then what should I use

#

For the hands and weapon

hexed pecan
#

As I said I personally chose to use a single camera. So I can't recommend anything else

#

And fixed weapon clipping to walls with a basic weapon collision system

flint apex
#

Can't I just use render texture and swap ui raw image on top

hexed pecan
flint apex
#

I don't know anymore

#

These cameras are shit

#

For example how valorant did this

#

Or CSGO

hexed pecan
#

Maybe some shader magic. Different projection matrix for the gun/arms or something...

#

Not sure though

shadow fern
#

hello everyone, i developing a 2d game. I have TMP_InputField in my scene's middle. after that, i touched inputfield in mobile (iOS or android), the keyboard takes up almost half the screen. how can i solve this?

open wasp
hexed pecan
#

And again, Vector3.Lerp is not for eulers

forest linden
#

I can see the arrays if I open the script up as properties and enable debug mode in the property tab. It works but I hate it

rigid island
forest linden
#

same

#

didn't fix it

rigid island
forest linden
#

?

open wasp
forest linden
#

its on every single script

hexed pecan
#

To answer the question: you can multiply to quaternions to "add" them together

#

The left-right order of the multiplication might matter, try both ways

open wasp
hexed pecan
open wasp
#

i did and it makes my screen go crazy when i move my mouse

hexed pecan
#

Ok sorry can't read all the code right now, a bit busy

open wasp
#

nah man. you're good

#

i'll wait however long i need to get help

#

it is the default unity starter assets code

rigid island
#

i was asking if it was an array of a custom class

#

good ol GUID +Dictionary

#

forgot the full details i used for this but it was a pain but easy enough

flint apex
# hexed pecan Not sure though

When I get home I will try moving the camera if the result is decent I will use it if not I will offset the bullet line

thick socket
#

is there a way to simplify this?

 if(target.transform.position.y > transform.position.y)
                {
                    if(target.transform.position.x > transform.position.x)
                    {
                        curveCounterClockwise = true;
                    }
                    else
                    {
                        curveCounterClockwise = false;
                    }
                }
                else
                {
                    if (target.transform.position.x > transform.position.x)
                    {
                        curveCounterClockwise = false;
                    }
                    else
                    {
                        curveCounterClockwise = true;
                    }
                }
leaden ice
open wasp
thick socket
#

this feels wacky to do lol

curveCounterClockwise = (above == right);```
hard viper
#

usually youโ€™d want to define these sorts of things based on angles, or implicitly with dot products.

#

this logic is simple, but it depends on the specific use case if it is good enough

hexed oak
#

If I wanted to put in some demo functionality that wouldn't normally run unless I'm in a debug type mode, but I wanted to consolidate the definitions of the demo mode functionality to an interface, how savage is it to put an #if TESTMODE interface like this?

public class BaseGame
#if TESTMODE
        : DemoTester
#endif
{

}```
foggy sentinel
#

Does someone know how I would implement a tilemap which the player can use to interact and build stuff.

hidden flicker
#

The fov never resets or even lowers, however it says that ResetFov runs, once, at the correct time.

knotty sun
hidden flicker
#

Ok, well now it keeps increasing the fov

knotty sun
#

to start with, never check floats for equality

jaunty sundial
#

How would i go about making it so that my 3rd person player cant move outside the vision of my static camera so i.e moving my player left off screen will just mean my player doesnt move almost like a collider

vagrant blade
frosty surge
#

When the player is hit by the bullet he get a knockback but only in y axis the x remain constant even though i didnt lock x in the rigidbody of the player

public class Player_Life : MonoBehaviour
{
    [SerializeField] private float health = 10;
    [SerializeField] private float startLavaTimer = 0f;
    private float lavaTimer;
    private bool insideLava = false;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        lavaTimer = startLavaTimer;
    }

    void Update()
    {
        CheckIfInLava();
    }
    void CheckIfInLava()
    {
        Debug.Log(health);
        if (insideLava)
        {
            lavaTimer -= Time.deltaTime;
            if (lavaTimer <= 0)
            {
                health--;
                if (health <= 0)
                {
                    Destroy(gameObject);
                }
                lavaTimer = startLavaTimer;
            }
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.CompareTag("Lava"))
        {
            insideLava = true;
        }
        if(collision.gameObject.CompareTag("Bullet"))
        {
            rb.velocity = new Vector2(5,2);
        }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        insideLava = false;
    }
rigid island
frosty surge
# rigid island are you overriding velocity somewhere else?

this is my player movement

public class Player_Movements : MonoBehaviour
{
    [SerializeField] private float speed = 0f;
    private float horizontal;
    private Rigidbody2D rb;
    public Transform groundCheck;
    private bool isGrounded;
    [SerializeField] private float jumpForce;
    public LayerMask whatIsGrounded;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, whatIsGrounded);
        if(isGrounded)
        {
            if(Input.GetButtonDown("Jump"))
            {
                rb.velocity = Vector2.up * jumpForce;
            }
        }
    }
}
rigid island
#

well there you go

#

rb.velocity = new Vector2(horizontal * speed,

#

you'd have to put some sort of bool probably

#

I prefefer simple FSM

frosty surge
rigid island
#

you're still overriding it

#

with 0

#

speed can be 1000

#

if horizontal is 0

#

it will be 0

#

you need to do rb.velocity.x in there when KNocked back

scenic crown
#

Hey I am trying to do a game project for school and I want to know if I can have a code editor within a game to allow people to code in the game.

#

And will I be able to do it and post it on webgl

scarlet pawn
leaden ice
leaden ice
#

Presumably it's ignoring time scale

scarlet pawn
#

Everythibg worked perfectly fine 5 minutes ago, now i reopened the project and everything broke

leaden ice
#

Irrelevant

leaden ice
scarlet pawn
#

This project is like 7mknths old and im trying to improve it

scarlet pawn
scenic crown
leaden ice
#

And unsafe

scenic crown
#

How so?

scarlet pawn
#

Movement code

leaden ice
# scenic crown How so?

C++ is a language that allows the user to directly access and modify arbitrary memory locations.

Not even C# does that really

#

It's also a compiled language

#

It would be very complex and ill advised to use C++

#

Something like Lua or JavaScript would be more typical and easier to control

flint apex
#

@hexed pecan just did the offset thing and it works like a champ thx for the idea

simple egret
#

Jokes aside, please post !code correctly

tawny elkBOT
scarlet pawn
simple egret
#

Then come back later, most of these are blurry or overexposed, too hard to read

scarlet pawn
#

I cant open discord on my pc

scarlet pawn
#

No one wants to help me

simple egret
#

Once you will post code properly, this will change

scenic crown
scarlet pawn
#

Im not on my pc rn so i cant open discord

simple egret
#

Then ask again when you'll be on your PC

scarlet pawn
#

11 rn

scenic crown
simple egret
#

All I can say is, make sure the method that should run when you click the button is actually running

#

Place a Debug.Log() in it, write something meaningful and run the game, click the button, see if you get the message in the console

scarlet pawn
#

ok pls help now

#

@leaden ice

#

you wanted movement code

#

pause code

quartz folio
#

!code please post properly

tawny elkBOT
scarlet pawn
scarlet pawn
quartz folio
#

No you didn't. You posted a large amount of plain text that I deleted, and above is also a large codeblock not posted as a link

scarlet pawn
#

THIS SERVER SUCKS, BUT ITS MY LAST CHANCE TO GET HELP

quartz folio
#

Just read the post from the bot and follow the instructions without getting worked up about it

lean sail
spring creek
rigid island
scarlet pawn
simple egret
#

lol

#

Going full circles

rigid island
#

you have more time combatting and being a child

#

yeah troll

quartz folio
#

!mute 709639836402974732 30m take a break, go outside, and when you return please just post links to large codeblocks like our read-me and bot post states.

tawny elkBOT
#

dynoSuccess neilas_z was muted.

hidden flicker
rigid island
#

your missing yield return null inside whileloop @hidden flicker

simple egret
#

Precisely

#

In the block between lines 25-28

quartz folio
#

or yield for the coroutine if that's what you want to do instead

simple egret
#

If you need to start the coroutine (line 27), and wait until it's finished to continue through the if statement (after line 27), then yield return StartCoroutine(...)

hidden flicker
quartz folio
#

SPR2 elaborated

hidden flicker
simple egret
#

Line 27

#

Only if you want the code to wait there until ResetFov() has completed

hidden flicker
simple egret
#

Can you post the code again? Website says the contents was not found or deleted
Could be just on my end though

hidden flicker
#

Yeah for sure, plus it'll be the current version after my modifications

simple egret
#

Oh it's fixed wtf, I refreshed the page

hidden flicker
#

Oh alr

#

Tysm for your time btw, really appreciate it

simple egret
#

Yeah so you can still yield return StartCoroutine() because what checks for the FOV reaching its target is the if statement on line 24 14

hidden flicker
simple egret
#

Yielding the coroutine will just not allow the code to move past line 18, until the ResetFov() coroutine itself has completed. So when execution resumes say on line 19, the FOV will already be reset

hidden flicker
simple egret
hidden flicker
#

It should just loop until the conditional of the while loop isn't met

simple egret
#

It will loop again if the condition is met, correct

#

Without the yield return, it will loop immediately after line 18 was executed.
With the yield return, it will loop only after ResetFov() has finished running. If that takes 10 seconds to run, then the loop will start looping again after 10 seconds only

hidden flicker
simple egret
#

What do you mean by "run properly" here?

hidden flicker
#
  1. As long as the field of view is not equal to baseFov + changeBy:
  2. Move the field of view towards baseFov + changeBy
  3. If the field of view IS equal to baseFov + changeBy:
  4. Log that it ran ResetFov
  5. Run ResetFov
  6. Stop running BurstFov
swift falcon
#

i dont know which channel i would put this in but i cant move this or anything

#

i can only move terain

simple egret
#

To say it differently, the fact that you put yield return or not, acts on when step 6 will be "executed", right after the ResetFov() coroutine has started, or after it finished

hidden flicker
#

Aaaaand it apparently never runs ResetFov.

simple egret
#

I'd say it's the way you compare the values in the while loop and if statement conditions. As these values are float it's very unlikely it will be exactly equal to what you're comparing it to

#

Instead of: if (a == b)
Prefer: if (Mathf.Abs(a - b) < some_small_value), or if (Mathf.Approximately(a, b))

hidden flicker
#

This code pulses

#

This code crashes

leaden ice
simple egret
#

The crash indicates that the if statement passes

hidden flicker
#

Got it. Why does the first one pulse though?

leaden ice
simple egret
#

The loop never exits

leaden ice
#

check your logs, etc.

hidden flicker
#

Ok. Iโ€™ll add some debugs and get back with the logs

daring crane
#
using System.Collections;
using System.IO;
using UnityEngine;

public class RandomTextureLoader : MonoBehaviour
{
    void Start()
    {
        LoadRandomTexture();
    }

    void LoadRandomTexture()
    {
        string texturesPath = "Assets/Textures/Walls"; // Change this if your folder is located elsewhere
        string[] textureFiles = Directory.GetFiles(texturesPath, "*.png"); // Change the extension based on your texture types

        if (textureFiles.Length > 0)
        {
            string randomTexturePath = textureFiles[Random.Range(0, textureFiles.Length)];
            Texture2D texture = LoadTexture(randomTexturePath);

            if (texture != null)
            {
                ApplyTextureToMesh(texture);
            }
            else
            {
                Debug.LogError("Failed to load texture: " + randomTexturePath);
            }
        }
        else
        {
            Debug.LogError("No textures found in the specified folder: " + texturesPath);
        }
    }

    void ApplyTextureToMesh(Texture2D texture)
    {
        MeshRenderer meshRenderer = GetComponent<MeshRenderer>();

        if (meshRenderer != null)
        {
            Material material = meshRenderer.material;
            material.mainTexture = texture;
        }
        else
        {
            Debug.LogError("MeshRenderer component not found on the attached GameObject.");
        }
    }

    Texture2D LoadTexture(string path)
    {
        byte[] fileData = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(2, 2);
        texture.LoadImage(fileData); // Auto-resize the texture based on the image file data
        return texture;
    }
}

Why isn't this loading the texture? I have the pngs in the Assets/Textures/Walls directory

leaden ice
winged tiger
#

anyone know how to get list of folders inside Resources folder?

leaden ice
#

At runtime though, no such folders will actually exist

winged tiger
#

at runtime you can load resources from assets

leaden ice
#

You can load resources from Resources

#

not from assets

winged tiger
#

wait what

#

ah yes

leaden ice
#

but also - the folder structure of your project will no longer exist in a build.

winged tiger
#

ohh

leaden ice
#

Only the paths for Resources assets will be saved in order to facilitate Resources.Load, but the folders themselves will not really exist

winged tiger
#

so there's no way to list the folders

leaden ice
#

No. Why are you trying to list the folders? What are you actually trying to accomplish?

winged tiger
#

Im trying to create a radio

#

and load at runtime the channels

#

every folder is a channel

leaden ice
winged tiger
#

you pasted the wrong link but I got it

#

yeah thats a good idea

leaden ice
#

no I posted the right one for my suggestion.

winged tiger
#

ohhh

#

i see

#

thanks

pure garden
#
    public WeaponSO weapon_id
    {
        get
        {
            return weapon;
        }
        set
        {
            weapon = value;
            UpdateWeaponType();
        }
    }```

any idea why that doesn't call the updateweapontype function?
simple egret
#

Make public WeaponSO weapon;, private instead. You'll see the errors right away, I think you may be not using the property at all here

pure garden
#

ok so, is there any way i can asign weapon_id in the editor or only by code?

simple egret
#

Only by code. Unfortunately Unity cannot serialize properties in the Inspector

broken zodiac
#

guess whos game still isnt working?

soft shard
simple egret
#

Yeah but that bypasses the getter/setter

#

It'll set the backing field directly

soft shard
#

Ah

hollow hound
#

Is there a way to get "continuous collision detection"-like for triggers?
I have fast bullets (that should be trigger colliders) and sometimes they are moving to fast to detect trigger event.
Both object has dynamic body type with continuous collision detection.

simple egret
#

You have to roll your own. A few lines of code that raycasts from the last bullet position (last frame) to the current bullet position can do. You won't even need the collider anymore, and you can extend it to a RaycastAll, if you need to compute penetration damage, what stops the bullet, etc.

hollow hound
#

I thought about it, but wanted to ask for the simpler built-in solution. But there is no such, right?

broken zodiac
#

can someone please help me cause everytime i right click on my mouse the game keeps pausing?

hollow hound
simple egret
#

Oh, you can set their mass to a very small value

#

Input 0, and it'll set the value that's closest to zero that's not zero. A few micrograms or less

hollow hound
#

But if the projectile is big and small, and spawns inside of an enemy it still pushes them

#

Also I need actual mass because I'm using force movement for theme

simple egret
#

I remember seeing some property on the Collision object passed in OnCollisionEnter that's the force that was applied to the receiving object. You can apply an equal and opposite force to cancel it out

hidden flicker
#

Alright I got some debug stuff in.

fossil blaze
#

Why might the trigger not work?

simple egret
#

I don't think OnControllerColliderHit detects trigger colliders

#

You might want to switch to the regular OnTriggerEnter for this

fossil blaze
#

OnTriggerEnter only works with rb, after all

#

but it didn't work with him either

fossil blaze
#

I have a 3D game, objects in the form of a tilemap

#

the prefab of the road itself

severe wedge
#

Hi,
I have issues with order of executions between when I setup a singleton manager and when I subscribe to an event it exposes :

GameManager.cs

using System;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public event Action OnPlayerDeath;

    private void Awake()
    {
        Debug.Log("Executed second");
        Instance = this;
    }

    public void GameOver()
    {
        if (OnPlayerDeath != null) OnPlayerDeath();
    }
}

ObstacleController.cs

using UnityEngine;

public class ObstacleController : MonoBehaviour
{
    private void OnEnable()
    {
        Debug.Log("Executed first");
        GameManager.Instance.OnPlayerDeath += GameManager_OnPlayerDeath;
    }

    private void OnDisable()
    {
        GameManager.Instance.OnPlayerDeath -= GameManager_OnPlayerDeath;
    }

    private void GameManager_OnPlayerDeath()
    {
        // do stuff
    }
}

Here, ObstacleController.OnEnable() is executed before GameManager.Awake() therefore, I get a null ref when trying to access the GameManager instance.
I do not want to fix this by messing around with the scripts execution order as I feel this is not a robust solution and I might break it with future changes/refactors.

When would you setup the GameManager singleton in order to ensure its exposed event is available for other scripts to subscribe to ?
Or would you move the subscription code in ObstacleController to another spot in its lifecycle ?

Looking for best practices here please ๐Ÿ™‚
Thank you

simple egret
#

Awake: initialize yourself
Start: get references from others

OnEnable runs directly after Awake, it's not like Start which runs when all other script's Awake have finished running

severe wedge
#

so I should subscribe to events in Start() method ?

simple egret
#

Yes

hollow hound
simple egret
#

2D doesn't have that, only 3D rigidbodies do

severe wedge
#

alright, thank you.
most of examples i've seen about events always managed subscriptions in OnEnable/OnDisable

#

would you still unsubscribe in OnDisable() ?

simple egret
#

Only if you need the event handlers to not run when the object is disabled. Else, you unsubscribe in OnDestroy() so everything is cleaned up when the object/script is destroyed

severe wedge
#

got it, ty

dusk apex
soft ruin
#

is there a list type like dictionaries but they can have repeating keys

lean sail
soft ruin
latent latch
#

What does repeating keys imply? Multiple keys to 1 value?