#archived-code-general

1 messages · Page 131 of 1

coral talon
#

Oh, that was an engine-reserved name?

quartz folio
coral talon
#

That actually worked, many thanks!

viscid parcel
#

new smaller issue, unsure of how to actually check for which layer is being hit in the if statement

#

cause i cant use GetMask on my layermask to define which layer is which from my raycast.

quartz folio
#

if (hit.collider.gameObject.layer == theIndexOfTheLayerYouCareAbout) {

viscid parcel
#

you sir have made my day

#

🫡

#

absolute legend

swift falcon
#

How can I print out all scripts that are using a function

void Function()
{
   print(All Scripts that call "Function")
}
rough crown
#

so lets say I have class A with a variable of int speed which has a value of 5. And Class B that inherits from Class A. How do I make it so that inherited classes also have the value of the variable from the class they're inheriting? In this example, Class B's speed variable would also be 5 similar to Class A.

dusk apex
rough crown
#

Oh yeah protected works best with what I'm doing

#

I assume getters and setters might also work

dusk apex
#

Depends on what you're trying to do overall.

rough sorrel
#

Hi. One question, what would be the best way to have like 5000 bullets spawned and moving and checking for collision without tankind performance please? Like for a fast shooting weapon

#

idk if this would be the best solution, but you could create a new material and then assign it to the cubes with code

#

or you want it like random colors?

#

but like, how do you want to colour it?

#

like, just a single color for everything?

#

hmm then maybe vertex coloring would be the best solution, but I'm not 100% sure how it works😅

trim schooner
#

What were your search terms?

Mine would be along the lines of 'unity how to set vertex colour via code'

#

Can't say, don't have enough info

#

If you create the meshrenderer from scratch via code, then your material + texture will need assigning correctly at run time.
If you already have a sphere, with a material and texture, but manipulate it at runtime.. I would expect the material/texture to display regardless.. just if it's UV'd it'll be messed up

rare owl
#

Anyone here who can help me out with proper frame pacing

#

Achieving smooth and consistent frames is quite challenging haha

trim schooner
#

Profile, profile, profile... on the target platform

#

Doesn't really sound like a code issue.. unless you've already narrowed it down to your code causing the slow downs

simple ridge
#

Hi everyone, I asked this last night in the animation chat but since I never got a responce I was wondering if I should also ask here. I'm looking to work on some animations for some machines and my player characters mechanical armor. However since I'm a programmer, and not really well versed in rigging and animation I was thinking of just doing all "machine-based" animations through script, (like a hydraulic piston in a joint setting its position and rotation through script as the body moves). Is this a feasible solution or is scripting too slow for this on the large scale, that something like the animator might be better off with.

#

I've written IK before through scripts so I'm thinking of just doing things like that but as a global solution for all mechanical things if that makes sense

trim schooner
#

100% it's going to be a lot better with an animator... you can do it via code though, but it will be very time consuming depending on amount and complexity of the animations

rare owl
trim schooner
#

stutters happen because of...... performance

rare owl
#

Lemme elaborate

simple ridge
#

Ah, okay I will look further into the animations then

#

Thanks

trim schooner
#

Loading a prefab that isn't already in the scene can cause a stutter

simple ridge
# rare owl Lemme elaborate

As @trim schooner says, the profiler will show you the frames that typically use more resorces and cause stuttering. There is some overhead with the editor running in the background, but usually if its a script issue you will see a large spike on the frame, then you can use deep profiling to find what is causing the stutter

#

You can have a solid 60fps for the whole game and just one frame where something large happens / or alot of garbedge is collected. which can cause a spike in frame delta time.

#

Is that your issue?

rare owl
# trim schooner stutters happen because of...... performance

More about a frame variance thing in my case. My game works on 60fps all the time. There's no lag. It's just about mismatching refresh rate and Target framerate, and/or very small variance between previous and current frames. To eliminate this Unity has the optimised frame pacing for Android which uses Google's swappy. Maybe you'll understand it better if I further let you know more about my issue and the topic

#

So um, if I play the game at 60fps while my device is working at 60hz refresh rate things are smooth as silk. And once I toggle to 120hz refresh rate, the same 60fps starts to stutter (feels less smooth and sorta jittery)

#

Now if I lock the fps to 30 with my device is at 60hz, 30 fps feels not so good

#

I understand there's a difference between 30 and 60 but it can look better

#

I'll give more information which would convince you

rare owl
#

Lemme screen record it

#

There's no frame drop at all, and you may feel some micro stutters in the video if you're really paying attention, just ignore them it's my screen recorder's fault as the game never stuttered at all.

#

Look carefully. Do you feel the difference in smoothness?

#

30fps feels bad at 60hz and even worst at 120hz due to the same reason

#

Now it can feel better!

spark flower
#

isnt int points basicly the same as private int points ?

rare owl
rare owl
#

Fix is, to change the refresh rate of the device to the closest value possible to the capped framerate

#

But I can't cap the refresh rate to anything lower than 60hz so for 30 fps unity's optimised frame pacing can do the job. It has it's own useless overhead so I don't want to use it for 60fps and above as I can lock the refresh rate to make it look smoother. Is there a way to toggle optimised frame pacing on and off through a script?

#

Also instead of directly asking the question I wanted to show some states. Idek how old games used to look that smooth at such low frame rates without any special effects like motion blur. I would like to know more about frame smoothing techniques if possible

sleek jasper
#

I was wondering if someone would mind helping me as i got myself in a picke with material.Settexture.

swift falcon
sleek jasper
#

i am trying to add a texture i just created to a material but for some reason it is not working. Setfloat and Setvector work fine for the same material. I have double checked the property reference sting in code and it is definetly correct

#
        mat.SetFloat("_GDTScaleAdjustment", terrain.terrainData.size.x);
        mat.SetTexture("_GrassDamageTexture ", image);```
simple egret
sleek jasper
#

Ill check:)

#

omg

#

thank you so much i have no idea how this lsipped through

vagrant blade
#

@sharp dirge !collab

tawny elkBOT
thin pilot
#

Hello! I'm working on a desktop companion application similar to shimeji. I have working transparent background, but I don't have any idea on how to interact with UI elements on a windows OS desktop screen.

This is the closest thing I was able to find regarding the topic, but I don't know if this is the correct approach nor do I know how to access these dll files in Unity:
https://stackoverflow.com/questions/73361591/unity-desktop-app-c-sharp-finding-position-of-task-bar-to-align-assets

How would one go about getting positional data on windows UI elements like the windows taskbar, and how would you translate that to ingame world space?

grave jackal
#

Does anyone have suggestion for detecting if code is running as a part of a unit test or in normal play mode?

fervent furnace
#

i just detect my code in play mode with log(start running) then delete it if it works normally

#

or you can have some #define DEBUG (preprocessor directive)

grave jackal
#

I was hoping to find a combo of things that works with what unity does itself, the code where I'm putting is in a [RuntimeInitializeOnLoadMethod]

rare owl
#

Hey does anyone knows how to change the global fixed timestep value through script

grave jackal
rare owl
knotty sun
#
public static float fixedDeltaTime; 

static means global in this context

rare owl
#

Thanks!!

prime sinew
#

Unity's fixed timestep loop

#

But also what Steve said

rare owl
#

Thanks alot friends!

dapper mural
#

hi there guys, is it there any way to launch a .bat file inside unity?

fervent furnace
#

dont cross post
idk if you can make a new process in unity

#

(i know nothing about process in c#, i only know exec of c)

dapper mural
#

cross post? sorry but what I would like to achieve is creating a mesh via an external script in python an run it inside unity so I can render it there

potent sleet
dapper mural
#

aw ok I didnt know

craggy veldt
#

Assuming this is Editor only, the usual Process.Start(path) should work

dapper mural
#

I placed the bat file inside the asset folder of my project

potent sleet
#

and?

#

it wont magically run by itself

dapper mural
#

I made a script in C# trying to open it on Start() but seems like it doesn't work

leaden ice
#

what does that mean exactly?

dapper mural
leaden ice
#

Like open it in a code editor?

dapper mural
#

no I just want it to run the code

leaden ice
#

you need to do Process.Start(pathToPython) and include the path to the python file itself as a parameter

#

i.e. you need to know where your python executable is

#

not your .py file

#

but the python command itself

#

it's the same as starting it in the command line /path/to/python/python.exe myPythonScript.py

dapper mural
#

I was trying this approach because I have a lot of imports in my python script that are not compaytible with unity

craggy veldt
#

nah just call the python from the batch script instead

leaden ice
#

oh yeah if you have a batch script already running do that

potent sleet
#

btw whats the difference with Application.OpenURL

#

would that not work?

dapper mural
#

so? any idea? I was thinking is it possible to just like attach my bat file to an empty game object and on play I say to unity to run it?

potent sleet
#

comprehension issue 101

dapper mural
#

sorry Im not native... mmm like how can I run this bat file while play mode is on?

knotty sun
dapper mural
potent sleet
#

it's not

dapper mural
#

like a reference ?

#

ok

potent sleet
#

you already been told how to do it tho..

fervent furnace
#

you can run your python script by system call (?) in start....

dapper mural
#

Process.Start() ?

knotty sun
dapper mural
leaden ice
#

Is there a reason you want to create the mesh in python? Is this a Blender python script?

#

Also is this something you want to have happen in the game itself, or just in the editor

#

If thids is a thing for the game, you definitely don't want to be using a Blender python script. That puts a hard dependency on the game user having Blender (of the correct version) installed on their computer.

dapper mural
leaden ice
#

SO... it's blender too?

#

this is quite a lot od dependencies you will need to bundle with the game

dapper mural
leaden ice
#

Wouldn't it be better to do the mesh generation in the cloud or something?

dapper mural
#

I need to pass some variables to the AI model so the mesh created its always different

unborn dagger
#

Hello, how can I know whether an object is an instance of a certain prefab (in my case I want to know if the object that I'm colliding with is an apple) ?

leaden ice
#

So?

leaden ice
dapper mural
leaden ice
knotty sun
leaden ice
#

either check for:

  • the existence of a component
  • a tag
  • a variable on a component
    @unborn dagger
unborn dagger
#

Ok thank you

dapper mural
craggy veldt
#

Question is who'd want to play your game when pytorch and all the dependecies are part of the requirement?
Do you know how massive in size pytorch is?

unborn dagger
#

Can I just attach a script named apple and check if it's there or is it bad code ?

craggy veldt
#

😅

unborn dagger
#

ok ty

leaden ice
#

Another option is to attach a script named Item and give it an ItemType variable and check if the type is ItemType.Apple

dapper mural
unborn dagger
knotty sun
leaden ice
#

and just set the unity game up to read the Fbx directly and display it

#

THen the unity thing doesn't need to know/care about python or torch or anything

dapper mural
#

ye I was thinkig something like that, like running externally my script and just importing the mesh via script when I need to

#

but then I need like a script to run unity and the mesh generator toghether

leaden ice
#

yeah that's the batch script

dapper mural
#

ye sorry I read it wrong

#

ok thx for the suggestion

#

mmm the cool thing inside unity was like I create a UI that like on click makes me the mesh and rend it in realtime :C

idle oxide
#

This is my code for aiming in my 2D unity project (https://hatebin.com/qvpehcmcjt). I am trying to do the same thing in Unity 3D but nothing I try works. Either the object doesn't move or it moves so fast it looks like it's flashing. Can anyone please help?

earnest gazelle
#

Is it OK to create a new class type for each to categorize/group similar objects?
For example in a game, there are different items/elements.
I can create one class to describe an Element and then several derived classes inheriting from e.g. MaterialElement, FoodElement, etc. or just one class Element and with enum field to group them.
Now, MaterialElement and FoodElement are the same as Element (they don't have additional fields).
If in the future, they have their own fields, do you create spearate classes for each or put all fields in the root class?
Personally, I do not like to create extra classes for each when I doubt if it should be.
It is worth noting, these classes are data structures (data only)

dapper mural
#

ok it works!! bat file launched

simple edge
karmic cape
#

Hey peeps, this code

 if (sun.elapsedTime >= (time * 4) + .1 && sun.elapsedTime <= time * 5 && currentskybox != SkyEarlyDusk)
        {
            RenderSettings.skybox.Lerp(SkyAfterNoon, SkyEarlyDusk, .5f);
            currentskybox = SkyEarlyDusk;
            output("Skybox Changed to edusk");
        }

isnt working correctly the if statment works and runs the code within it at the correct time, however the skybox isnt updating

RenderSettings.skybox.Lerp(SkyAfterNoon, SkyEarlyDusk, .5f);

is the line that changes the skybox material and then

DynamicGI.UpdateEnvironment();

is used to update it (from what iv read in the docs)

any idea why the skybox isnt changing?

mellow sigil
#

That will set the skybox to halfway between noon and dusk. Is that intentional?

karmic cape
#

im trying to transition from one sky box to another with some blending so it looks more smooth

mellow sigil
#

and you have to change the logic so that it runs every frame

quasi edge
#

I'm trying to add a wheel collider to a car I made, but the wheel collider is perpendicular to the car's wheels. Anyone know how to fix this?

karmic cape
#

ty

potent sleet
#

show gizmos as well in local space

quasi edge
#

ill put it in unity talk next time

potent sleet
quasi edge
#

yeah i know that

#

i tried rotating it to 90

potent sleet
#

it should be 0

quasi edge
#

when it was at 0 rotation it also wouldnt work

potent sleet
#

wdym "woudln't work"

quasi edge
#

rotating the wheel collider wont actually rotate it

potent sleet
quasi edge
#

oh ok

quasi edge
potent sleet
#

I've used wheel collider like twice

earnest gazelle
# simple edge Derived classes Once you need more properties you just add them to the classes t...

OK, so you say derived classes for each even if they are empty?
What about if several derived classes have one same field? again inheriting?

public class ElementDefinition: ScriptableObject{
   public string Guid;
   public string Name;
   public Sprite Icon;
   public ElementGroup Group;
   public ElementType Type;
}
public class FoodDefinition:ElementDefinition{
    public int Energy;
    public Receipe[] Receipes;
}
public class SeedDefinition: ElementDefinition{
}
public class MaterialDefinition: ElementDefinition{
   public MaterialGroup MaterialGroup;
}
//...

earnest gazelle
#

Also, sometimes it is hard to categorize them. For example a seed can be a food or not

#

Isn't it more flexible to put all in one place?

public class ElementDefinition: ScriptableObject{
   public string Guid;
   public string Name;
   public Sprite Icon;
   public ElementGroup Group;
   public ElementType Type;
   public bool IsEdible;
   public int Energy;
   public Receipe[] Receipes; // for foods or crafting materials
   public int Temperature;
}
frank vigil
#

I hope this is the right place to ask this but Im trying to use unity multiplayer stuff. I cant figure out how to use the callback function onClientDisconnect. Like how do I actually use code when someone disconnects

frank vigil
#

Thank you

undone prism
#

does anyone know if there is a photon discord? im kinda stuck on this small thing in my multiplayer game

#

because i cant find one

swift falcon
#

so i'm havning some problems with this script:

if (Input.GetKey(crouchKey_))
{
crouched = !crouched;
}
if (Input.GetKeyDown(crouchKey))
{
crouched = true;
}
if (Input.GetKeyUp(crouchKey))
{
crouched = false;
}

    if (crouched)
    {
        transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
    }

    if (!crouched)
    {
        transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
    }

basically crouchKey is shift and i want it so that you crouch when you hold the button, while crouchKey_ is a button on the controller and i want to make it so when you click you start crouching and when u click again u stop
Image
it kinda works (once every three times i click) but is super buggy and i can't

and also i'm having problems with this other method: it will correctly debug when crouched is true but it will never put the state to crouching
Debug.Log(crouched);
if (grounded)
{
//Crouching
if (crouched)
{
state = MovementState.crouching;
desiredMoveSpeed = crouchSpeed;
}

        //Sprinting
        else if (Input.GetKey(sprintKey) || Input.GetKey(sprintKey_))
        {
            state = MovementState.sprinting;
            desiredMoveSpeed = sprintSpeed;
        }

        //Walking
        else
        {
            state = MovementState.walking;
            desiredMoveSpeed = walkSpeed;
        }
    } 

any help would be appreciated, thanks!

wide terrace
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

swift falcon
wide terrace
# swift falcon https://gdl.space/inusuboqux.cpp
        if (Input.GetKey(crouchKey_))
            crouched = !crouched;

This will toggle crouched between true and false each frame for as long as the button is held. Since you want it to toggle only when the gamepad button is pressed, you change it to a Input.GetKeyDown() instead - that is, "toggle crouch state when button is pressed" rather than "if button is still pressed toggle crouch state".

swift falcon
#

i tried but that sadly didn't work at all

wide terrace
#

What are the symptoms of it not working? I don't think it'd be possible for

if (Input.GetKeyDown(crouchKey_)) {
  crouched = !crouched;
}

to not set your crouch state correctly 🤔

swift falcon
swift falcon
wide terrace
swift falcon
#

exactly

#

@wide terrace

wide terrace
#

Yeah just digging to see if I can spot anything 😅

Just to be sure - crouchSpeed is set to something other than 0 in the inspector for this component?

swift falcon
#

sorry for pinging ya, just wanted to make sure you knew i was still here

#

🙂

wide terrace
# swift falcon sorry for pinging ya, just wanted to make sure you knew i was still here

Nothing immediately jumps out at me - you may need to start sprinkling some Debug.Log()s around to try and narrow down the problem. Maybe starting with the end of the movement process here, in order to ensure the correct moveSpeed is in fact getting all the way to the AddForce() call. To that end, I might slip one in MovePlayer() like

if (crouched) {
  Debug.Log("MovePlayer() crouched with moveSpeed " + moveSpeed + " in direction " + moveDirection);
}

That way, if it logs an incorrect value for moveSpeed, we'll know the problem's somewhere in the prior speed handling code. If it is correct, then a proper force should be getting applied - so it might be that crouchSpeed needs to be bumped up to overcome friction, or perhaps crouching is sinking your collider into the floor or some such.

swift falcon
#

thanks a lot I'll try more debugging

civic berry
#

im making a fps game that uses projectiles as the bullets how do i make the enemy take different amounts of damage based on the type of gun im using

leaden ice
#

have the gun set it when it shoots the bullet

civic berry
#

so public float damage;

leaden ice
#

sure

sage latch
civic berry
#

if i run into my enemy it stops following me and is repelled by me

#

how can i fix this is my enemy code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Enemy : MonoBehaviour
{
    public GameObject player;
    public GameObject effect;
    public float damage = 10f;
    
    public float enemyHp = 50f;
    public float previoushp;

    void Start()
    {
        previoushp = enemyHp;
    }
    void Update()
    {
        gameObject.GetComponent<NavMeshAgent>().SetDestination(GameObject.Find("Player").transform.position);

        if (enemyHp < previoushp)
        {
            
            previoushp = enemyHp -20;
        }

    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag == "Player")
        {
            Player player = other.transform.GetComponent<Player>();

            if (player != null)
            {
                player.TakeDamage(damage);
            }

            Debug.Log("Player HP: " + player.hp);
        }
    }

    void Die()
    {
        Destroy(gameObject);
    }

    public void TakeDamage(float amount)
    {
        enemyHp -= amount;
        if (enemyHp <= 0f)
        {
            Instantiate(effect, transform.position, Quaternion.identity);
            Die();
        }
    }
}
potent sleet
#

repelled by me and stops following doesn't come clear in this code

civic berry
#

nvm i fixed it by adding walls

night lance
cursive gorge
#

witch sprite mesh is most performant

weary quiver
#

Helloo, I am in need of some help cause I am really lost. I've just made a simple Highscore Table on a scene besides my already existing game scene, where I wrote a code so it saves my highscore.Now my problem is, that I do not know how I should combine these two out, like for example in the game or something I write my name out, and after I make a new highscore it should be saving it to the highscore table, how can I do that? Here is the highscore table code: https://hatebin.com/egyclkjdgn , and here would be the game code: https://hatebin.com/ihttkildzv

jaunty needle
#

Guys why is my raycast so skewed?

#

Here is the script:

#
    {
        Ray ray = new Ray(transform.position, transform.forward);

        if(Physics.Raycast(ray, out  hitInfo, range)) 
        { 
            if(hitInfo.collider != null)
            {
                if(hitInfo.collider.CompareTag("Zombie"))
                {
                    Destroy(hitInfo.collider.gameObject);
                }
            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawLine(transform.position, transform.forward * range);
    }
knotty sun
jaunty needle
#

I'm putting it on the main camera

buoyant crane
jaunty needle
buoyant crane
#

you’re supplying it a direction

jaunty needle
#

Like it detects before it hits

buoyant crane
jaunty needle
#

I will provide a demonstration

weary quiver
cobalt gyro
#

when should i use structs instead of scriptable objects

buoyant crane
#

Trying to answer it would be like trying to answer when you would use a hammer instead of a car

cobalt gyro
#

got it

jaunty needle
#

oooooooooooh

#

I think I got it

#

It isn't ignoring the trigger collider

#

That i have on the zombie

buoyant crane
jaunty needle
#

Btw how do I get a physics raycast to have ignore triggers but without layermasks

cobalt gyro
jaunty needle
#

I know

#

I meant in the Physics.Raycast function

#

Like in all these 16 options

#

There isn't one where there is the querry interaction but no layermask

#

I don't want a layermask

buoyant crane
#

wrong overload but the general idea is still there

jaunty needle
#

so I just add the layermask and set it to default?

buoyant crane
#

you can

buoyant crane
cobalt gyro
#

ty

buoyant crane
glossy basin
#

Hello there, I am implementing a random card spawning / selection system and the current algorithim I have has a major problem which Im going to describe. So my algorithim should generate a specific / special card if the player does not have it already and it also needs to make sure that the spawned cards do not spawn more than once (cards can not be repeated). Both things work fine, however my only issue is that the assured specific card is always spawning at the index 0 of my list, how can modify my code so it can spawn at a random index?

#
 //Generate a random relic keeping in mind that they can not spawn more than once on the same round
    private void GetRandomRelic (byte playerIndex, RoundAttributes.roundContents roundContents)
    {
        PlayerBuffs player = playerIndex == 1 ? player1Buffs : player2Buffs;
        RelicData relic = null;

        for (int i = 0; i < 3; i++)
        {
            //Checks if the player already contains this relic, if not , then assure its spawning
            bool isEvolutionRelic = !player.relicsInUse.Contains(player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution);

            if (isEvolutionRelic && !player.randomPickedRelics.Contains(relic))
            {
                relic = player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution;
            }
            else
            {
                // Generate a random relic that has not been picked yet
                do
                {
                    relic = cardData.relicData[UnityEngine.Random.Range(0, cardData.relicData.Count)];
                } while (player.randomPickedRelics.Contains(relic) || (isEvolutionRelic && player.relicsInUse.Contains(player.skillsInUse[player.skillsInUse.Count - 1].relicForEvolution)));
            }
        }

        player.randomPickedRelics.Add(relic);
    }

This is the code I'm using

wintry crescent
#

AAGH, I don't know where to ask, I know this isn't probably a good place for this, but I'm going crazy, is there a way to override this limitation in visual studio?

wintry crescent
#

I wasn't clear, true

#

I mean, the project is like 60gb so I can't blame it, but I really was hoping it's possible

glossy basin
#

Also, why is it that heavy?

#

Have you tried deleting and regenerating library folder?

wintry crescent
glossy basin
wintry crescent
#

IDK, wasn't my decision, it's a work thing

#

Assets folder is like 22gb

glossy basin
#

Lmao, that's the problem then

wintry crescent
#

just cloning the repo and opening the project (couple of hours) brings it to 60

glossy basin
#

Having multiple projects inside a single project will increase the size drastically

wintry crescent
#

yea, you tell me

glossy basin
#

Im not sure if there is a workaround to splitting all those projects in different folders respectively

wintry crescent
wintry crescent
glossy basin
glossy basin
swift delta
#

I'm getting some weird 2D Rigidbody interactions wherein a player won't be knocked back in the X axis at all, but will behave just fine when being knocked back in the Y axis. An enemy interacting with a trigger seems to work just fine in all directions.

#

the knockback code:

    public void Knockback(float power, GameObject origin, GameObject receiver)
    {
        Rigidbody2D rb = receiver.GetComponent<Rigidbody2D>();
        Vector2 direction = (origin.transform.position - receiver.transform.position).normalized;
        rb.velocity = Vector2.zero;
        rb.AddForce(-direction * power, ForceMode2D.Impulse);
    }
#

on that note: would it be better if I didn't use GetComponent for this and instead just passed the rigidbody as a function argument?

gilded matrix
#

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

public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
private Rigidbody2D rb;

private void Awake()
{
    rb = GetComponent<Rigidbody2D>();
}

private void Update()
{
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");

    Vector2 movement = new Vector2(horizontalInput, verticalInput);
    movement.Normalize();

    rb.velocity = movement * moveSpeed;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    // Check if the player collides with objects tagged as "Obstacle"
    if (collision.gameObject.CompareTag("Obstacle"))
    {
        // Calculate the desired movement direction
        Vector2 movement = rb.velocity.normalized;

        // Reverse the movement direction to avoid the obstacle
        rb.velocity = -movement * moveSpeed;
    }
}

}

#

my player won't collide with rigid body kinematic objects

prime sinew
wintry crescent
gilded matrix
#

rigidbody

prime sinew
#

Check if it's actually triggering the OnCollisionEnter first, then see if your code is just making it seems like nothing is happening based on what octia is saying

wintry crescent
#

also - do the player AND the kinematic objects both have 2d components?

gilded matrix
#

yes

#

lol i asked 3 different AI's

#

and they say it should work idk lol

prime sinew
#

Please don't ask AI..

gilded matrix
#

i tried many variations of settings

#

lol

prime sinew
#

Okay, how about you try debugging using the link I sent

#

And in the future please format your code using this

#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

wintry crescent
#

also does it work with non-kinematic objects that block? add a lot of mass to them and check

pastel halo
#

Hey, I'm trying to figure out how to cache the "Debuff ui element" that displays how long the debuff is applied for. The first issue is caching it, the second is making sure there aren't duplicates (to avoid rapid damage spike/dupe debuff elements), the third issue is calling the cache through the StatusEffectDot coroutine since its a temp variable not a permanent one.

rn it does spawn the icons and does apply the correct tick display, but it's unable to limit them/reset pre-existing ones, and tick down the values since I don't know how to access a temp variable externally through an IEnumerator (without converting it to a perm variable? but then would i need a list?)

rocky basalt
#

Hi all,
After copying/re-naming my project, I find the Application.persistantDataPath still leads to the old project's folder structure.
Does anyone know the way to fix this?
Thanks

wintry crescent
pastel halo
#

These are all contained in the same class currently

#

I have a PlayerDebuffManager that's applying all the states. It's pushing data into the "UI debuff" prefab and trying to track that internally. Like cache it and update it from the current class, rather than have a secondary script on the ui debuff prefab itself working internally

#

I can paste the entire class online if that helps**

wintry crescent
pastel halo
#

O ya i'm familiar with those, just need to figure out how to apply it appropriately since I'm using it in basic ways, and this task seems a bit more advanced

wintry crescent
# pastel halo https://pastebin.com/duZyQmTR

Also, I like to have separate scripts on elements like the debuff icon - keep track of them with a dictionary (key StatusEffectType, value scriptThatControllsDebufIcon)
Have 1 coroutine, running forever, that goes through a list of references to debuff UI icon scripts, and updates them accordingly
could also be a function called in update. Keep the tic counts in public variables in the debuff ui icon scripts, update the image (and time left) from them as well, through a function called by your main script

pastel halo
#

Ok, i'm sorta following. So I need a class on the debuff prefab itself (the one that spawns into the canvas), then have the dictionary track that

#

Is that new class ex: DebuffPrefabUI going to read values from the base class PlayerDebuffManager? like some kind of injection within the Start/Awake?

wintry crescent
#

don't bother getting info in the start/awake of the DebuffPrefabUI - too much hassle - just put it in from the class that spawns it, through a function you call

pastel halo
#

Ok i'll give that a shot. A bit abstract to me atm but I'll figure things out. Also are those two classes in your example or one?

wintry crescent
# pastel halo Is that new class `ex: DebuffPrefabUI` going to read values from the base class ...

and before that, you just need to check if debuffDictionary has the key for the new effect that you're adding, and if it's not null
if it doesn't exist or is null, do the following code that I posted above
else, access that script, and call a function that will add time to it
and within the update function of that debuffPrefabUI script, change the timer every second (or a coroutine, that could be easier)
also, you might want to put all this image changing in the debuffPrefabUI script, and have it take that info from the debuffManager itself, based on StatusEffectType, from another dictionary there

wintry crescent
#

just showed you what type of dictionary I'm talking about, and how to more easily instantiate prefabs - no need to spawn gameobject directly, you can spawn any component that's on the gameobject, it'll spawn the same, and you'll automatically have a reference to the component you want

pastel halo
#

would that be inside my playerDebuffManager class, or in the debuffPrefabUI class? It's reading like its in the debuffPrefabUI class

wintry crescent
pastel halo
#

O gotcha, ok I'll give that a shot

gilded matrix
#

would it be possible for me to show u my screen? I could stream screenshot

#

i am really new to unity

#

i got it to work but i havre to set player to dynamic

#

and when i do some wierd stuff happens

prime sinew
#

No. and please don't send friend requests from here to DM people

blissful yoke
#

How expensive is it to turn a list into a queue?

lean sail
blissful yoke
#

I see

blissful yoke
#

I'm trying to figure out how to best implement an turn order initiative feature.

#

Got it

lean sail
#

if you convert it once, it doesnt matter really. if this is some conversion happening over and over then id be concerned

#

best thing is just get it working before you try to optimize

#

plus this list likely wont be that long if its just turn orders, theres not gonna be anything expensive about it

blissful yoke
#

so, I would like to incorporate a speed-based initiative order ala Triangle Strategy (Ie faster characters go more often), with some turn order manipulation seen in games like Honkai Star Rail, where turns can advance or be delayed.

Each unit would have a speed stat base of 100. Their place in the initiative is found by dividing 10000 by their speed, giving an ActionValue average of 100. When a Unit's turn ends, the Action Value of every other unit in the queue would be reduced by the ActionValue of the unit that just had its turn.

Let's take an example, we have Unit A (Speed 80) and B (S 100), and C (S 120).

So, a turn order would look like this (UnitName: ActionValue)
C: 83
B: 100
A: 125
C: 166
B: 200
C: 249
A: 250

When C's turn is concluded, all the other ActionValues for the units in the order are reduced by 83.
B: 17
A: 42
C: 83
B: 117
C: 166
A: 167

And so on. I think this system will offer quite a few fun options for how games will go.

What I'm struggling to do is figure out how to elegantly create the turnorder. What I think I want to do is this:

  • Create a number of turns for each unit (say 1000 action points worth of turns).
  • When a unit finishes a turn, create a turn at the end of the queue. To do this, I need to find the unit's turn with the highest turncount (or ActionValue), and add a turn at the end based on that.
  • If a unit's turn ActionValue changing changes its place in the turn order (such as with an advance or a delay), then this should be reflected in the turn order of course.
  • The queue would be displayed in the UI (a number of turns ahead, at least). Changes in the list would be reflected here with an animation.

So, should I go for Queue or List? Or both?

#

Logically, a turn order seems like something you'd want to use a Queue for. However, due to the manipulation that will happen, a List maybe? I'm conflicted.

lean sail
#

I havent played that game but i think i understand what you mean. if you're going to be editing values a lot over the entire collection theres no reason to use a queue because you'll just be dequeuing and enqueuing constantly to keep the order. A list should just be fine

fervent furnace
#

You have to deque the first one, so you can either use foreach to manipulate all the values or implement your circular queue

sharp harness
#

Good day, Multiplayer Floating Origin. Anyone have experience or willing to discuss ?

cobalt gyro
#
{
    public class EntityStatistics : MonoBehaviour
    {
        public Stats stats;
        void Update(){  
            stats.displayHealth = (int)stats.health;
            stats.maxDisplayHealth = (int)stats.maxHealth;
        }
    }
}
#

for some reason the struct stats doesn't popup in the inspector

blissful yoke
cobalt gyro
#

nvm

sacred vault
#

why UI mask doesn't work?

#

my maskablegraphic not getting masked

#

unity version 2021.3

gilded matrix
#

my custom physics shape is not being used

#

,and i have a tilemap 2D collider. Instead of using my custom physics shape unity is counting an entire grid as a collider? any ways of fixing this?

sacred vault
inland grail
#

how do i make an object make a sound when the player collides with it in unity 3D

dusk apex
#

Don't cross post.

swift falcon
#

sry

soft shard
# inland grail how do i make an object make a sound when the player collides with it in unity 3...

Sound is played through a AudioSource component, so if your object has one (or you have a reference to one), you can call .Play from the collision event, theres many other properties like setting the AudioClip as well: https://docs.unity3d.com/ScriptReference/AudioSource.html - how the sound is heard, is determined by a AudioListener, there can only be 1 in the scene and by default its attached to the "Main Camera", and the Audio Source Spatial Blend and volume settings greatly affect where and how the audio source is heard, relative to the listener (assuming that the Game view audio isnt muted)

gilded matrix
#

my custom physics shape is not being used
,and i have a tilemap 2D collider. Instead of using my custom physics shape unity is counting an entire grid as a collider? any ways of fixing this?

#

any possible fixes, not links to things online since i searched everything

swift falcon
#

Hello, I got a question. for unity, anyone knows a tutorial where it teaches how to check the performance benchmarks? Bec for school I am doing a study between two algorithms and am comparing the frame time, load time, memory usage, cpu usage, gpu usage, input latency etc...

fervent furnace
#

profiler

swift falcon
#

ty

swift falcon
#

how do i make it so that i can record what button player clicked?

#

like i want to make custom keybinds but instead of having a super long scroll menu i'd like to listen to what the player clicks

fringe ridge
#

What's the best way to calculate distance between objects if I don't actually need the distance, just to check which is bigger. I believe there was a function that doesnt calculate the square root

simple egret
#

Yep (b - a).sqrMagnitude

fringe ridge
#

Thanks

#

also, is this a proper way to remove list elements while looping through it ? for(int i = 0;i< chars.Count; i++) { if (chars[i].IsDied) { chars.Remove(chars[i]); i--; continue; }

#

I feel like this shouldn't skip any other elements if the current one is removed

simple egret
#

Might be with that decrement, but to be safe I would do a reverse for loop myself

#

Most IDEs have a snippet for that, forr then tab twice

fringe ridge
#

yeah, reverse sounds safer

simple egret
#

Or if it's a List, then you can use .RemoveAll(c => c.HasDied) to do it in one line

placid summit
#

Anyone having trouble uploading apps to Apple for distribution today (Xcode)?!

late lion
fervent furnace
#

i think your data is unordered, you can simply do this
for(i=0;i<Count;){
if(a[i] needed to be removed)->remove as swap back (ie swap it with a[Count-1]), Count--
else i++;
here the i pointer only increment when it meets a non dirty element

heavy smelt
simple egret
heavy smelt
#

They appear in the Unity Console. I tried the regeneration, will look the asmdef solution you propose !

simple egret
#

Assembly definitions are files, you can easily check if you have some, by searching for any file with the asmdef extension

quartz folio
#

You can search t:AssemblyDefinitionAsset

heavy smelt
#

problem solved. @simple egret @quartz folio Learnt something new ! Thanks, you are awesome.

swift falcon
#
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
        {
            if (Input.GetKey(kcode))
            {
                Debug.Log(kcode);
            }
        }

i'd like to store only the value before the last one how do i do that

swift falcon
#

and like it's
Joystick1Button9

JoystickButton9

Joystick1Button9

JoystickButton9 --> i'd like to store only this value in a keycode variable
Joystick1Button9

knotty sun
#

yes, it will debug every frame the key is held down

swift falcon
#

cuz when i use the gamepad it debugs Joystick1 then Joystick and i only want to store Joystick, which is the penultimate

knotty sun
#

so cache the kcode and check current against previous

swift falcon
leaden ice
knotty sun
#

there is that. and use break when the first one is hit maybe

#

but

KeyCode prevCode`;

then

prevCode = kcode;
#

in the if will cache the value

swift falcon
swift falcon
simple egret
#

Two values are normal, the first indicates any joystick button was pressed down, the second one is that it comes from joystick 1. If you had a second one, it would have said joystick 2

knotty sun
#

so in fact a break; after the debug should do it?

#

i still have no idea what he is trying to achieve

simple egret
#

Depends on if they want to know what button on which joystick was pressed, or just that a joystick button was pressed

#

Button remapping UI, if I read the question correctly

knotty sun
#
KeyCode lastCode;
foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
        {
            if (Input.GetKey(kcode))
            {
                lastCode = kcode;
                Debug.Log(kcode);
                break;
            }
        }

lastCode now contains the keycode found;
I guess?

swift falcon
#

one second

spring basin
#

Trying to make a payment on payments.unity.com fails saying ILLEGAL_TRANSACTION
My dashboard has been locked out
What could be the issue?

spring basin
#

couldn't find the appropriate channel 😛

#

this one seems to be the most active one, lmao

#

could you maybe point me to the right channel?

knotty sun
spring basin
#

@knotty sun alright ty

odd ridge
woven island
#

@spiral marsh we meet again

#

NYEH HEH HEH

swift falcon
odd ridge
#

KeyCode.JoystickButton9

fierce estuary
#

Hi all, I have a somewhat unique question regarding the unity line rendering system. I'm trying to create a mechanic where the player can draw certain shapes with an outline of their movement, and the outline is constantly being checked for resemblance to these shapes. The line is stored in the script as a LineRender object. However, I have no idea how to go about this. I feel pretty competent in my math ability, so if there is some algorithms/mathematical concepts for checking the resemblance of a line represented by an array of 2d positions to an equation then that would be great, or some other unity recognician function idk. Any help would be appreciated, I'll also send a screenshot of what the line looks like if that helps

odd ridge
fierce estuary
#

yeah this looks like a great starting point, thanks!

#

i tried googling unity specific stuff because I didnt know how to word the problem for mathematics, and couldnt really find anything relevant

#

anyways this is a huge help, thanks again

odd ridge
#

no problem. i guess start with the basics/theory and then work up to unity specific things

swift falcon
#

Are enumerable methods like List.Any() expensive to be running frequently?

I'm trying to avoid duplicates on a list by checking something like if(!actorList.Any(a => a == actor)) but i'm not sure if there's a more efficient way, or if it's even worth worrying about duplicates that much.

prime sinew
fierce estuary
#

if you never want duplicates then a hash set could be faster than a list

odd ridge
#
***** ContainsExistsAnyVeryShortRange *****
*******************************************
List/Contains: 1067 ticks
List/Exists: 2884 ticks
List/Any: 10520 ticks
Array/Contains: 1880 ticks
Array/Exists: 5526 ticks
Array/IndexOf: 601 ticks
Array/Any: 13295 ticks
HashSet/Contains: 6629 ticks
***************************************
***** ContainsExistsAnyShortRange *****
***************************************
List/Contains: 4ms
List/Exists: 28ms
List/Any: 138ms
Array/Contains: 6ms
Array/Exists: 34ms
Array/IndexOf: 3ms
Array/Any: 96ms
HashSet/Contains: 0ms
***************************************
********* ContainsExistsAny ***********
***************************************
List/Contains: 11504ms
List/Exists: 57084ms
List/Any: 257659ms
Array/Contains: 11643ms
Array/Exists: 52477ms
Array/IndexOf: 11741ms
Array/Any: 194184ms
HashSet/Contains: 3ms```
spiral marsh
woven island
swift falcon
fierce estuary
#

np

solar wren
#

Do someone know how to compare objects colliders from a another object, So in my case i have the script attached to the camera and in the camera script i want to check if the grenade collider is colliding with the enemy colliders, I would be so happy if someone could answer my question, Thanks!🖐️

fierce estuary
#

is the camera going to be the only object which cares about this collision?

#

if so, use an event

solar wren
#

I can't find a soulotion to compare collisons from another object

fierce estuary
#

But if you need to have the camera handle this for whatever reason, then trigger an event in the ontriggerenter in the enemy script and have the camera subscribe to that event

wide hamlet
#

How would I give an ai the ability harvest crops like wild hemp plants and apples on trees

potent sleet
timid leaf
#

Hi, whats the variable/parameter type that BoxCollider uses for you to select (in editor) a certain area?
Something like Vec3[] or Area?

wide hamlet
#

Basically if the colliders were to collide with each other it would sense it

#

Then it would harvest the plant when its close enough to harvest

potent sleet
#

hmm you can just use distance checks as well

gilded matrix
wide hamlet
#

Thank you!

hexed pecan
heady iris
#

yes, it's a Bounds

strong nimbus
#

How do I make two objects the exact size? Working with relative size is kinda weird isnt it, if I have two objects I wanna make them absolutely the same size, how? In inspector if possible..

heady sail
#

Need help with making the enemy ai use the same bullet controller the player is using

heady iris
#

it's all "relative size" because...how could it be anything else?

#

if I export a correctly-scaled brick and a correctly-scaled house from Blender, i'd expect them to not be the same size in unity

#

let me rephrase things here

#

what are you trying to do?

#

what part of your game are you creating?

mossy snow
forest imp
#

Has anybody had an issue where the layermask for raycasts is shift in a direction? For me, it seems as though the collision box for raycast does not line up with my geometry and is shifted to the left

heady iris
#

the "layer mask" is just a bitmask controlling which layers can be hit

#

so you mean teh actually collider doesn't line up

forest imp
hot torrent
#

it also does log the 1st msg

heady iris
forest imp
heady iris
#

i dunno what that library is doing exactly

#

why are you doing that?

forest imp
#

Apparently it is a security for multiple physics scenes in Fusion. I'm trying it with physics2d.raycast

swift falcon
#

So I need to make a programatical grid to store my cells (Each cell will be assigned enum/int)
I know I gotta make a loop inside a loop but I dont know how to make the actual cell grid

I would need something like this:

000100
010000
010010

0 is an empty cell
1 is a filled cell

Any have any tips?

fervent furnace
#

2d array

#

to optimize the memory usage, you can consider allocate your 2d array with suitable primitive type

swift falcon
#

Alright ill research about them

#

Thanks

forest imp
heady iris
#

oh wait

#

the ray you're drawing is 1 meter long

#

the raycast is 10 meters long

#

no wonder it's mismatched looking

#

the fourth argument of DrawRay is the lifetime of the line

forest imp
#

How far it reaches right?

#

Should it matter if it's only checking the 'ground' layer?

heady iris
#

the ray is going 10 meters

#

your visualization is going 1 meter

heady iris
#

it has nothing to do with the length of the line

#

the raycast is completely correct. your visualization of the raycast is wrong.

forest imp
#

I set duration to 15

#

That's how long it lasts on screen right?

wide terrace
#

Like you only get the "Waiting 0.1s" Debug.Log()? It's worth a mention that the latter WaitForSeconds() will be affected by timescale, and also that the coroutine will stop if the object which called StartCoroutine() is disabled/destroyed

hot torrent
wide terrace
#

so someone'll have to make a bugreport that invoking coroutines from different classes is problematic
I don't understand the particulars - but I believe that that's the intended behavior. It would be nice if the docs would emphasize that a little more, however

hot torrent
#

forget everything i said.

#

the gameobject destroys itself after invoking the coroutine

#

well, now it says m_displayhit(). but that`s where it invoked the coroutine before.

#

so you were right!

#

it stops because the gameobject deletes itself

wide terrace
#

ahh gotchya 👌

Yeah that's a fun caveat to suss out 😅

hot torrent
#

i thought the Destroying = stopping coroutine only applied to the gameobject the coroutine is on

hot torrent
hot torrent
heady iris
forest imp
#

Think I got it thanks for the help

mossy snow
haughty zephyr
#

Has anyone ever experienced noise on mobile builds? It's a 3D heavy game and when switching a certain scene it does this...

feral solstice
#

Hello, this is a very specific situation, but I'm trying to network my hololens with my computer using ZeroMQ but it just crashes unity when I deploy it. Has anyone tried to do this before?

indigo tundra
#

hello, does anyone know what is the best "how to make an online game" turtorial? or just a really good one

ember moth
#

Camera.current is null inside OnBecameInvisible. Is this a bug or by design?

heady iris
indigo tundra
#

i just wanted to know if anyone has some suggestions

static tiger
#

Hi there, I have a issue with loading serilized data from json (database). My JSON string has a lot of characters and there are some incorrect data when loading it because the objects are in the wrong positions e.g. Is it possible that JSONUtility can't handle that much data which is causing the corruption? When using wrapper it counts around 80k characters with spaces. Anyone had similar problem or have diffrent solution for that. It is my first time having to do anything with serialization atwhatcost. Sorry if I'm talking nonsense but it's hard for me to explain.

late lion
heady iris
ember moth
#

anyway it makes sense what you say now that I think of it

#

Use this function only when implementing one of the following events: MonoBehaviour.OnRenderImage, MonoBehaviour.OnPreRender, MonoBehaviour.OnPostRender.

static tiger
heady iris
#

perhaps your code is wrong

heady iris
potent sleet
#

try to stay away from multiplayer until you built a good grounding / experience

indigo tundra
#

thanks!

thorny onyx
#
    {
        if(addedwin == false)
        {
            if(win.Value != -1)
            {
                addedwin = true;
                wins[win.Value - 1] = wins[win.Value - 1] + 1;
            }



        }
    }``` how come when this method runs, any other value that isnt wins[win.value - 1] gets set equal to zero
#

there is no instance where wins[i] gets set to null, they are instantiated with a value of 10

leaden ice
leaden ice
#

show the rest of the code

thorny onyx
#
        {
            addWins();
            GameObject.FindGameObjectWithTag("UI").GetComponent<NetworkUI>().win(playernum.Value);


        }``` method is called here. win.value gets set to a value when a player collides with the goal
#
    {
        wins = new int[] { 10, 10, 10, 0 };```
#

array created in start

#

not created, assigned a value

#

private int[] wins;

#

created in the class not a method

leaden ice
#

in a paste site ideally

thorny onyx
#

its spaghetti code, you can ctrl f

#

whats a good site

leaden ice
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

thorny onyx
#

i dont send code often

#

ok

leaden ice
# thorny onyx https://gdl.space/abutibimuh.cs
        if(collision.gameObject.tag == "Finish")
        {
            win.Value = (int)(playernum.Value);
        }```
What's stopping this from running on every client and thus all of them trying to change win.Value at once?
thorny onyx
#

it only appears to run on the colliding player, that wouldnt cause this issue would it?

#

maybe ill stick an isowner in there

leaden ice
#

Yes it runs on the colliding player but on every client, right?

thorny onyx
#

its not supposed to

#

its supposed to set the win value to the assigned number of the player that won

leaden ice
#

every client will try to do the same thing though - I guess it's confusing that each player object has a variable on it that is saying which player won

#

this class seems to be doing way too much overall

thorny onyx
#

true

leaden ice
#

it seems to be both a character controller and some kind of scorekeeper system

thorny onyx
#

i was never taught how to code, all my games end up having everything in the movement class

leaden ice
#

and a UI updater 🤔

heady iris
#

it's an easy thing to do

thorny onyx
#

im almost done with the online part of my game tho so i wont have to touch it much

leaden ice
#

How are you determining that?

thorny onyx
#

or null

#

ill show u

#

well

leaden ice
#

null is not possible

#

since it's an array of ints

thorny onyx
#
    {

     
            pla = GameObject.FindGameObjectsWithTag("Player");
            winText.text = "Player " + (playernum) + " Wins!";
            playerwintext[playernum - 1].text = "Player " + playernum + ": " + pla[playernum - 1].GetComponent<glide>().getwinsmethod(playernum - 1);
            scoreVisibility(true);
            StartCoroutine(waitfornextscene());
        



    }``` win method, the score for every other player gets set to " "
leaden ice
#

why not just have a single int winCount variable on each object that tracks the wins for that particular player

#

since you're only reading the wins for that player from it anyway

#

I don't see the point of the array

leaden ice
thorny onyx
#

hold up

#

i think that its null because the scene gets reloaded, along with the scoreboard

thorny onyx
leaden ice
#

the fix to that is to fix that lol

#

not to make each client track the scores independently

thorny onyx
#

i think i got it

#

the scoreboard only updates one value

leaden ice
#

I'm not really exactly sure what your problem is but it's related to that whole setup

thorny onyx
#

yea

#

im ready to be done with multiplayer

candid moon
#

https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs

Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime

Components:

Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script

Animator in the child object

private void OnTriggerEnter(Collider other)
    {
        if (other.name == "WalkToPos")
        {

            nav.ResetPath();

            animator.SetBool("isWalking", false);

            nav.updateRotation = false;
            Rigidbody rigidbody = GetComponent<Rigidbody>();

            rigidbody.velocity = Vector3.zero;
            rigidbody.constraints = RigidbodyConstraints.FreezeAll;

            StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));

        }
    }

IEnumerator CustomerSit(GameObject sitPos)
    {
        yield return new WaitForSeconds(0.4f);

        transform.position = sitPos.transform.position;

        print(transform.position + " " + sitPos.transform.position);
        print(transform.position);


        transform.localRotation = Quaternion.Euler(0, 0, 0);
        transform.rotation = Quaternion.Euler(0, 0, 0);

        Animation customerSitAnim = GetComponentInChildren<Animation>();

        animator.SetBool("isOrdering", true);

        ChooseRandomItem();

        sitting = true;
    }```

Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.

▶ Play video
heady iris
#

you're setting the local rotation to zero, then the rotation to zero

#

neither of these care about the rotation of the seat

#

seems weird

#

as for the incorrect y position, i guess you just need to add an offset?

#

the origin of the model may not be the right place to put them

leaden ice
#
transform.localRotation = Quaternion.Euler(0, 0, 0);
transform.rotation = Quaternion.Euler(0, 0, 0);``` yeah this second line completely invalidates/overwrites the first line
heady iris
#

setting localRotation to zero would make sense if it was parented

#

at least, more sense

knotty sun
#

you are mixing physics and manual movement/rotation. Try turning the Rigidbody off

candid moon
candid moon
#

I have / had a print function which prints the location before and after the position was set and the position which was printed would've been right but when i go into the inspector it automatically changes

heady iris
#

i see zero frames where it's not stuck in the seat

candid moon
heady iris
#

sounds like the animator is moving it, then

#

although, i'm not sure where this script is

candid moon
#

shouldn't be able to change it since the animator is in the child object

candid moon
wide terrace
# candid moon

Maybe you're intending to set the character's localPosition to sitPos instead?

gilded matrix
candid moon
candid moon
#

If anyone has time and would like to help me fix this, I'd be really greatful if I could show them the game via discord stream, I am extremely confused on what's causing the issue

wide terrace
# candid moon

The reason I was asking was that the positions displayed in the console log vs the inspector here could well be the same world position, as the one from the inspector is local position. But which object is that inspector ss from/what object is the posted code attached to?

wide terrace
#

ah alright 👍 :/

candid moon
# wide terrace ah alright 👍 :/

Tbh I feel like it's one of those problems where it's a really simple solution but like I don't understand what the cause for the "offset" is, I believe I've checked everything

steady moat
#

If there is no position that is offset, than I believe the animation has the issue.

#

If there is an animation*

fallen lotus
#

I cannot figure out why i'm getting a NullReferenceException: Object reference not set to an instance of an object error when running the following code. everything is assigned correctly and I don't know whats going on.

[SerializeField] private Toggle speedrunToggle;
[SerializeField] private Toggle developerCommentaryToggle;

private void Start()
{
    if(PlayerPrefs.GetInt("speedrunToggleSwitch", 0) == 0)
    {
        speedrunToggle.isOn = false;
    } else {
        speedrunToggle.isOn = true; <--- THIS IS THE LINE THAT IS TRIGGERING THE ERROR
    }

    if(PlayerPrefs.GetInt("developerCommentarySwitch", 0) == 0)
    {
        speedrunToggle.isOn = false;
    } else {
        speedrunToggle.isOn = true;
    }
}
leaden ice
fallen lotus
leaden ice
#

note that you might have more than one copy of the script in your scene.

#

yes in the inspector

candid moon
fallen lotus
#

this is whats so confusing to me

#

is there a way to check if a script is attached twice?

leaden ice
fallen lotus
leaden ice
simple egret
#

You have another instance of this script attached somewhere else, check for t: GameplayTab in the Hierachy

leaden ice
#

in the hierarchy window type t: GameplayTab

fallen lotus
#

okay thank you! ive never used the search before

#

oop foun dit

#

thank you so much @leaden ice and @simple egret

steady moat
gilded matrix
#

this should be it?

wide terrace
# candid moon Tbh I feel like it's one of those problems where it's a really simple solution b...

Yeah... I think this one's probably out of my wheelhouse - especially if it has something to do with the animator. I've only really got random stabs in the dark to try and understand what's going on here, more than any really plausible angles.

I think it may be worth throwing a print(transform.localPosition); in with the others just to be absolutely sure that it's moving afterwards as you suspect it is...

I can't quite make sense of how in the video C_Table1_1's center pivot is 5.4 units below CustomerPrefabs, but in your inspector screenshot (which is presumably with the real pivot) the position is 1.2 units above CustomerPrefabs - unless C_Table1_1's pivot point is 6.6 units above it's center?

pastel halo
#

Hey, still trying to figure out how to call and assign a debuff. I'm getting close but still missing some core components. Would you compare two enums, and if so how? Seems like that doesn't work since it can't equate them. I'm trying to push values from the onTrigger into the player debuff, and that pushes values into the UI. Alotta back and forth and trying to figure out who stores what and who stores the enums and how to read those values to switch things like text/sprites to update the UI

Here's the PlayerDebuffManager players script, it uses a dictionary to store active VFX so debuffs can't stack if already existing: https://pastebin.com/vnWQ6Z2u
Here's the DamageVolumeConditional script which triggers the debuff using an onTrigger (trap, enemy, etc) https://pastebin.com/grRQxHHB
Here's the DebuffPrefabUI prefab that spawns in the UI. https://pastebin.com/bd3HaDN2

#

Also need to have a setup where if a condition already exists, it's either cleared or renewed so it's reapplied without instantiating another cached UI object. (to avoid visual stacking). System seems to be partially working. It is only spawning 1 prefab and it does show the tick counting down/deleting. Just unable to pull data and assign different values from a scriptableObject (not sure how, i'm assuming an enum switch to assign scriptable data?)

mossy snow
gilded matrix
#

for the tiles

gilded matrix
#

that is 1 wall

#

and every tile asset has the same settings

candid moon
wide terrace
# candid moon 1. Don't think it can have anything to do with the animator, animations only aff...

Ah shucks. I was really hoping for that local log 🥲

  1. From the original video, where the tool Pivot Mode was set to "Center." It's probably not relevant - it just struck me as weird that the scene grid could be seen outside of the window which is presumably at y=0, yet while C_Table1_1's center appeared to be well above that plane within the scene (judging by the transform gizmo), the inspector listed it's y position at -5.4
candid moon
wide terrace
#

Ahh gotchya 👌. That makes my brain feel better anyway

candid moon
#

Hahaha

#

Any chance I can stream you it? maybe it's some obvious issue, because i am completely confused

#

not planning to talk in vc tho

wide terrace
candid moon
static tiger
#

Gameobjects serialization problem

shell scarab
#

why is this false?

Debug.LogAssertion(tilemaps[0].id == TilemapID.BASE); // .id is a TilemapID who's id is "base"
``````cs
[System.Serializable]
public sealed class TilemapID
{
    public static readonly string[] ID_LIST = new string[] { "base", "foreground", "background" };

    public static TilemapID BASE { get => new(ID_LIST[0]); }
    public static TilemapID OVER { get => new(ID_LIST[1]); }
    public static TilemapID BACK { get => new(ID_LIST[2]); }

    public string id;

    private TilemapID(string id)
    {
        this.id = id;
    }

    public override string ToString()
    {
        return id;
    }
    public override int GetHashCode()
    {
        return id.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj is TilemapID id)
            return this.id.Equals(id.id);
        else
            return this.id.Equals(obj);
    }

    public static explicit operator string(TilemapID id) => id.id;
    public static explicit operator TilemapID(string s)
    {
        for (int i = 0; i < ID_LIST.Length; i++)
        {
            if (ID_LIST[i].Equals(s))
                return new TilemapID(ID_LIST[i]);
        }

        return null;
    }
}
slim mason
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

shell scarab
#

what?

wide terrace
#

Ah I see no worries well if you want you

feral holly
#

[Android] Hey guys, how to detect if the player clicked on the go back button? Or "slided back" in the new android full screen immersive mode?

shell scarab
# leaden ice Why is what false?

the first line seperated from the rest, sorry:

Debug.LogAssertion(tilemaps[0].id == TilemapID.BASE); // .id is a TilemapID who's id is "base"
leaden ice
shell scarab
#

I did

#
    public override int GetHashCode()
    {
        return id.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj is TilemapID id)
            return this.id.Equals(id.id);
        else
            return this.id.Equals(obj);
    }
#

did I not do what I think I did?

leaden ice
shell scarab
#

oh. I guess I assumed the == is shorthand for .Equals

#

thanks lol

leaden ice
#

Nope they're different

#

For better or for worse

glossy basin
#

Hello there, when doing inheritance, is there a way to hide or show fields on the inherted classes (on the inspector)?

Lets say I have an int on the base class, and I don't want it to be visible on all the classes that derive from it, rather I want to show it on specific classes

lean sail
glossy basin
#

On my base class I am doing this

 [HideInInspector]
    public CombatStances targetStance = CombatStances.Stance1;

and on the class deriving from that, I am doing this, but I can't view the field on the inspector

 [SerializeField]
    public new CombatStances targetStance 
    {
        get { return this.targetStance; }
        set { base.targetStance = value; }
    }
glossy basin
lean sail
#

oh i misunderstood what you wanted visible

glossy basin
#

I just want some classes to have that specific variable shown on the inspector

leaden ice
#

second, if you want to change how the script is rendered in the inspector, you'd need to write a custom inspector

glossy basin
lean sail
knotty sun
lean sail
#

Yea was just wondering because they said "ever" which i assume meant every case

knotty sun
#

not sure about this

get { return this.targetStance; }
        set { base.targetStance = value; }
#

shouldn't they both be base.

lean sail
#

@swift falcon why u X react? it does work

trim hearth
#

Hi all. Maybe somebody can help me. I tried since a long time now to solve this problem, but all the solutions are not really statisfying.
I am programming a 3d game and when I jump at walls and trees and everything that stands upright, my character gets stuck on the side of it.

I tried all these things:

  • raycast forward and backward and stop movement and add a force down - this seems not really working for all situations, as the raycast is not seeing everything and backward raycasting does not seem to work either
  • adding material with zero friction to all the walls and trees and the player - this works, but is it really the idea to set the zero friction material to everything vertical ?
  • Sweepcast is somehow not good as it is casting the floor and low object too....

Has anybody here a good solution for that? I hope I found the right channel for my problem awkwardsweat

lean sail
lean sail
undone whale
#

I have problem with cameras, I want to add card system on top of my 3d game, and I've setup overlay camera to handle card system. And if something is closer to game camera than cards are to overlay camera then it is still on top of my cards. How to handle that overlay camera is always on top no matter what?

swift falcon
heady iris
#

you get a serialized field

heady iris
#

[field : SerializeField] public int Property { get; private set; }

swift falcon
#

Let me try this out.

heady iris
#

it looks normal

#

with one interesting caveat

#

[field : SerializeField] public int property { get; private set; }

#

this will show up lowercase in the inspector

#

very weird looking

swift falcon
#

Test code:

        [SerializeField]
        private int Auto { get; set; }

Rider:

heady iris
#

you forgot [field : at the start

lethal shell
#

Sorry, I want to ask questions about the topdownengine package. Which channel should I go to?
sorry to bother you

heady iris
#

that makes the attribute target the backing field

#

otherwise, it targets the property, which is not useful

swift falcon
#

I think I know this syntax for naming the attributes explicitly for the language token -- I've seen it used for assemblies.

#

Okay so for now it doesn't serialise default values.

        [field: SerializeField]
        private int AutoPotto { get; set; } = 69;
heady iris
#

no, it serialized the 0

trim hearth
heady iris
#

adding a field initializer doesn't do anything to the already-serialized value of 0

#

resetting the component or adding a new one will make the field initializer's value show up

swift falcon
#

okay, so resetting it shows that it works

#

alright, I'm sold

lean sail
trim hearth
#

ah o.k.

glossy basin
trim hearth
leaden ice
lean sail
#

ah i see what u mean

swift falcon
#

Why is System.Text.Json.JsonSerializer an internal class here?

#

Newtonsoft doesn't support ReadOnlySpan unfortunately.

heady iris
#

ReadOnlySpan sounds extremely weird to serialize

#

What are you doing?

swift falcon
#

I'm trying to achieve this:

var response = System.Text.Json.JsonSerializer.Deserialize<ResponseObject>(
    downloadHandler.nativeData.AsReadOnlySpan()
);
heady iris
#

Broader scope.

swift falcon
#

What/How do you mean?

heady iris
#

What are you doing ?

#

Oh, I get it. You’re trying to deserialize the result of a download

#

I thought you were trying to serialize something with a ReadOnlySpan in it

#

You should be able to get a string out of that span. Would have to look closer

#

at dinner rn

swift falcon
#

I don't want a string from a span if I can help it!

#

I'm trying to use this class but it's marked as internal for some reason. Not sure.

#

The documentation states it is also available as a NuGet package, which would mean I could potentially get its DLL somewhere if needed.

worn night
#

Hello! Hope you are having a great night! I am having some struggles with deciding what architecture to use for my next Unity Project... Basically, I have been doing projects for fun for a while but now it's gotten kinda professional... so I wanted to take it serious!

#

I have been looking at MVC, but then read that it's not that great... I have tried to learn about architecture for a while but it all seems really project-specific which kinda makes sense

#

So my question is, how I can know if I'm doing things properly? Should I use MVC (Model View Controller)? Or go for another route? What's your experience?

heady iris
#

A lot of it is project-specific

swift falcon
#

Also something I am learning to judge only now: use the profiler to guide your architectural decisions.

worn night
#

I see... Honestly, I'm kinda nervous because I'm the one in charge of that and I don't want to make people have problems because of me

#

So I have been struggling to get it right

#

But yeah, there are no clues to that

swift falcon
#

No way to have the cake and eat it too.

heady iris
#

i just look for what feels nice to use

#

does it spark joy? it is good architecture

worn night
#

Mhhh

heady iris
#

one thing I've gotten into the habit of: the player is not special

#

everyone is an Entity with a Brain that tells it what to do

swift falcon
#

Don't focus on the humans you have no control over, focus on the performance which you do have control over.

#

Then write things which don't make your eyes hurt.

worn night
#

I understand, yeah

heady iris
#

i've gone through several games and, generally speaking, each one is better-structured than the last

#

doing game jams is a good way to QUICKLY gain experience there

#

I made a soulslike last last year and I took the opportunity to learn how to use state machines properly

#

(using the Animancer package, specifically)

worn night
#

I have done some kinda advanced projects for a while now but I wanted to start using some more professional techinques

swift falcon
#

Making somewhat-accurate aircraft movement does involve scouring the source code of physics engines underneath the hood, for example.

worn night
#

I don't want to think of doing that right now hahahah

#

But hey, thanks for the quick talk, kinda got overwhelmed in there for a bit and needed to chat

swift falcon
#

Go do those game jams, I didn't so I generally suck :P

heady iris
marble halo
#

So I found this script for moving platforms using a character controller

#

it works pretty well but it has one problem

#

You continue to move on the platform until you fall on something else

#

For example if I jump, i still move with the platform

#

How do I make it so that it if Im not on it, i wont follow it?

heady iris
#

you'd need to set activePlatform to null the moment you aren't touching a platform

marble halo
#

I tried this and it doesnt work if(hit == null) { activePlatform = null; }

swift falcon
#

I imagine KCC or other kinematic movement logic allows tons of optimisations if one doesn't target physics.

marble halo
#

I find kcc a bit complicated

#

like for some reason if i use kcc i keep falling right

heady iris
#

it's a little harder to set up than the default character controller, for sure

#

i like it

heady iris
lean sail
swift falcon
heady iris
#

i'm not sure if you'll get those from the character controller

heady iris
#

maybe you can just clear the active platform every frame. i'd have to stare at the script harder to figure out if that works

swift falcon
lean sail
#

it just inherits from collider so it should work

heady iris
#

ah, right

lean sail
#

depending on the gameplay possible, might need to store what platforms are currently in contact then only make it null if none are in contact

#

like if 2 sliding platforms are next to each other, making it null might just make you stay still

marble halo
#

tried collison exit doesnt work

#

actually to hell with this script

#

Why do guides keep gaslighting me?

lean sail
#

they arent, and thats not at all what gaslighting means lol

#

if you dont understand whats happening in the guide, you wont be able to edit it

marble halo
#

well it feels like it, cause everytime i use one its got something wrong in someway

swift falcon
lean sail
knotty sun
low horizon
#
public class CustomLight
{

}
public class CustomPointLight : CustomLight
{
         public float radius;
}
            List<CustomLight> lights = new List<CustomLight>();
// in a for loop
            CustomLight currentLight = lights[i];
            
//cant get this because the class can be anything, how can i tell my compiler that it is %100 a point light?
            currentLight.radius

how can i get that radius property if i am sure it is a point light? how can i tell my compiler?

swift falcon
knotty sun
swift falcon
#

It's supposed to work with .NET Stndard 2.0+ if I have the correct DLL.

knotty sun
#
knotty sun
swift falcon
#

Yep, that's what I was thinking

#

anyways I'll do that

knotty sun
#

certainly got nothing to do with ReportGeneratorMerged dll which is what you are using

pastel halo
#

Hey, I'm still trying to figure out how to push/extract values from classes to create a debuff system. i've got two enums that im trying to equate in order to use a enum switch for each (but they can't be compared since they are considered two diff enums not one). The values are then pushed into a UI prefab which spawns the debuff icon + timer to notify when it'll wear off.

Would you use some kind of return value in the switch enum? and how would that be done if so? Also trying to incorporate a scriptable object, but unsure how and if that'd be an array, or per variable (i.e. "burningDamage = debuffSO.damage"; "iceDamage = debuffSO.damage";)

knotty sun
#

well the easy way to compare enums is to cast them to int

pastel halo
#

Gotcha, does my setup look correct for what I'm trying to do? Unless there's a better method than comparing two enums

knotty sun
#

I do not look at screenshots of code

pastel halo
#

Ok I can pastebin all 3

knotty sun
#

it is also 2am so I aint gonna examine your code either

pastel halo
#
#

O gotcha fair enough

vague jolt
#

if i do nodes.Remove(node) and node does not exist in the list do it get an error ?

wide terrace
vague jolt
tender vault
#

I have this issue where my z axis movement isn't working but my x axis movement is?

vague jolt
#

how do i make the inspector display this

public List<List<ConnectionsV2.References>> connectedNodes = new List<List<ConnectionsV2.References>>();
vague jolt
tender vault
# vague jolt be more clear this is not enoght for you to get help, proved how is not working ...
    if (rigBod.velocity.x != 0 || rigBod.velocity.z != 0 && Input.GetKey("left shift"))
        {
        hMulti = 6.2f;
        zMulti = 6.2f;
        } else hMulti = 3.2f; zMulti = 3.2f;

        //Move Input to Horizontal string
        Move = Input.GetAxis("Horizontal") * hMulti;
        Depth = Input.GetAxis("Vertical") * zMulti;
}

        //Fixed Update method
private void FixedUpdate()
{
        //Vertical movement velocity update
        rigBod.velocity = new Vector3(Move, rigBod.velocity.y, Depth);```
#

unsure of how to format

#

hMulti and inputgetaxis horizontal work fine

vague jolt
vague jolt
wide terrace
tender vault
#

No it's 3D, I'm trying a paper mario type

#

its a pill shaped collision box though despite being a quad with a sprite on it

vague jolt
#

the problem is here

#

classic rookie mistake

#

else hMulti = 3.2f; zMulti = 3.2f;

tender vault
#

you can't do the double ;?

#

{} bracket it?

vague jolt
#

else hMulti = 3.2f; zMulti = 3.2f; this means that else hMulti = 3.2f and always zMulti = 3.2f;

vague jolt
#

else works like if

tender vault
#

Lol damn its been a moment since I've tried unity

#

thanks mine_lovers

vague jolt
tender vault
vague jolt
#

oh sorry

wide terrace
#

no problem 😅

vague jolt
#

didn't notice

tender vault
#
        {
        hMulti = 6.2f;
        zMulti = 6.2f;
        } else
            {
            hMulti = 3.2f;
            zMulti = 3.2f;
            }```
#

Like this?

#

GOT IT the z axis was locked

vague jolt
#

so i just implemented DFS to my game and i wanted to see it working so I added the following code to see it working.

        if (visualize)
        {
            node.originStructure.GetComponent<SpriteRenderer>().color = Color.blue;
            DateTime startTime = DateTime.Now;
            TimeSpan duration = TimeSpan.FromSeconds(1);

            while (DateTime.Now - startTime < duration)
            {
                Thread.Sleep(10);
            }
        }

But it does not update the color of the gameobjects untill the end, some one knows how to solve ?

lean sail
#

what are u trying to do with that code..

fluid lily
#

Do I have to do Async scene loads in a coroutine? Or if I don't care when it is done I can just call it and forget about it?

leaden ice
vague jolt
#

still if you know a better method

leaden ice
#

No game time or frames will pass while you sleep the main thread

vague jolt
leaden ice
#

You won't be able to see anything working

lean sail
#

that is not what the code is doing

#

you are just straight up freezing the game

vague jolt
leaden ice
#

Do not ever use Thread.sleep in Unity

vague jolt
vague jolt
# leaden ice https://discord.com/channels/489222168727519232/763495187787677697/1121251574530...
    void Initialize()
    {
        foreach(ConnectionsV2.References node in nodes)
        {
            if (notVisitedNodes.Contains(node))
            {
                visistedNodes = new List<ConnectionsV2.References>();
                adjacentNodes = new List<ConnectionsV2.References>();

                //after we reset everything we run DFS

                DFS(node);


                NodesNetworks nodesNetworks = new NodesNetworks();
                nodesNetworks.network = visistedNodes;


                connectedNodes.Add(nodesNetworks);
                visistedNodes =  new List<ConnectionsV2.References>();
            }
        }
    }
``` here i wait for the function to finish before gointg to the next sets of nodes, how do i make this stack wait for DFS to finish ?
leaden ice
#

make the DFS itself a coroutine

#

as mentioned

#

this code is irrelevant

#

the DFS itself is what matters

vague jolt
leaden ice
#

if you want something to happen at the end of the DFS, call it at the end of the DFS

#

or have another coroutine run the DFS coroutine and yield on it

lean sail
#

I dont know why but i feel like the DFS function isnt an entire DFS, unless u are actually running the algorithm many many times

vague jolt
leaden ice
#

I would assume a function called DFS would be an entire DFS

lean sail
#

either way though, u can just store the results of the DFS and have another coroutine run through that loop, highlighting it blue with a yield between each iteration

leaden ice
#

my guess is that you probably unfortunately wrote it recursively

lean sail
vague jolt
#

is that bad ?

vague jolt
#

XD

leaden ice
#

bad tutorial

#

recursive code is basically for school

lean sail
#

i wouldnt call it horrible, but theres no reason to use recursion in c# ever basically

leaden ice
#

it's generally bad in practice

#

especially for something like a DFS

lean sail
#

its never more optimal in c#

leaden ice
#

it's less efficient than just using a Stack

#

and it will make it much much harder to do what you want

vague jolt
#
    void DFS(ConnectionsV2.References node)
    {
        notVisitedNodes.Remove(node);
        adjacentNodes.Remove(node);
        visistedNodes.Add(node);
        

        AdjecentsNodeAdder(node);


        if (visualize)
        {
            node.originStructure.GetComponent<SpriteRenderer>().color = Color.blue;
        }


        if (adjacentNodes.Count != 0)
        {
            DFS(adjacentNodes[0]);
        }
    }

This is the code i wrote, i should i instead make a while loop that keeps looping untill all is done ?

leaden ice
#

well sure but you need either a Stack or a Queue to hold the fringe nodes

lean sail
#

honestly i would separate the visualization from the DFS regardless

vague jolt
leaden ice
#

no

#

well you can make a stack efficiently with a list

#

but a stack specifically has Push and Pop functions which semantically work a certain way

#

regardless when you do it non recursively it is easy to add yields to it

#

e.g.

while (fringe.Count > 0) {
  var current = fringe.Pop();
  // process the thing

  yield return new WaitForSeconds(time);
}```
#

much simpler than in the recursive approach

lean sail
#

its been so long since ive used DFS, but that original code really doesnt look like recursive dfs to me

vague jolt
vague jolt
vague jolt
leaden ice
#

when you call DFS the whole thing happens instantly

lean sail
leaden ice
#

that being said you could do the DFS instantly, and just walk the returned list slowly

#

yeah

vague jolt
#

yeah i will do that

vague jolt
zinc flare
#

hey, I have a bunch of procedurally generated meshes strung together all under one parent object. To spawn trees on them, my first thought was to choose random vertecies in each mesh and spawn trees on those. but my code doesnt work. does anyone know how to help? thanks.

using System.Collections;
using UnityEngine;

public class RandomTreeSpawner : MonoBehaviour
{
public GameObject treePrefab;
public Transform parentObject;
public int numTrees = 10;

void Start()
{
    SpawnTreesOnRandomVertices();
}

void SpawnTreesOnRandomVertices()
{
    MeshFilter[] meshFilters = parentObject.GetComponentsInChildren<MeshFilter>();
    Debug.Log(meshFilters);

    foreach (MeshFilter meshFilter in meshFilters)
    {
        Mesh mesh = meshFilter.mesh;
        Vector3[] vertices = mesh.vertices;
        int numVertices = vertices.Length;

        for (int i = 0; i < numTrees; i++)
        {
            int randomVertexIndex = Random.Range(0, numVertices);
            Vector3 randomVertex = vertices[randomVertexIndex];
            Vector3 worldPosition = meshFilter.transform.TransformPoint(randomVertex);
            Debug.Log(worldPosition);

            GameObject tree = Instantiate(treePrefab, worldPosition, Quaternion.identity);
            tree.transform.parent = meshFilter.transform;
        }
    }
}

}

there are no errors, but when the game is run, nothing happens

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
#

And:

nothing happens
Nothing? What about your log statements?

zinc flare
leaden ice
zinc flare
#

true

leaden ice
#

Debug.Log(meshFilters); is just going to print the type (hence your log showing an array)

#

but if that's all that prints my guess is the array length is 0

#

you said the stuff was procedurally generated, so maybe that generation hasn't happened yet by the time this code has run - hence the empty array

thorny onyx
#
    {
        Debug.Log("MouseOver");
    }``` why tf does this not work its a ui element and has a box collider
zinc flare
#

yeah the array is empty

#

how can I delay the code just a little bit for the meshes to generate?

should i use WaitForSeconds() ?

prime sinew
#

There's the event trigger component

leaden ice
#

or call this code after calling the mesh generation code

zinc flare
#

okay thanks so much!

thorny onyx
#

ohh

#

thats pretty nifty!

leaden ice
#

you can also add IPointerEnterHandler to your script

thorny onyx
prime sinew
thorny onyx
#

ya i got this

#

oh

#

that too

#

thanks

leaden ice
#

yes that is the event trigger

rugged storm
#

i asked this earlier but no one answered, whats the best way to basically just render a 2d array of colors to the screen

#

i want to make a game similar to noita and im trying to render the elements to the screen

upper pilot
#

How do I use OnTriggerEnter2D(for 2D game) or other built in collision events with disabled collider?(I don't want collision to be affected by physics etc so I want to disable it, but keep the events triggering)

#

so I want to detect a collision, but not actually collide(not be blocked by a collider) i.e. allowing the player to walk through walls, but detect when player collides with the wall(or when player is inside a wall etc)

prime sinew
#

Just it being a trigger will make it not be affected by physics though @upper pilot

shell scarab
#
// strings s1 - s10 are 19 random numbers strung together (first being random from 0-8 so it doesn't go over the long limit)
string result = roomdata;

Regex.Replace(result, @"=1=|=2=|=3=|=4=|=5=|=6=|=7=|=8=|=9=|=10=", m =>
{
    Debug.Log($"Match Value: {m.Value}\ns1 Value: {s1}\ns2 Value: {s2}");

    return m.Value switch
    {
      "=1=" => s1,
      "=2=" => s2,
      "=3=" => s3,
      "=4=" => s4,
      "=5=" => s5,
      "=6=" => s6,
      "=7=" => s7,
      "=8=" => s8,
      "=9=" => s9,
      "=10=" => s10,
      _ => "",
    };
  });

  Debug.Log($"result: {result}");

  return result;
```Why is regex not replacing? The debug statement lists out the `m.Value`s correctly, but the result is the unmodified`roomdata` string. Even if it wasn't matching something in the switch statement, a match should still get replaced with "" right?
quartz folio
#

Because strings are immutable and you need to use the string returned by Replace

shell scarab
#

i just realized that, 😭

#

been running into too many easy problems today, time to take a break for a bit i suppose.

swift falcon
#

You take a break and the problems are doing pushups and getting stronger.

swift falcon
#

I will be learning unity for a school study to compare between two procedural map generation algorithms bec unity has alot of tutorials on procedural map + it has profiler which is important in order to compare. However I wanna learn Unity tools more than learning how to make a game bec I just need to understand these two algorithms and learn how to alter them to check different scenarios. For this reason I wanna focus on the tools of unity, anyone knows agreat free course/tutorial? on youtube

dense tusk
#

ello lads. i'm working on implementing sound effects into my project like footsteps, crouching, jumping, etc. my question is what might be an efficient way to go about doing that if i plan on including different sounds for the terrain? i reckon a switch statement would work, but is there a better method to doing this than putting a switch statement inside of each switch statement? it doesn't seem like it wouldn't work, but i'm just wondering if there is a better way

prime sinew
# dense tusk ello lads. i'm working on implementing sound effects into my project like footst...

Hi, to be honest, I'm not sure if this will be relevant, but maybe skim through this and see if it might help?
https://www.youtube.com/watch?v=nqAHJmpWLBg

Check out the Course: https://bit.ly/3i7lLtH


Want cleaner code? Keep an eye out for code smells in your unity3d project and c# code.. We'll talk about why switch statements can indicate architectural issues in your code, how to tell if they're actually an issue, and some alternatives to make your unity project and code architecture ...

▶ Play video
rugged storm
#
        Vector2Int startPixel = new(Random.Range(0, mapdata.GetLength(0)), Random.Range(0, mapdata.GetLength(1)));
        for (int x = startPixel.x-2; x <= startPixel.x+2; x++)
        {
            for (int y = startPixel.y-2; y <= startPixel.y+2; y++)
            {
                if (x < 0 || x > mapdata.GetLength(0) || y < 0 || y > mapdata.GetLength(1)) { continue; }
                mapdata[x,y].Update(this,x,y);
            }
        }```
im getting index out of bounds errors, shouldnt the if statement avoid this?
cosmic vector
#

= not >

#

assuming mapdata is 0 based. The index where x == length or y == length is not valid either