#archived-code-general

1 messages · Page 285 of 1

tall salmon
#

so since it was a dying particle VFX

#

i created it as a whole gameobject

#

and just instantiate it

rigid island
#

makes sense

tall salmon
#

so since its another gameobject it doesnt destroy with the destroy(GameObject)

#

ty my man

#

you are really helping me

rigid island
#

np !

tall salmon
#

you spent the last hour here with me and helping without even knowing me

#

cheers for more people like you on the world!

tall salmon
rigid island
#

sure

tall salmon
#

im setting it as color and it says it is ambiguous between system.drawing.color and UnityEngine.Color

#

i literally just did ctrl c ctrl v because im honestly fed up with my nonsense XD

rigid island
#

its the editor auto-adding namespace

tall salmon
#

the namespace ?

rigid island
#

those using statements up top

tall salmon
#

yep

rigid island
#

those are namespaces

tall salmon
#

but i dont have those

rigid island
#

think of them like folders your scripts belong to

tall salmon
#

yes i have

#

why are they there ?

rigid island
#

delete the system.drawing one

#

since it has a Color inside of it

#

the computer doesn't know which Color you want, from UnityEngine or System.Drawing

tall salmon
#

alright

#

and they got auto added?

#

i didnt add those

rigid island
#

usually visual studio does that when you paste code

tall salmon
#

damn

rigid island
#

you can delete all the dark gray ones

tall salmon
#

oki!

#

ty!

rigid island
#

could disable that feature for paste if you'd like

tall salmon
#

hmm idk it could be usefull in future moments right ?

#

it just made me f up because i was lazy

#

i think

rigid island
#

sure just be aware of it

tall salmon
#

maybe im wrong

#

oki!

#

ty again!

stoic mural
#

Hello! this may be a really obvious question but I cannot figure it out for the life of me var projection = Vector3.Project(vectorOfTarget, transform.right); I have this projection and I just need to get the length of it. Does anyone know how?

tall salmon
#

(hope i dont have to ask again for help xd)

rigid island
#

no worries lol

#

just here tryina get my npc to queue on line for snacks xD

tall salmon
#

xD

#

srry coreyy but i have no clue how to do that

stoic mural
# rigid island magnitude iirc

oh it is, ok in that case I have another problem lmao. I'm trying to make a tank rotate so that its bullet will hit a player if it is moving in a constant direction.

#
private void RotateToShootPlayer()
{
    Vector2 direction = player.transform.position - transform.position;

    var vectorOfTarget = player.GetComponent<Rigidbody2D>().velocity;
    var projection = Vector3.Project(vectorOfTarget, transform.right);
    var vectorOfProjectile = transform.right * 12f;

    float angle = (Mathf.Atan2(direction.y, direction.x) + Mathf.Asin(projection.magnitude / vectorOfProjectile.magnitude)) * Mathf.Rad2Deg;

    transform.rotation = Quaternion.Euler(Vector3.forward * angle);
}```
#

This is my code so far and it's so close to working but there is just something I am not doing right and I can't see it

latent latch
#

are you just trying to do rotatetowards

stoic mural
rigid island
#

like prediction

stoic mural
#

well its not really a prediction it can be done by a calculation im just doing it wrong

#

You can figure out the angle the tank needs to rotate using trigonometry but that is only if the player is moving at a 90 degree angle so you have to project the players direction onto a vector at 90 degrees then use that projection in the calculation but im doing it wrong somehow

rigid island
#

my trig math is kinda dogshit sorry UnityChanLOL

#

made a tank game myself 2 days ago my enemy just shoots directly at you lol

stoic mural
#

yeah, unfortunately I have to do this for a uni assignment 😭

little meadow
stoic mural
latent latch
#

one of those things you'd find on stackoverflow

stoic mural
#

yeah I've searched everywhere and can't find a solution

hasty canopy
#

@stoic mural this is pretty simple task logically

First you calculate "predicted position of player when the bullet will reach him"

Let's call this position predictedPos

Now all you have to do is transform.rotateTowards and give predictedPos as parameter

#

The hardest part here is just to count where player will be when bullet reaches him

stoic mural
#

Yeah, for my task the bullet has to be 100% accurate. It can never miss

stoic mural
latent latch
#

Projectile motion and interception gives a lot of good answers and SO does seem to have a lot of posts about it

stoic mural
#

I have to use the players location, and velocity and use it to get a clockwise angle in degrees. That is the way I need to code it. All of the stuff on SO doesn't do that and they calculate the position that the player will be in over time then just make the projectile go towards that position.

little meadow
stoic mural
little meadow
#

And what exactly did they tell you?

stoic mural
# little meadow And what exactly did they tell you?

Shots aimed at the player should hit if the player is not moving, or if the player is moving at a constant speed. To avoid hits, the player must need to change while the shot is travelling. As input to the system you will be given the player’s relative location and velocity. You must return the relative clockwise angle in degrees needed to hit the player.

little meadow
#

So, what SO does and then you convert it to some degrees 🤷‍♂️

bold pewter
#

where can I ask for help with something in Unity?

little meadow
spring creek
#

This is obviously a code channel, so it's for programming issues

bold pewter
#

Thanks

#

It was with lighting found it hand

mental rover
stoic mural
stoic mural
remote dirge
#

Okay, so for my game's main fighting screen, the enemies (all of them are bosses) come one at a time, and a new one only comes after the previous enemy is defeated. Because they come one at a time, is there a need to try using scriptable objects for their stats?

mental rover
spring creek
spring creek
remote dirge
#

I'll also admit, in regards to my question, I have no idea how to really use scriptable objects for stats for enemies, so I'll probably be asking a lot more questions about that.

spring creek
#

SOs would be very helpful in having boss varieties

spring creek
#

Then on the boss class script, it would have a field for the scriptable object, and you drag its specific stats SO into that field

#

Then the boss uses that SO to populate the data in its class

remote dirge
#

Okay, I think I understand a little better.

spring creek
#

You do not want to modify the values of the SO at runtime

stoic mural
remote dirge
#

I was asking because the fighting for the main bosses will be rather primitive, simply attack, they attack, you both heal according to your magic stat at the end of the turn, it isn't like a more fleshed-out system.

spring creek
remote dirge
#

I'm looking at the fighting of gods from ITRTG as an example for the combat.

stoic mural
little meadow
#

Just do what SO says to find where projectile would hit the player 😋

spring creek
stoic mural
stoic mural
#

Hence why im here lmao...

spring creek
stoic mural
little meadow
# stoic mural I can't make any sense out of it

Well, target is moving and bullet is also moving... to find where one will hit the other, you need to solve an equation on t (t being time) where PlayerPos + PlayerVelocity * T = BulletStartPos + BulletVelocity * T
But you don't actually have BulletVelocity... you have its length and that's the part that you need if you do what the SO answer says. You basically are aiming at finding this T and where player is as that time, because that's a place that both the player and bullet will reach in T time.
Does that help making some sense out of it?

mossy snow
#

he does have bullet velocity, it's 12 units/s

stoic mural
#

the velocity of the bullet is the tanks transform.right * 12f

mental rover
remote dirge
#

!code

tawny elkBOT
little meadow
#

you don't know that velocity, yeah, you know the speed, but not the direction, that's what you're trying to calculate

stoic mural
#

I'm trying to calculate the angle in degrees to rotate the tank in order for it to shoot the bullet striaght and hit the player along its course

remote dirge
#

Trying out some scriptable objects for boss data. How does this look so far? (also sorry if I'm not formatting this correctly.)

'''cs
void Start()
{
bosscurrentHP = bossMaxHP;
}

// Update is called once per frame
void Update()
{
    
    bosscurrentHP = Mathf.Clamp(bosscurrentHP, 0, bossMaxHP);

}

'''

little meadow
mental rover
stoic mural
remote dirge
#

What I'm trying to go for here is, when starting, each boss's current health is set to their maximum, and that their current health cannot go below 0 or above their max health. I can set it above the maximum health in the editor, but will this code still work?

#

Again, I'm not good with scriptable objects at the moment, so sorry if this is a silly question.

hollow knoll
#

Hi! how can i make a boat system where you gotta pull the rope in the boats motor it will start the engine?

#

if someone knows pls tag me to the answer

mental rover
#

you'll need to switch your brain on at some point and really think about the problem to get an understanding of it

stoic mural
#

I am not ignoring them I just do not understand properly

#

I am trying my hardest to understand what I am reading but I have been working on this problem for over 7 hours straight now

latent latch
mental rover
mellow sigil
remote dirge
mellow sigil
stoic mural
# mental rover I mean, Pulni typed out a pretty great summary of what to think about here: http...

I didn't really understand it.

sin a = o/h

Although we don't know the length of o or h as they each depend upon the variable time, we can still find the ratio. If we say:
v = speed of target
p = speed of projectile
t = time

then:
o = tv
h = tp

so:
sin a = tv/tp = v/p 
 
and, as you can see, the time variables cancel out. What this tells us is that the angle calculation does not depend on the time.

Re-arranging this we can find the angle with:
 a = arcsin v/p

The Unity function Mathf.Asin will perform this calculation.

This solves the simplest case, but in practice, the target is unlikely to be moving at exactly 90 degrees. However, in general, we can project the target's direction vector onto a vector at 90 degrees and use the length of this projection as our value for o.

If we can create this projection, then the solution is the same as the simple case above. The Unity function Vector.Project will create such a projection.

If the target is not directly ahead, the we can rotate our tank until it is. And again, the solution is the same as above.```

I found this and tried to do what it is saying as best I can but I am going wrong somewhere.
mental rover
#

I'm not sure where you found this but it looks very wrong to me

little meadow
#

It is at least somewhat wrong I think, yeah... misses some cases at the very least 🤔 (or perhaps only works in some cases is a better way to put it)

stoic mural
#

Found it on my uni site, lecturer uploaded it to help figure out the solution.

mental rover
#

that's disappointing to hear tbh

stoic mural
#

i mean it obviously works for what they want, the course has been running for years and students before me have tried and succeeded with it

mental rover
#

I think the clue is in the very last note - you have to rotate the tank first, and do this in multiple steps

#

fully leveraging Unity to do the work for you

stoic mural
little meadow
remote dirge
#

Unless I'm just not thinking about it right.

mental rover
stoic mural
little meadow
mental rover
stoic mural
#

Tried to do what SO said and still doesn't do what I want

#

I think what is happening now is that it is shooting behind the player and not infront

mental rover
#

there's at least one mistake in the algebra from the top reply unfortunately

remote dirge
#

Does anyone have tips for making enemy stats work in scriptable objects? I keep trying to wrap my head around them but I’m getting nowhere.

#

Maybe I just need to sleep and try again. I’ll ask later once I’m well-rested.

latent latch
# remote dirge Does anyone have tips for making enemy stats work in scriptable objects? I keep ...
[CreateAssetMenu(fileName = "New Entity Profile", menuName = "Entity")]
public class EntitySO : ScriptableObject
{
    //Entity Info
    [field: SerializeField] public string Name { get; private set; }
    [field: SerializeField] public Sprite Sprite { get; private set; }
    [field: SerializeField] public Animation Animation { get; private set; }

    //Base Stats
    [field: SerializeField] public float Health { get; private set; }
    [field: SerializeField] public float Mana { get; private set; }
    [field: SerializeField] public float Speed { get; private set; }
}```
robust whale
#

How can i fix this? this is my throw code;

        if (Input.GetMouseButtonDown(0)) {
            rb.isKinematic = false;
            interactBase.haveParent = false;
            rb.AddForce(transform.forward * throwForce, ForceMode.Impulse);
            transform.SetParent(null);
            didThrow = Teacher.Instance.isTeacherAngry;
        }
languid hound
#

Does anyone know why EditorLoop spikes every second (pretty much exactly)?

#

It's making up 98.2% of the frame and it's on the exact frames my game freezes for about half a second

#

This is a completely empty project with an action based XR controller and a quad

#

Okay great nevermind it was because I had something highlighted in the inspector...

languid hound
#

Has anybody got any ideas on how to fix this?
_body.position -= leftHand.localPosition - lastLeftPosition; I'm using this line in update to move the body by how far the hand has travelled so it looks like you're grabbing something. Issue being that it's jittery. Not noticably but it is jittery

#

I thought of using lerp to interpolate the movement but that would cause it to not be exact and therefore cause a desync

indigo verge
#

I have a major problem. I have an abstract class for controlling menus, and a pause menu that derives from it, but when I start my scene, which has a pause menu derived from the abstract menu, it, for some reason, removes the variables that are added in the derived class.

Is this just how abstract classes work, or has something gone wrong here?

little meadow
#

something gone wrong... show what you mean in video or screenshots

indigo verge
# little meadow something gone wrong... show what you mean in video or screenshots

Here is my Abstract Class
https://pastebin.com/3yiFHj5T

And here is the Derived Class from it (The disappearing Variables are in the image screenshots)
https://pastebin.com/WFL0gnyy

#

In the screenshots, it shows how, in editor,, all the variables look fine, but as soon as the scene starts, they all disappear, and malfunctions occur

#

Can I just not add variables to the derived classes of Abstracts?

little meadow
#

wait, are the variables disappearing in the inspector? not just heir values, but the variables themselves? when you enter play mode? 😮

indigo verge
#

I have no clue, but SOMETHING is breaking, I'm doing more investigations, it... Might just be an editor bug?

#

The variables inconsistently appear in editor during play mode...

little meadow
#

I'd say restart Unity just in case

#

right after you start it, check if you have any errors in console

#

and whether the stuff appears

indigo verge
#

Oh, no, it turns out, I'm just stupid. Apologies, I accidentally didn't have my "enable/disable" menu inside of the code that actually made it activate when the menu finished sliding on/offscreen.

That, paired with the editor acting weird, convinced me that something was going on.

pure jasper
#

Hello everyone, first of all is the first time I try to do something like this and I need help on a specific thing, I'm trying to recreate the kinetic rotation system of the create mod of minecraft, but I have a problem, I have been able to make it transmit the blocks connected by a boolean system but I would like to make it can transmit the speed of an engine or an object that can vary, ie an engine with a certain variable speed by the player to change the entire sequence connected to the network and even if there is a block that changes this speed in the middle of the network, then also change it for the following blocks. The problem is that I do not know how to make the block a transmit the information to block b, and block b to c... etc. I have this code, does anyone have an idea of how to do it? I would be very grateful. I leave a video so you can see what I mean with the rotation system if someone has not played the create mod

prime sinew
#

!code

tawny elkBOT
pure jasper
#

in my way

static horizon
#

what is the best way to store variables/data such as scores between scenes? I utilize playerprefs right

knotty sun
orchid abyss
#

why is my player not being found?

fervent furnace
#

GameObject is not component iirc

#

and you probably can reference it in inspector directly

orchid abyss
#

even without that it still cant find it

spring flame
#

Hey, I am looking to some kind of comparison/juxtaposition of old vs new unity systems. Not necessarily a comparison of features (but would be nice), but just a comparison of what system corresponds to what other system. I'm trying to google for something like "new vs old systems in unity" but it doesn't really give meaningful answers :P

Some things (I think) I already understand
MonoBehaviors/Components -> DOTS ECS
Old input system -> new input system
old unity UI -> new UI Toolkit
Asset Bundles -> Addressables
BRP -> URP/SRP/HDRP

#

did I get it (generally) right and are there other examples (of legacy vs new things, even if they are still not fully supported)?

tight sphinx
#

hi
im trying to loop a 10 sec video from the 6th sec mark. Anyway I can make the loop be seamless without any pause? Here's my code
using UnityEngine;

using UnityEngine.Video;
public class VideoLoop : MonoBehaviour
{
[SerializeField] VideoPlayer videoPlayer;
void Start()
{
videoPlayer.loopPointReached += Loop;
videoPlayer.Play();

    videoPlayer.playbackSpeed = 1f;
}


public void Loop(VideoPlayer source)
{

    videoPlayer.Play();
    videoPlayer.time = 6f;
}

}

distant citrus
hard viper
#

what is a good way to represent a bunch of menus that overlay on each other in terms of data?
I feel like a Stack makes sense, but Stacks aren’t very good at peeking in the middle, or chopping the stack from the middle.

#

Like final fantasy menus that overlay on each other like main fight menu > magic menu > target select menu

hexed pecan
#

Are you asking performance-wise or what?

hard viper
#

architecture wise

#

i always stress when I add new menus to my system, and it makes me sad

#

i want to be able to easily define new menus, and define the connectivity without a bunch of switch statement nonsense

#

and every time I try, I end up with a system that still sucks to extend

chilly surge
#

A system like browser history, where each menu is basically a new page and a button opening a new menu is just telling the browser to navigate to a new page, is actually not very complicated to build.

#

It's not very common for game menus to get that complex though.

ebon apex
#

can someone let me know why the navmesh agent isnt moving? and why is it flickering so much? is having the .setdestination method in update wrong?

hard viper
#

I currently have a tree-like hierarchy defined for menus. Each menu state is a unique enum value, and the hierarchy lets me know what is supposed to be under it.

And then I added a notification textbox that should be allowed over any other UI state, and it all went to shit

hexed pecan
#

That will fight with the agent

ebon apex
hard viper
#

Part of the reason for the hierarchy is to know: which menus not to disable because they are still supposed to be under, and define which menu states are allowed to go to which ones.

hexed pecan
hexed pecan
chilly surge
hard viper
#

i had something like that, where I manually defined every link like a giant directed graph

#

but it quickly turned into defining a ton of directed links and switch statement cases and shit every time I added a new menu

chilly surge
#

That doesn't have to be the case

hard viper
#

i know, but idk how to make a system that is not stupid

chilly surge
#

Link doesn't have to be a magic string identifier (like URL) or an enum containing every possible page, the link could just be a page factory or even the page itself.

hard viper
#

it was basically a dictionary of <enum current state, enum[] states we can go to>

#

which, was not good

#

i feel like this is something that could be actually easily defined via visual scripting, to actually see the graph

chilly surge
#

I don't think it's necessary to use a graph at all

remote dirge
hard viper
#

it’s just a way for me to visualize. At the end of the day I need 2 things:

  1. Function of current UI state that spits out a bool for whether or not a given menu should be enabled or not
  2. A function of two UI states that spits out a bool for whether or not that transition is allowed or not
#

as long as I can define the functions in a way that allows new menus to be easily added, all is fine

chilly surge
#

In my project where there are hundreds of pages and they can navigate amongst each other, it's really simple: router takes care of navigation to a new page, backing to previous page, and transitioning/displaying the current page. A page is nothing more than an interface that implements specific things for router to use it. And a page going to a different page is simply Router.Push(new NextPageToGoTo(...));.

hard viper
#

at the end of the day, that is similar to a directed graph

chilly surge
#

There's no complex graph dictating which page can go to what, no magic string, no giant enum containing all possible pages, no giant switch. If clicking this button is supposed to bring up a sub menu, just push it to the router.

hard viper
#

it’s a function that can be represented as a directed graph, as opposed to a function that reads a data structure representing a directed graph.

chilly surge
#

Hmm well I might be missing the point why you need to explicitly define which menu can go to another menu, because to me menu A literally cannot go to menu B unless there's a button in menu A with code that explicitly says "router go to menu B"

hard viper
#

but I think the way you define it is like, each page is a vertex, and all links on the page are a list of vertices you can reach from that page, which defines directed edges

hard viper
#

like if I press the wheel button while in the level save screen, I want the extra protection to block the wheel menu from popping up

#

since UI elements can majorly fuck everything up, I use it as an extra layer of redundancy for validation

chilly surge
#

Eh, the way I do it in my would just simply be router is the one listening to wheel button event (since router is the one controlling all of UI) and level save menu's router simply ignores all wheel events.

#

Which means if you are in level save menu and goes to a sub menu of level save, you still can't click open the wheel menu without you needing to explicitly code that into your logic.

hard viper
#

right now I have a router that actually does transitions. Each menu has a separate set of Monobehaviours that call Router.RequestSetUIState(…) to ask nicely that the UI state be changed

#

Router asks UITransitionLogic to validate the transition as a condition of actually going through with it

hard viper
chilly surge
#

That's exactly why you shouldn't do it like that ("validate transition is allowed or not")

hard viper
#

i’m confused

chilly surge
#

Because that's essentially O(n^2), when you have n menus, every menu you need to write n-1 validations to say "is this transition allowed" and you will inevitably miss one or two.

hard viper
#

yes, that is why I did not like the previous method

chilly surge
#

That's why wheel event should just get send to the router and router handle it.

hard viper
#

but I’m doing that right now? Wheel menu recieves input, and sends the event to router, who is smarter than wheel menu

chilly surge
#

Level save menu has a router which does not handle wheel event, so that means when level save menu (and all of its sub menus) is active, all wheel events go to that router which get ignored. In another router where it is allowed, then wheel menu will get transitioned.

hard viper
#

oh you mean to more manually make sure the modes of input get turned off?

chilly surge
#

No

#

I mean there are multiple different routers, the router used by level save menu simply ignores wheel events, where some other routers do allow wheel events and navigate to the wheel menu.

hard viper
#

so let’s say I am in save menu, and click the button for wheel menu on my controller. In your system, are you saying the wheel menu does capture input, sends to router, and router ignores?

chilly surge
#

In my game the main router can handle deep links, whereas router for in game menus like pause screen ignores deep links. It's basically the same idea.

#

So instead of coding the logic of "pause menu cannot activate deep link" you move that logic into the router and becomes "in game router cannot activate deep link"

hard viper
#

i have to think about that a bit more.

#

like how i’d refactor to connect everything

#

I have an idea, actually. My main method is RequestSetUIMode(GameUIType newMode)

#

I could change the signature to RequestSetUIMode(GameUIType newMode, GameUIType requestingUIMode)

#

so the second argument is the menu we are invoking from.

#

that defines a shallow link, and router rejects if the requestingUIMode does not match the current mode.

#

does that sound like a good idea?

chilly surge
#

Is GameUIType the giant enum that contains every type of menu, and the method does a giant switch on it to show the corresponding menu?

hard viper
#

yes, and second is currently kind of yes

#

but proposed to be just if (requesting == current)

chilly surge
#

Yeah that gets painful real fast, every time you want to add a new menu you need to 1) obviously implement the menu itself, 2) add a new enum member, and 3) add a new branch in the method to handle that enum member to show the menu.

hard viper
#

my current method, yes

#
  1. is a necessary evil no matter how you slice it
#
  1. is an awkward undesirable sideeffect
chilly surge
#

Use something like Router.Push(Func<IMenu> factory) (or even simply Router.Push(IMenu menu)), router just needs to know how to handle IMenu and that's it.

#

That way you get rid of 2 and 3.

hard viper
#

oh so it’s an interface

chilly surge
#

Interface, a base class, whatever, some kind of contract.

hard viper
#

i get that. But then I need an instance for each menu to request the router to go there

#

like a menu in the middle would need a ref to the instance of the IMenu it links to

chilly surge
#

Which you will need if you want to pass data between menus without relying on global state.

flat granite
#

i'm watching a tutorial and I already don't like how uneccessarily complicated the code was made just for wasd controlls. can someone tell me if this code can be cleaned up and how i can add support for wired controllers?

#
using System.Collections.Generic;
using System.Numerics;
using Unity.Mathematics;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // movement components
    private CharacterController controller;
    private Animator animator;
    private float moveSpeed =4f;
    // Start is called before the first frame update
    void Start()
    {
        // get movement components
        controller = GetComponent<CharacterController>();
        animator = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        //runs the function that handles all movement
        Move();
    }
    public void Move()
    {
        //gets the horizontal and vertical inputs as numbers
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("vertical");
        
        //direction in a normalized vector
        Vector3 dir = new Vector3(horizontal, 0f, vertical).normalized;
        Vector3 velocity = moveSpeed * Time.deltaTime * dir;

        //check if there is movement
        if(dir.magnitude >= 0.1f)
        {
            // look torwards that direction
            transform.rotation = Quaternion.LookRotation(dir);

            //move
            controller.Move(velocity);
        }

    }
}
#

plus it gives me errors no one in the comment section has

hard viper
#

i literally defined a whole dualshock controller scheme yesterday in like 5 min, just adding it to everything else

hard viper
ebon apex
hard viper
#

because it is really not

#

i wish most of my classes could be as simple as this lmao

flat granite
hard viper
#

you should not put physics commands in update btw

flat granite
#

it says this for vector3 as well

hard viper
#

why did you import system.numerics

flat granite
#

because thats what the tutorial user did

hard viper
#

nothing in this class needs System.Numerics

flat granite
#

actually wait no they didnt somehow they got added after

hard viper
#

that quaternion should be UnityEngine.Quaternion

chilly surge
# hard viper ty, I will have to sketch it out a bit more

Think about it with this example, when you type "burrito" into Google's search bar and hit enter, it goes to a new page, how does the new page know the thing you are searching? That data is passed in the URL with something like ?s=burrito.
The URL is essentially the argument of Router.Push() method, you use that argument to allow router to know which menu to show and what data it should have. It also means that your menus can be general purposed and reused in multiple scenarios, because now the pusher has the ability to feed different data into it.

flat granite
#

idk where math or numerics came from considering i didnt add them. does VS code automatically add it when math is used?

hard viper
#

you need to turn that shit off. it’s in visual studio options

ebon apex
flat granite
hard viper
#

turn that shit off

#

it will sometimes add namespaces that break if you try to build your project

ebon apex
hard viper
#

a lot of times it added UnityEditor.…., and I don’t notice until I build, and like 10 files break

#

shit feature

#

you also get all these random namespaces at the top that you did not mean to use, have no idea what they are for, and now that they are in there, you don’t remember if you actually put it in or not on purpose because it’s been a month since you opened the file

#

and this time, it stopped his code from compiling because it created an ambiguity with a namespace he didn’t need

flat granite
hard viper
#

happens every time

flat granite
#

now i just need to find where in settings that feature is to turn it off

#

is this it?

chilly surge
#

In VS Code this should be the one you want to turn off.

flat granite
#

ahh ok, i was looking under statements, even intellisense and all sorts

chilly surge
#

As a general tip, look at the C# extension settings since the thing you are looking for is about C#.

flat granite
#

will do in the future

chilly surge
#

VS Code's search bar also has a ton of filters you can use and you can type @ to bring them up, eg @ext: will allow you to filter only specific extensions.

flat granite
#

for some reason unity decided to close itself so now i have to wait for it to open back up to test and see if my code works 😭

static matrix
#

is deleting this folder (cache) going to screw me?
I presume its just stuff for quickload

heady iris
#

i suspect that's the package manaegr cache

#

not familiar with where unity puts stuff on linux though

terse plaza
#

hello when ever i import a script it always says that the name is not corect when it is correct

knotty sun
terse plaza
knotty sun
#

If 1 script has errors none of your scripts will compile

rigid island
terse plaza
#

oh

knotty sun
#

In that script alone I count 4

lament lava
#

I'm toggling on a UI canvas using a button and it works perfectly fine in editor, but as soon as I build the game, the button simply doesn't do anything. I've googled this for a while now and a lot of people seem to have a bunch of different small fixes for it (mostly relating to the Canvas Scaler settings), but none of them seem to work for me. I don't know if this is caused by how I'm toggling on the canvas or what and I'm stumped. Btw, all of this is being done in my script for Unity's lobby service, but here's a rough example of how I'm toggling on the canvas: https://hatebin.com/tdecricyjy

heady iris
#

It's possible that the UI is sized differently in your build, and that something is covering up the button

#

Does the button visibly change when clicked, but not work? Or does it not respond to the cursor at all?

lament lava
#

the button clicks normally

heady iris
#

check if it's actually working by logging something in response to the click

#

then look at your player logs

lament lava
#

@heady iris ok so i was messing around with some of the player settings when building and i found out it only works if i use Fullscreen Mode: Maximized Window

#

everything else doesnt work

tawny elm
lament lava
lament lava
lavish frigate
#

Any clue as to why this is always returning false, even though a child wallcheck transform is clearly inside of terrain that is on the correct ground layer?

heady iris
#

how is _groundLayer defined?

lavish frigate
#

LayerMask

heady iris
#

okay, good -- and I presume you've got the right layer in there

lavish frigate
#

Same as my terrain yeah

simple egret
#

OverlapCircle returns an array, that is never null - even if nothing was detected

heady iris
#

I'd sanity check this by setting it to work with any layer

#

no, OverlapCircle returns a collider2D

#

OverlapCircleAll gives an array

#

(i'm finally doing a 2D project, so i know the methods now 😛 )

#

OverlapCircle also has an overload that puts the results into a list, which makes it more confusing

simple egret
#

Right, this is very not much consistent with what OverlapSphere does, wtf

heady iris
#

because this is 2D physics

#

it has different conventions

#

I wish 3D physics could put results into lists...

mild bluff
#

hello. i am new to unity. i have a sprite that is managed through shaders, and when i spawn an instance of the game object containing the sprite, i want to also set the shader's parameters to some initial values. but it does not work

lavish frigate
#

Does a Physics2d call like that ignore stuff like colission matrix and box collider overrides?

heady iris
#

The collision matrix is not relevant here

#

I'm not sure about collider overrides.

#

I would guess they don't matter, since you're just directly asking for things on certain layers

#

not for things that collide with certain layers

mild bluff
#

is there a way to get a rigid body on the parent from a child component's collider?

heady iris
#

i don't think you can directly ask the collider

#

but GetComponentInParent will unambiguously give you the correct rigidbody

mild bluff
#

what if im not sure whether im getting the child or parent?

heady iris
#

If your object has a Rigidbody, then GetComponentInParent will return it

#

It searches yourself and your parents

lavish frigate
#

this func in the same script does work haha

heady iris
#

like how GetComponentInChildren searches yourself and your children

mild bluff
#

i made a typo. "child OR parent"

#

so i have a collider on the parent aswell

#

but i dont control which of them returns first.

#

and i want to get the parent.

heady iris
#

"which of them returns first"?

mild bluff
#

in the raycasthit array

heady iris
#

I don't understand what you're doing

#

oh, you can just ask the RaycastHit for a rigidbody

lavish frigate
heady iris
#

it has a field for that

mild bluff
#

oh alright... should've lead with that lol

#

thanks

heady iris
#

It will be null if there was no rigidbody involved

#

(also, even if you didn't have that, GetComponentInParent would give you the same thing)

mild bluff
#

how would there be a raycast hit without a rigid body?

heady iris
#

a raycast can hit a static collider

mild bluff
#

does it need to be set to static?

#

for that to work?

heady iris
#

no, "static collider" just means "a collider that isn't under a Rigidbody"

#

Having a rigidbody becomes important when you want to receive collision or trigger messages from collider overlaps

mild bluff
#

i was having issues with that originally. did i just have to configure the cast to check for colliders? cause when i last tried it it didn't detect my colliders and i had to use a rigidbody

#

i would note i both have a collider i need to cast and just normal ray casts

heady iris
#

you can tell it whether or not it should hit trigger colliders

#

but having a rigidbody should not be relevant

#

It might have an effect if you've just moved an object with a collider on it

#

The physics system won't know about this until the next physics update

#

(or until you call Physics.SyncTransforms())

#

I dunno if having a rigidbody would change anything there

mild bluff
#

yeah. its so random sometimes. i don't even have that complicated of a setup, but i solved one of my issues by having a collider so im going to stick to it for now. thank you for letting me know i can get the rigidbody from a raycasthit result

celest iron
#

When I add an assembly, Unity says InputAction does not exist inside the UnityEngine namespace?

#

What am I missing?

leaden ice
#

Are you talking about the using directive

celest iron
heady iris
#

Your assembly definition will need to explicitly reference every assembly you need.

#

It won't automatically reference every existing assembly

leaden ice
# celest iron

you need to reference the input system assembly from your Gameplay assembly

celest iron
#

Oh I see

#

I mean, the Gameplay assembly is the only one I made

#

So I'll need to make one for the input then

heady iris
#

No.

#

You need to reference the Unity.InputSystem assembly from your Gameplay assembly

heady iris
# celest iron

Is there a reason you're using an assembly definition?

celest iron
#

Generation code too large, want to separate compile time from gameplay

heady iris
#

your game doesn't compile when you enter play mode

#

oh, I see; you're saying that you have a ton of code for level generation, and you don't want to have to recompile it when you change your gameplay code?

celest iron
#

yes

#

exactly

#

But I got it

heady iris
#

in the assembly definition asset's inspector, reference every assembly you need here

lavish frigate
heady iris
celest iron
#

I didn't know the InputSystem had a whole assembly. I thought everything from Unity would be automatically referenced.

#

And only needed to reference custom assemblies.

lavish frigate
#

yeah, what ill try for now is shooting a raycast to the left from the right wall check, distance being to the player, to see if a wall is in between.

celest iron
#

Good to know thanks

heady iris
knotty sun
#

you're probably using a world space canvas

tawny elm
subtle shore
#

anyone know how i can check code for plagarisim

modern creek
#

You sorta can't.

#

Code is meant to be plagarised. 🙂

#

If you're a teacher - give exams. If you're a student, you're cheating yourself (out of learning how to actually write code).

subtle shore
modern creek
#

Then don't plagarise?

subtle shore
#

i mean its not gonna be zero

modern creek
#

I mean, it sounds like by asking the question.. you're probably doing something you shouldn't be, and you're not really gonna get any help with doing that here.

subtle shore
#

and ive used some help from outside sources so i wanna see the plagarsim

subtle shore
#

for code i dont think that an unreasonable question

modern creek
#

If you've copied and pasted code you don't understand and can't explain well.. that's a pretty obvious case of plagarism.

#

Uh, yeah, it's a bit unreasonable and if you don't understand why.. your time might be better spent learning how to write code instead of learning how to copy and paste it and not get in trouble with your school. 🙂

subtle shore
#

so passive aggressive

modern creek
#

🤷‍♂️

subtle shore
#

😭

#

caesar u got me very intrigued

wide dock
#

If you had wrote most of the code by yourself, you'd know that there's no point in ever using a plagiarism checker. Asking for one repeatedly suggests that this probably isn't the case and you did in fact just copy and paste a bigger chunk of code, maybe changed a few names here and there.

Either way, you'll know the results of running a plagiarism check on your code once you submit it to your teacher, if it's some sort of school assignment that we're talking about here.

icy zephyr
#

Why when the method is run with OnBecameInvisible, then OnBecameVisible does not start, all colliders, there are renders on the mesh:
public class VisibleObject : MonoBehaviour
{
private Renderer meshRenderer;

private void Start()
{
    meshRenderer = GetComponent<Renderer>();
}

private void OnBecameInvisible()
{
    meshRenderer.enabled = false;
}

private void OnBecameVisible()
{
    meshRenderer.enabled = true;
}

}

heady iris
#

I do not understand your question.

mint garnet
#

how do i make it so i can drag in a game object into here

heady iris
heady iris
icy zephyr
heady iris
#

make it public or use [SerializeField] to make Unity serialize it

modern creek
#

@wide dock He really needs to be ... trying to learn how to code from a class, not from tutorials.. ie, copying and pasting entire blocks of code and wondering why it won't compile.... #💻┃code-beginner message

heady iris
icy zephyr
#

okay

heady iris
#

Are you saying that the mesh renderer is being disabled, but is never becoming enabled?

#

That won't run if there are no enabled renderers on the same game object.

icy zephyr
#

yes

heady iris
#

The message is sent when a renderer becomes visible

mellow sigil
#

You don't need to disable the renderer manually. OnBecameInvisible means by definition that the object isn't rendered

mint garnet
modern creek
#

GameIsPaused isn't isGamePaused

mint garnet
#

shit

#

thanks

modern creek
#

and those look like they're on different objects/scripts entirely anyway

mint garnet
#

am stupid

modern creek
#

pause_music doesn't automatically have access to PauseMenu

icy zephyr
heady iris
#

yes, because there are no enabled renderers

#

so it is impossible for a renderer to become visible

modern creek
#

think of your classes/scripts/gameobjects as houses.. or boxes.. your PauseMenu has a boolean called GameIsPaused but your pause_music (which is poorly named, btw?) isn't doesn't have access to it unless you tell it PauseMenu.GameIsPaused

mint garnet
#

ok ill just do it in the same script

icy zephyr
heady iris
modern creek
#

you don't need to but I'd strongly suggest taking a step back and understanding what "objects" are .. like, either from a professor or TA or something..

wide dock
lavish frigate
#

if i have a direction (0,1), and a incoming velocity (x,x). I want the velocity to become (x,1), so where direction is 0 velocity stays the same. How can i easily do this, or will i require if statements?

leaden ice
heady iris
#

that sounds like the opposite, since that keeps the component from incomingVelocity if the direction has a 1

leaden ice
#

Oh wait you want the opposite of that?

little meadow
#

just write a few ifs... 😄

lavish frigate
leaden ice
#

Scale with Vector3.one - your direction

little meadow
#

it's not gonna be cleaner if you do hacky math that only you understand the meaning of

heady iris
#

that Clean Code book has done so much damage to programming

#

(although that's hardly relevant here, lol)

#

i just bellyache about it

barren flicker
#

Hello, is this the right channel to ask for some help regarding coding?

barren flicker
#

TY

#

I have a problem when using cinemachine with spherical worlds. As in any game, i want the player to move in the direction the camera is pointing, so what i tried is to get the local rotation of the camera and paste the "y" component into the player's rotation. I use local rotation because since the player stands on spheres, it has to be aligned with the center of gravity. My solution creates a positive feedback loop where the player rotates, the cinemachine camera tries to follow the player's rotation, the camera's position changed so the player tries to follow it... I've been scouting internet but i couldn't find someone with the same problem regarding spherical worlds and camera controls.

heady iris
#

You shouldn't directly manipulate euler angles.

simple egret
#

First things first, you should NOT directly modify values of a quaternion by copy-pasting someof its compoenents here and there

heady iris
#

(and especially don't modify rotation.y!)

simple egret
#

If you want to do that, then prefer using directions (eg. .transform.forward), where modifying components is legal and its consequences predictable

#

Flatten using Vector3.ProjectOnPlane(), normalize, etc.

barren flicker
#

ohh okay, im new to unity so im just trying to get the squiggly red line go away 😅

simple egret
#

If you have errors, you should post them, and the offending code in question

barren flicker
#

it is not an error per se, mostily a problem where idk how to get the player to rotate without making the cinemachine camera go crazy

simple egret
#

The direction the camera is pointing towards is cam.transform.forward where cam is a variable containing the object which the Camera is on (or the Camera component itself).
I suppose you don't want to fly off if you look straight up and press forwards, so you'll need to flatten it along the ground. For that you'll need the ground's normal direction, ie. the direction that's perpendicular to the ground at a given point. If you're using a ground check that's using a Raycast in the code, then you can get the normal direction pretty easily with that

hard viper
#

when making a font, is there a simple way to make a serialize strings to show characters like emojis or custom characters?

earnest meteor
#

Hello guys. Maybe anyone knows how to download and save image in unity. I did but it cant be open. Or maybe i can change data format?

leaden ice
earnest meteor
#

it shows png in explorer

#

but id does not open

leaden ice
#

well is it actually a PNG image?

#

you're saving it as .png but what is it really?

earnest meteor
#

yes

#

i named it as icon1.png

leaden ice
#

yes you named it that way

#

but is it actually a PNG or not

#

where is this image coming from?

earnest meteor
#

it is png actually

#

on google drive

leaden ice
#

That's your private google drive I can't access it

#

most likely your Unity client can't either unless you gave it authentication credentials too

earnest meteor
#

i gave access

leaden ice
#

it's a JPG

#

not PNG

earnest meteor
#

so i need to save it like jpg?

#

Cool. I gave access as you said and it is working now.

#

thx a lot

#

❤️

leaden ice
#

your URL would have just given a 403 error

earnest meteor
#

Only started work with web in unity. Thx for help again.

raven basalt
#

This courotine is supposed to trigget the destruction sound and then deactivate the gameObject. However, the destruction sound doesn't play properly, the audio keeps on breaking up. How do i fix this?


    private IEnumerator DeathCoroutine()
    {
        collider.enabled = false; //So the player's bullets no longer collide with the enemy
        //transform.localScale = Vector3.zero; // This makes the Object invisible enemyHealth.

        avatar.SetActive(false);
        if (animator != null)
        {
            animator.speed = 0;
        }
        manaDeathParticles.Play();
        audioSource.PlayOneShot(deathAudioClip);
        if (healthType == EnemyHealthType.SpawnManager)
        {
            spawnManager.enabled = false;
        }


            yield return new WaitForSeconds(2); //This delay is here because otherwise the gameObject (and its audio source) will be set to inactive before the death effect can finish playing.

        if (deathBehavior == Death.DestroyUponDeath)
        {
            Destroy(gameObject);
        }
        if (deathBehavior == Death.InactiveUponDeath)
        {
            gameObject.SetActive(false);
        }
    }```
latent latch
#

what happens if you play it outside of the coroutine

#

if you're destroying the gameobject here that has the audio source then you're interupting it too

leaden ice
raven basalt
#


    private void HandleVanishing()
    {

        StartCoroutine(DestructionCoroutine());

        // Handle the boulder when its lifespan expires
        // For example, you might want to deactivate it, destroy it, etc.
        // Reusing the fallingTooFarBehavior for simplicity, or you can define a new behavior

    }

leaden ice
#

where does that run?

#

is this happening each frame for example?

#

this added no new information

#

also this isn't DeathCoroutine

#

it's different - DestructionCoroutine

raven basalt
#

Oh wait I gave the wrong code by accident

#

I have the following in my awake method:

audioSource.clip = rollingSound;

And my destructionCourotine is not working:

    private IEnumerator DestructionCoroutine()
    {
        collider.enabled = false; // So the player's bullets no longer collide with the enemy.
        boulderMesh.SetActive(false);

        destructionParticles.Play();
        audioSource.Stop(); // Stop any currently playing sounds.
        audioSource.clip = null;
        audioSource.PlayOneShot(destructionAudioClip); // Play the destruction sound.

        // Wait for the longer of the two durations: the specified destruction duration or the audio clip's length.
        //float waitTime = Mathf.Max(destructionDuration, destructionAudioClip.length);
        //yield return new WaitForSeconds(waitTime);
        yield return new WaitForSeconds(destructionDuration);

        // Proceed to deactivate or destroy the GameObject after the wait.
        if (destructionBehavior == DestructionBehavior.InactiveUponDestruction)
        {
            gameObject.SetActive(false);
        }
        else if (destructionBehavior == DestructionBehavior.DestroyUponDestruction)
        {
            Destroy(gameObject);
        }
    }
leaden ice
#

Where is this running?

#

Is it happening every frame?

raven basalt
#

This courotine isn't called every frame. Its called once the gameObject's lifespan has expired

leaden ice
#

How?

#

Show the code

raven basalt
#
private void Update()
    {
        Debug.Log("Boulder Position: " + this.gameObject.transform.position);

        // Decrement the lifespan each frame, based on the time passed
        lifeSpan -= Time.deltaTime;

        // Check if the lifespan has expired
        if (lifeSpan <= 0)
        {
            HandleVanishing();
            return; // Skip further processing in this frame
        }

        // Continue with your existing movement logic
        Vector3 movement = Vector3.right * moveSpeed * Time.deltaTime;
        transform.Translate(movement);

        if (transform.position.y < minYThreshold)
        {
            HandleVanishing();
        }
    }

    private void HandleVanishing()
    {

        StartCoroutine(DestructionCoroutine());

        // Handle the boulder when its lifespan expires
        // For example, you might want to deactivate it, destroy it, etc.
        // Reusing the fallingTooFarBehavior for simplicity, or you can define a new behavior

    }

leaden ice
#

unlike what you said

#

this IS running every frame

raven basalt
leaden ice
#

so that's why the sound is playing weirdly

#

because every frame you're stopping and restarting the sound

#

Update runs every frame, and you're calling this in Update

raven basalt
#

I thought the code only played it if the condition if (transform.position.y < minYThreshold) is met?

leaden ice
#

yes

#

it runs when that is met

#

EVERY FRAME

#

because this is in Update

raven basalt
#

ooooooooh

#

How do I make it so it only runs once?

leaden ice
#

use a bool or something

#

to mark when you started the vanishing process already

raven basalt
#

ok thanks so much for the help!

indigo verge
#

I'm working on making a struct that holds a Class Type, and an Enum that determines which menus are compatible with one another, derived from an Abstract Class.

Assuming I have the Abstract Class "BaseMenuController", and the derived classes "PauseMenuController" and "InventoryMenuController", how can I define a variable that can contain either PauseMenuController or InventoryMenuController?

I basically want to set it up so I can give each menu type a list of compatabilities with each other menu type, so you can't open the inventory while paused, pausing closes the inventory, ect, ect, by defining how which classes interact with which other classes.

#

I'm uncertain which type of variable would be best for this.

leaden ice
indigo verge
#

Thank you very much, that works great!

latent latch
hasty sinew
#

Hey gang, let me know if this is the wrong channel for this --

I'm currently experiencing a strange issue with sprites in my build appearing like so.
So far I haven't been able to find a common thread between the sprites. None of these issues are happening in the editor.

Any suggestions as to where to start looking to solve this?

Thanks for any help! (Tagging @indigo summit )

quartz folio
#

If it's only happening on one computer, I would say to upgrade your drivers

hasty sinew
#

Aha good to know. Tried it on my computer and my collaborator's, same issue.
The player character's movement Atlas seems to be the one thing working so it must be an issue with corrupted Atlases.
(Thanks for the compliment on the drawings!!)

dark kindle
#

why is Random.Range inclusive for float max but exclusive for int max?

quartz folio
dark kindle
#

thank

leaden ice
dark kindle
#

ok, thank

lean sail
# fair jackal What does this mean?

inclusive means include, exclusive means exclude. The max value you give it will be included (aka can be chosen) for floats but excluded (not chosen) for ints.

fair jackal
#

Ah ok, and same for minimum?

lean sail
#

no the minimum is just included

fair jackal
#

Oh, no matter what?

lean sail
#

yes, itd be kinda tedious if it wasnt like this

fair jackal
#

I guess

fair jackal
green jay
#

these are the code related to movment and unit selection
[11:29 PM]
everything works fine, however i have an object i created called ground market, it simply is supposed to be a quad as a placeholder at the moment and does nothing but appears where you click once the unit starts moving there. if you have ever played an RTS game when you select a unit and right click to move that unit to a place there is a market or an arrow or somthing on the ground letting you know where you clicked and mine is not appearing
[11:29 PM]
also if i can do anything or you have any tips to make my code more readable please let me know i always want to improve on readability

#

sorry i dont kno0w if this is a beginner question or a general one

#

i am not really a beginner with coding, just game engins and how they work

rigid island
#

don't crosspost

hasty sinew
quartz folio
#

Annoying you had to do that!

indigo verge
#

I have a list of structs, which I'm wanting to use a foreach on, but it's not letting me, I think due to the fact that the function is being called in a different object?

    //Contains the list of interactions between this menu and other menu types
    [System.Serializable]
    public struct MenuCompatabilies
    {
        public MType Type;
        public BaseMenuController menuController;
    }

So I have a list of these on an object

I pass that object to a function in a master object, for processing, I try to use

foreach(MenuCompatabilities menu in Origin)

But it doesn't recognize the MenuCompatabilities struct in the second class. Do I need a copy of the struct in both objects?

#

Here's the class with the Struct in it
https://pastebin.com/sUsBiyT4

and here's the function that's being called, (Called "ChangeMenuStates")
https://pastebin.com/XrtijbuK

I've removed the guts of the foreach loop in it, because it's not recognizing the struct when I type it.

#

I basically just want to loop through a list of structs, and check against their contents

#

but in function held in a class other than the one the struct is defined in

latent latch
#

im not seeing the code you posted up there

#

also probably show the error

indigo verge
#

Me?

latent latch
#

maybe

indigo verge
#

if you have a list containing a struct, can you just foreach the things inside the struct directly?

I assumed you had to foreach the struct itself, but I might be wrong.

I'm not getting an error, it's just not recognizing the name in editor, when I try to type it into it.

So
foreach(MenuCompatabilies menu in originCompatList)

Doesn't work, because it's not recognizing the MenuCompatabilities struct in a function inside a different class being run by the object in question, and I'm not sure what the solution is.

latent latch
#

well, if you can show me where in the code that is cause I dont see it

indigo verge
cosmic rain
indigo verge
#

It's a public struct in the other class, though, do I need to have duplicates of the struct in question? Or put it in something like a public static so it is recognized globally?

latent latch
#

what does the error say

indigo verge
#
Error    CS0246    The type or namespace name 'MenuCompatabilies' could not be found (are you missing a using directive or an assembly reference?)    
#

it's not able to access the Struct, but I don't know what the step to resolve that cleanly is.

cosmic rain
indigo verge
#

type signature? I don't understand.

    //Contains the list of interactions between this menu and other menu types
    [System.Serializable]
    public struct MenuCompatabilies
    {
        public MType Type;
        public BaseMenuController menuController;
    }

This is the struct in question, and it's nested in a public abstract class?

cosmic rain
#

You also have MState and MType in a similar situation. How do you access these types from outside the class?

indigo verge
#

I don't understand what you mean, I'm really sorry.

cosmic rain
cosmic rain
latent latch
#

may need to do BaseMenuController.MenuCompatabilies, otherwise take it out of the class the struct

#

it doesnt look like it's in a namespace

cosmic rain
#

Mao, don't spoil.notlikethis

latent latch
#

lol whoops

indigo verge
#

Thank you, I think that's the solution I needed.

#

I was literally just asking because I didn't know what specific solution I needed to access it, since I had never run into this issue before.

#

and it's kind of an obtuse problem to google.

cosmic rain
#

You just need to google "C# accessing nested types"

#

Or just "C# nested types"

indigo verge
#

Yeah, now I understand the concept more fully. I just needed to know what I had done wrong.

indigo verge
sudden stump
#

Would I need to create a new health class specific to the GameObject if I want to utilize ScriptableObjects?

sudden stump
sudden stump
#

So there's Health.cs and XPOnDeath.cs

cosmic rain
sudden stump
#

Constant

cosmic rain
#

Okay, then why would you need several SOs?

#

I guess to define different values, but then I don't get the question

#

Wdym by "create a new specific health class"?

sudden stump
#

For more context, I have a game object that gives the player XP when it's destroyed. There are three XP givers prefabs, each one has more XP and more XP than the previous one. There's going to be 500 or so of those spawned on the map, and when you destroy a lot, the game's going to spawn more to keep up. Would I need scriptable objects to change their HP and XP values?

#

Afaik to make a scriptable object you need to specifically define it in your class, and that'd just add more and more fields in the inspector that other game objects won't use

cosmic rain
cosmic rain
sudden stump
#

So no solution to this

#

Oh well, I'll just deal with it. 500 objects isn't much in the grand scheme of things, especially since it's a 2d game

cosmic rain
#

You'd usually have a formula that gives you higher values procedurally, instead defining the them manually for this kind of stuff.

solar hawk
#

Anyone has experience with lyra? Been on this for like 12 hours, Ue5 source build is compiled, The Lyra game game is compiled, 12 hours later and every fix from google it still wont allow me to build a dedicated server :S

earnest meteor
#

Hello. Maybe anyone know how to load random pictures from the folder?

knotty sun
earnest meteor
sweet yoke
#

I made some kind of mobile rhythm game, according some of my testers when using bluetooth headphones the audio is very async.
For the main modes i have implemented a calibration system already which seems to work well.
But for some short modes i cant make use of the calibration as im playing many short audio clips at the time a entertrigger responds.

What could be my best option to fix this issue ?

chilly surge
#

You can use some assets to lower the delay, but really there's no way but to tell players that it's the reality when using a high latency audio device.

sweet yoke
chilly surge
#

Do read how it works before making the purchase though, it might not be what you need.

sweet yoke
#

yeah this does not seem to be the right for me unluckily (no support for "Pitch" & "Low latency wireless/Bluetooth headphones") but i gona look for similar ones

swift falcon
#

someone please show me how to share ur whole project with someone for free

tired elk
swift falcon
#

open and do whatever they want so they can code with me

#

i tried github but you need to buy more for bigger project

tired elk
#

Make a Git repository, and share it to them

swift falcon
#

I did that

#

but my project is too big

knotty sun
swift falcon
#

nope..

#

I will test that

#

I'll let u know

#

oh yeah I did that already

knotty sun
#

there you go then, delete your repository, use the correct .gitignore and then make a new repo

swift falcon
#

Alright

frail dust
#

I have 3 prefabs - Coins, Cars, and Pickup Items. For all 3 of them I have a Separate Spawner script as all 3 have different spawn logic. Now When they spawn, sometimes these items spawn very close to each other or on top of each other. I want a functionality that checks if any item is very close to new spawn point selected, it skips that and spawns at next 'y' position ( Basically I am making an endless runner game, every item spawns at middle of roads, so I want a minimum y distance between all items)

Problem: Items spawned are sometimes on top of each other or very close to each other

cosmic rain
cosmic rain
frail dust
#

how do i make a higher level spawn manager

#

that governs

#

all of spawners

cosmic rain
#

As I said, depends heavily on your project, but in general something like this for example:

public class SpawnManager
{
  Spawner[] spawners;
  public void OnSpawnSomething()
  {
    foreach(var spawner in spawners)
    {
        var spawnPos = GetSpawnPos();
        if(IsValid(spawnPos)
        {
          spawner.Spawn(spawnPos);
        }
    }
  }
}
frail dust
#

can i make a script that enables/disables all the other 3 spawner scripts after every fraction of seconds? so that avoids colliding?

cosmic rain
leaden ice
#

rather than disambiguating three separate spawners.

cosmic rain
#

You can code whatever you like as long as it doesn't break the laws of physics/logic

frail dust
leaden ice
#

probably a single one, or no coroutine

#

but it can choose from multiple items based on whatever criteria

frail dust
#

i tried an approach of setting a random function choosing between [0,10], for some range of values it would select one coroutine, or vice versa. But that just crashed unity due to many items spawning suddenly

main tinsel
#

Is it possible to create an animation that follows the cursor? Like the one on this video https://www.youtube.com/watch?v=DPqc7qYDtzM but not just modifying the Z rotation but rather completely triggering a different animation when mouse points somewhere else? Like say a 2.5d game, project zomboid sort of mechanic but the sprite is 2d

In this video we will learn how to Aim a Melee Weapon at mouse pointer in Unity 2D. In the later video I will show you how to perform an attack and how to create enemies to fight with.

Make a Juicy 2d Shooter course:
https://courses.sunnyvalleystudio.com/p/make-a-juicy-2d-shooter-prototype-in-unity-2020

How to get input using the new input sys...

▶ Play video
wide dock
#

"Divide" your screen into 4 segments - up, down, left, right (or 8 is you have diagonal animations) and check in which segment is your mouse

summer bronze
#

i got isshues whit the genaration of the world bc my world should generate infinite but it dont generate at all could you please help me? this is the code for the generation: using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelGenerator : MonoBehaviour
{
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 200f;

[SerializeField] private Transform levelPart_Start;
[SerializeField] private List<Transform> levelPartList;
[SerializeField] private Player player;

private Vector3 lastEndPosition;

private void Awake()
{
    lastEndPosition = levelPart_Start.Find("EndPosition").position;

    int startingSpawnLevelParts = 5;
    for (int i = 0; i < startingSpawnLevelParts; i++)
    {
        SpawnLevelPart();
    }
}

private void Update()
{
    if (Vector3.Distance(player.GetPosition(), lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART)
    {
        // Spawn another level part
        SpawnLevelPart();
    }
}

private void SpawnLevelPart()
{
    Transform chosenLevelPart = levelPartList[Random.Range(0, levelPartList.Count)];
    Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart, lastEndPosition);
    lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
}

private Transform SpawnLevelPart(Transform levelPart, Vector3 spawnPosition)
{
    Transform levelPartTransform = Instantiate(levelPart, spawnPosition, Quaternion.identity);
    return levelPartTransform;
}

}

main tinsel
#

on the animator menu

wide dock
#

I always set up such things in code rather than the animator, so no clue

main tinsel
#

got it. can i atleast @ you later on once I get all my sprites drawn to help with the code?

main coral
#

Hey im using a Horizontal Layout Group. Is it possible that it spawns next row and not on the right ?

wide dock
# main tinsel got it. can i atleast @ you later on once I get all my sprites drawn to help wit...
enum Direction { Up, Down, Left, Right }
        
Direction GetDirection(Vector2 obj, Vector2 target)
{
    Vector2 relative = target - obj;
    float x = relative.x;
    float y = relative.y;

    if (y >= 0) {
        if (y >= Mathf.Abs(x)) {
            return Direction.Up;
        }
    } else {
        if (y <= -Mathf.Abs(x)) {
            return Direction.Down;
        }
    }
          
    return x >= 0 ? Direction.Right : Direction.Left;
}
```I believe something like that will be enough if I didn't make any mistake
main tinsel
#

It's gonna be 2.5d i'm using a 2d sprite on a 3d platform so I have to use vector3 right?

wide dock
#

I'm not sure if that even matters

main tinsel
#

Got it. Thanks for the help, I'll have to take a look at your code and see what it all does as I'm still learning c#

wide dock
#

You can just ignore the height of where the object/player is placed, since you can just assume that the object/player is on the same level as the mouse

#

You only need the x/y direction (or rather x/z, since y is the height)

main tinsel
#

Oooh okay thank you 😁

wide dock
#

f(x) = x & g(x) = -x

main tinsel
#

And I assume the "enum" indicates the animation/sprite names to be used when that if condition is met?

wide dock
#

enum Direction is just a type to make it more readable as to which animation should be used

#

You can either make a switch(direction), go through each possibility and play the correct animation

#

or as I like to do it, make an array of string-to-hash for your animator and choose a hash based on the enum (cast to int to get the index)

main tinsel
#

Yeah that makes more sense. Basically assigning an ID to each direction of the sprite anim

#

I'll plot out all the sprites first. Thank you for the help, I'm just thinking ahead as I realized that I need this code for the 2.5d aspect to work

wide dock
#
private static readonly int[] s_animations = {
  Animator.StringToHash(...);
  ...
};

[SerializeField] private Animator m_animator;

private void Animate(Direction direction) {
  int index = (int)direction;
  int animation = s_animations[index];
  m_animator.Play(animation);
}```Something along those lines
** **
last raven
#

if anyone having issues with idiot players on windows putting game into folders ending with whitespace characters and game failing to load because of a bug in mono System.IO.Path.CanonicalizePath(string):string I made this workaround:

private static readonly char[] DirSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar };
public static string FixPath(string path)
{
    if (string.IsNullOrEmpty(path)) return path;
    int sepIndex = path.IndexOfAny(DirSeparators);
    if (sepIndex == 0)
        sepIndex = path.IndexOfAny(DirSeparators, 1);

    StringBuilder pathBuilder = null;
    int startIndex = 0;
    for(;;)
    {
        if (sepIndex < 0)
            sepIndex = path.Length;

        if (char.IsWhiteSpace(path[sepIndex - 1]))
        {
            if (pathBuilder == null)
                pathBuilder = new StringBuilder(path.Length + 4);
            pathBuilder.Append(path, startIndex, sepIndex - startIndex);
            pathBuilder.Append('.');
            startIndex = sepIndex;
        }
        if (sepIndex == path.Length)
            break;

        sepIndex = path.IndexOfAny(DirSeparators, sepIndex + 1);
    }
    if (pathBuilder == null)
        return path;

    pathBuilder.Append(path, startIndex, sepIndex - startIndex);
    return pathBuilder.ToString();
}

just use it on Application.dataPath / Application.streamingAssetsPath, it works because adding . to the end of file or folder name doesn't change it on windows, it's still same name, but it tricks CanonicalizePath function into not trimming valid whitespace characters, so instead windows API itself would do the job correctly

rigid island
last raven
#

persistentDataPath will rarely have whitespace characters at the end of the path, only if player has it in their user name

#

but dataPath and streamingAssetPath can have such folders in path because player can put game in a folder with such name

#

and it's been my constant headache

leaden ice
#

What are you using those paths for where it causes a failure?

last raven
#

opening files?

leaden ice
#

What code did you write that failed to open a file?

last raven
#

anything that uses System.IO.FileInfo / System.IO.DirectoryInfo / System.IO.File / System.IO.Path

#

so any attempt to open files with .net api in such folder fails

#

because it incorrectly canonicalizes name and removes valid whitespace character from path

leaden ice
#

how did you construct the path that you passed into it?

last raven
#

Path.Combine(Application.streamingAssetsPath, fileName)

#

you can easily reproduce it, just create folder with name (EN SPACE, not U+0020 which is actually invalid on windows and you won't even be able to create such folder) and put game in it, then try File.Exists on any path inside it or log Path.GetFullPath on any path

#

such path breaks most unity games

#

unless they do not use any dynamic loading at all and everything is statically loaded

rigid island
last raven
#

not whitespace, specifically whitespace at the end of name, and not U+0020 whitespace (it's invalid on windows and windows wouldn't even let you create folder with such name) but any other unicode character in whitespace category

#

that happens because mono's mscorlib for some reason canonicalizes name on its own instead of relying on windows to do that like core clr does and it does it incorrectly - it calls TrimEnd() on every path part instead of TrimEnd(' ', '.') (skipping parts with names "." and "..")

#

code I gave adds . at the end of such names, which tricks function to not trim anything at the end and then when path is passed to windows api it canonicalizes name on its own correctly trimming . at the end without trimming whitespace character

#

other option is to patch mscorlib bundled with unity

robust kiln
#

Does anyone know how to unlock achievements easily on their Steam game? I can't succeed no matter how hard I try

vapid condor
mental rover
last raven
#

yeah, it's just not a common issue because most people don't use such folder names but when they do this is extremely hard to figure out

rich spire
#

Hello, I'm currently trying to create a procedurally generated dungeon and I'm running into the issue of overlapping rooms. I have created an unconventional method for linking rooms and I'm wondering if anyone has suggestions as to how to proceed with my current progress.
right now I have two prefabs for rooms, each with their respective exit and entry doors, each exit door will then create an instance of a new room, connecting to the entry door of the instantiated room and it will repeat for as many rooms as we'd like to generate, but, as I've said, they are overlapping, any idea on how to deal with this?

delicate flax
crisp minnow
#

Not sure if there's a dedicated channel but does Unity Ci support 2023 or not yet?

heady iris
#

sounds like continuous integration

#

wouldn't that just be the unity cloud build system?

crisp minnow
#

Game Ci docker package, no clue where to even ask about this, I don't think its directly supported by Unity

heady iris
languid hound
#

I'm not asking for somebody to write this just a point in the right direction
I was wondering how I can push a sphere out of any intersecting objects?
I was thinking of Spherecast but it needs a direction and 0 max distance doesn't work
I was thinking of OverlapSphere which.. technically works? I just don't know how costly ClosestPoint is

Are there any other solutions that would be more efficient? After all the end goal is to push an object out of another it doesn't need to be perfect

languid hound
#

Spherecast generally would've been perfect if it weren't for that fact. It provides a normal and everything

leaden ice
heady iris
#

jinx

#

😁

#

the method's signature is kind of frighteningly long

languid hound
#

Lol no worries thanks guys too dense to find that

heady iris
#

you give it the position and rotation of both colliders explicitly

languid hound
#

But yeah it's on an object that cant really have a rigidbody

heady iris
#

see the example:

            bool overlapped = Physics.ComputePenetration(
                thisCollider, transform.position, transform.rotation,
                collider, otherPosition, otherRotation,
                out direction, out distance
            );
#

I remember suggesting to someone that they just write a wrapper for it

#

it'd be something like

languid hound
#

That's not too costly right? It seems like it's taking a lot more into considering in comparison to a collider and a position

heady iris
#
public bool ComputePenetration(Collider first, Collider second, out Vector3 direction, out float distance) {
  return Physics.ComputePenetration(first, first.transform.position, first.transform.rotation, second, second.transform.position, second.transform.rotation, out directino, out distance);
}
#

just to make the function calls less...awful to look at

leaden ice
#

I mean the physics engine does this all the time

#

whenever objects collide

languid hound
#

All? Holy crap

#

Maybe I'm overthinking this. I thought that'd be really intense

heady iris
#

The position and rotation arguments are useful for asking if colliders would overlap

leaden ice
#

PhysX is pretty optimized

heady iris
#

but that's not what you're doing here; you're asking if two colliders are already overlapping

crisp minnow
late lion
heady iris
#

It will be factored in.

#

I was worried about that at first too (:

late lion
pine condor
#

Hi, im trying to make a game where you can spam 2 buttons to activate the same function, but currently having both pressed inputs set to the same functions makes it so that the 2nd button can't be pushed unless the 1st one is unpressed. imagine cookie clicker but you can spam 2 buttons basically (for example), how would i do this in the new input system ?

languid hound
heady iris
#

see the out params

languid hound
#

Oh right I missed that

#

Cheers

soft shard
# pine condor Hi, im trying to make a game where you can spam 2 buttons to activate the same f...

You could either setup both buttons in your input action asset, or you can use Keyboard.current, and check (I think its) .wasPressedThisFrame property, and call your function in 2 separate if-statements, though in general it seems odd to me that you might need 2 buttons to call the same function at the same time, unless your maybe setting up a "primary, secondary" type of interaction, though even in that instance youd probably only want the function to be active from either rather than both id imagine

pine condor
#

i want to make it easier to call the function in quick succession, since spamming 1 button is alot harder and annoying than spamming 2

#

and isn't keyboard.current the older input system that isn't compatible with the new one? i put both buttons in the same function and it makes me unpress the 1st button for the 2nd one to work

leaden ice
#

No Keyboard.current is part of the new system

languid hound
#

Yeah ComputerPenetration is literally spot on thanks you guys

leaden ice
#

The old system is exclusively the things in the Input class

languid hound
#

I can make workarounds but the ground isn't flat at all so it's only temporary

pine condor
leaden ice
pine condor
#

i.e instead of action having button 1 and button 2 would i need actiobutton1 and actionbutton2

pine condor
#

which isn't what i want

leaden ice
#

you can't just blindly trigger your thing

#

check the value

#

and do the thing for every time you see a 1

pine condor
#

how do i check the value ?

leaden ice
#

depends on which workflow you're using

pine condor
#

uhhhh pass

#

idk what u mean by that

leaden ice
pine condor
#

how do i use that specific part of the input system yes

#

i know how to call a function from an action but not check the value of an action every frame

leaden ice
#

Again it depends on which workflow you're using

pine condor
#

i mean i've got this bro idk

delicate flax
#

get rid of the 'else'?

leaden ice
#

IDK why you'd do it this way

#

Are you trying to read two different actions here?

#

Because that can work but yeah get rid of the else

pine condor
#

cus i was using something else then someone told me to use that instead

#

to do what i want

leaden ice
#

in this case, make your action a passthrough and subscribe to the .performedevent on the action

#

then in the callback function you read the value from the CallbackContext parameter

pine condor
#

i have no idea what a buffer is

leaden ice
#

you're tunnel visioning

#

I simply linked you to the list of methods on the class

#

you don't have to use the one you don't understand

#

ReadValue<float> or ReadValueAsButton

pine condor
#

aight got it thx

vapid condor
robust kiln
vapid condor
soft shard
# pine condor aight got it thx

Also, if you are subscribing with .performed you should also make sure your unsubscribing from it at some point, such as in OnDisable or OnDestroy

soft shard
# pine condor

Youd want to unsubscribe (-=) your function from the action you subscribed to (+=), so for example:

void OnEnable()
{
input.SomeMap.SomeAction.performed += SomeFunc;
}

void OnDisable()
{
input.SomeMap.SomeAction.performed -= SomeFunc;
}

Where SomeFunc is your function using the CallbackContext param

leaden ice
#

but no disable doesn't unsub

tired aspen
#
        if (Input.GetMouseButtonDown(0))
        {
            _initialMouseOffset = Vector3.zero;//restes the _initialMouseOffset vector
            Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); //gets the mouse position 
            NodeClass nodeToMove = (CheckIfPosIsOnNode(mousePosition)); //returns the node that is on that position 
            _initialMouseOffset = mousePosition - nodeToMove.transform.position;
        }

             Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
              foreach (var selectedNode in _selectedNode)
            {
                // moves the selected nodes relative to the _initialMouseOffset
                Vector3 newPosition = mousePosition - _initialMouseOffset;
                selectedNode.transform.position = new Vector3(newPosition.x, newPosition.y, selectedNode.transform.position.z);
            }

i want to move the selectedNodes relative to the mous position. But currtently i am just setting the position of every node to the mouse position - the offset. And I don´t know how to go from there

autumn field
tired aspen
#

would make sens

leaden ice
#

I would say... calculate the mouse offset each frame and add that offset to each object's position

#

(world space offset)

#

e.g.

Vector3 previousMousePos;

void Update() {
  Vector3 currentMousePos = // calculate current mouse world position
  Vector3 mouseDiff = currentMousePos - previousMousePos;

  foreach (var thing in thingsToMove) {
    thing.transform.position += mouseDiff;
  } 

  previousMousePos = currentMousePos  
}```
#

of course also set previousMousePos to current position whenever you need to start the drag thing

#

and add logic for whatever clicking/holding of buttons you need

tired aspen
#

Thx

rocky jackal
#

Im trying to insert an item into a list at position 13 and for some reson it says the position is out of range but its only 13, why does it break ?

heady iris
#

presumably that's a list you're inserting items into

rocky jackal
#

yes

heady iris
#

if the list doesn't have that many elements, you can't insert an element at that position

#

perhaps you want a dictionary here?

rocky jackal
#

oh, i thought it would resize automatically, thats what i found on the internet

heady iris
#

it will as you add items

neon nymph
#

hey how to use OnCollisionEnter/Exit?
My Questions:

  • Should the item that has the script attched have a rigidbody or the other one that is collided with?
heady iris
#

but it won't add a bunch of default items to fill in the space when you try to use Insert with an index that's too large

neon nymph
#

Ok

#

Hey but anyone that doesn't answer with a link
how to use OnCollisionEnter/Exit?
My Questions:

  • Should the item that has the script attched have a rigidbody or the other one that is collided with?
heady iris
#

they are concise and thorough

leaden ice
heady iris
rocky jackal
heady iris
heady iris
#
frontiers[3]
#

you will get an exception if no such item exists

neon nymph
#

Hey my problem is that how to have a collider and RigidBody and a Charachtre controller at the same time i wanna do that HOW ?

rocky jackal
leaden ice
#

unless maybe if the RB is kinematic

neon nymph
heady iris
#

the kinematic rigidbody is not affected by physics

leaden ice
#

unless you use SimpleMove, but that's very limiting

heady iris
#

why do you need a rigidbody and a collider on the same object as your character controller?

leaden ice
# neon nymph How?

keep track of current velocity in a variable, add to it each FixedUpdate, like how gravity actually works

heady iris
#

note that the CC itself functions as a collider

#

if you hit the player with a projectile that has a rigidbody and a collider on it, you'll get a physics message

leaden ice
#

Pretty much any CC movement tutorial will implement gravity

#

it's relatively simple

neon nymph
#

Ok i have done it before and thats why i'm asking so here's my code :

{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    float jumpInput = Input.GetAxis("Jump");

    // Check if the player is grounded

    // Movement
    Vector3 move = transform.right * x + transform.forward * z;
    controller.Move(move * speed * Time.deltaTime);

    // Apply gravity
    if (isGrounded && velocity.y < 0)
    {
        velocity.y = 0f;
    }
    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);

    // Jumping
    if (isGrounded && jumpInput > 0)
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }
}
void OnCollisionEnter(Collision C)
{
    if (C.gameObject.tag == "Ground")
    {
        isGrounded = true;
    }
}
void OnCollisionExit(Collision collision)
{
    if (C.gameObject.tag == "Ground")
        isGrounded = false;
}```
leaden ice
#

you need a different grounded check though

neon nymph
#

i know but i will record a video and send it to you

leaden ice
#

use a raycast or something

#

yeah your grounded check is busted

#

I recommend following a tutorial

neon nymph
leaden ice
#

you're using a CharacterController

#

switch to a raycast-based grounded check

#

What you have is not really a good grounded check for Rigidbodies either anyway

neon nymph
#

Ok then but i don't realy understand it so i will do some reseach

heady iris
#

Your character controller will not produce OnCollisionEnter/Exit messages when you hit the ground

#

the controller calculates how to move without getting stuck in a wall

#

so it never actually causes a collision; it just moves to the right spot directly

neon nymph
#

Ok

#

Can you explain How to Do a raycast grounded check ?

  • Note : "If u want to Help to do it"
  • "If not IDC"
#

I'm not forcing anyone here

leaden ice
#

The best way would be for you to look at examples

neon nymph
#

Ok

leaden ice
#

but essentially you do a raycast from your character downwards. If the cast hits the ground, you're grounded

#

otherwise not

rocky jackal
#

@heady iris , I cant use dictionaries since i sometimes get entries that should have hte same cost but i cant add 1 to every key so i would need to create a new dict every time a key already exists just to push back every other value by one

heady iris
#

it looks like some kind of optimization algorithm

neon nymph
#

But it tried bool isGrounded = controller.isGrounded

leaden ice
#

especially since your code has sort of a CC Move bug in it

#

but that can be fixed later

heady iris
#

isGrounded tells you if you tried to move downwards into a collider the last time you called controller.Move

#

You call controller.Move several times

#

the horizontal move will almost certainly make .isGrounded be false

#

since you will slide along the ground without trying to move down into it

neon nymph
#

I know that but my problem is that how to check .isGroundedOnwhat(GameObject)

crisp owl
#

hi everyone, i have a question. in this image you can see i have multiple idle animations, my game has multiple different character stage sprites for each action, but i'd like to know the best way to go about this, i was attempting to treat the "Idle" state as an if statement to check if these 2 parameters are false, so it could trigger the actual animations (image 1 is the transition to "Idle", image 2 is the transition to "Player_Idle"), but it gets stuck (image 3)

rocky jackal
# heady iris what are you actually trying to do?

im trying to make a path finding algorithm for creating roads on procedural terrain, im using this article as a refrence and im currently at the part wher i need to save the cost so the pathfinding preferes the path with the littles elevation change kind of to mimic real roads and i just need to sort my frontiers based on their current path cost

heady iris
#

ah, okay, I just implemented this recently

crisp owl
heady iris
#

You need a priority queue

leaden ice
#

then all bets are off

heady iris
#

C# has one, but it's not available in the version of .NET that Unity uses right now

#

Fortunately, priority queues are dead simple

heady iris
#

Here's my implementation I'm using for A* right now

rocky jackal
leaden ice
#

So why would you need to "add one to each node" or whatever you mentioned

neon nymph
leaden ice
#

yeah you need a prioerity queue for sure like Fen said

leaden ice
# neon nymph 👆

You don't need to spam - again, use a raycast to check if you're grounded

rocky jackal
#

thats what im trying to do

heady iris
#

oh wait, I'm not actually using this right now lol

tacit loom
#

how to prevent fixedJoint2D from stretching?

heady iris
#

I should probably fix that..that's going to make my A* way slower

rocky jackal
#

i could just save it in a vector 3 and use the 3rd value for the cost

#

then i can go back to my simple happy list

heady iris
tacit loom
#

I only put fixedjoint2D

heady iris
#

It's not a sorted list.

rocky jackal
#

that looks really organized but i dont have this much time since its for a game jam

heady iris
#

the alternative is to just iterate over the entire list every time

#

which is...what my A* is doing right now, lol

#

All you need is the ability to find the smallest element.

#

alternatively, just grab an A* library and get on with your game

rocky jackal
# heady iris All you need is the ability to find the smallest element.

Made my sorting algorithm, id need an open source one and id need to understand how to make it find the best path across a texture basically. that sounds more complicated to me. mine can already go from a to b and avoid slopes higher than 45°

int GetLowestCost(List<Vector3> l)
    {
        float HighestCost = 0;
        int index = 0;
        for(int i = 0; i < l.Count; i++)
        {
            if (l[i].z <= HighestCost)
            {
                index = i;
                HighestCost = l[i].z;
            }
        }
        return index;
    }
heady iris
#

A* is a very, very generic algorithm. All it needs is a list of places it hasn't been yet, the cost to go to a place, and an estimate of how far that place is from the goal

#

I implemented it as part of goal-oriented action planning for my game AI. I pathfind between world-states!

#

I want to pull the lever <- I pull the lever, so I need to be close to the lever <- I walk to the lever

autumn field
#

goap is so cool

rocky jackal
heady iris
#

oh yeah, it was a lot

#

and it took several tries before i really "got" it

#

it's also inappropriate for a lot of situations

heady iris
elfin tree
#

Is there a straight forward way to count a collider being disabled as a trigger exit for whoever was inside it?

willow hull
heady iris
#

i'm going to smash it together with my objectives system and see if I can make NPCs automatically complete the same objectives the player is given

heady iris
willow hull
worthy willow
#

The first image is the script I created to display a string when the player wins the round, and the second image is what displays when the script is ran.

heady iris
worthy willow
#

However I want it to print this

#

how can I do this?

heady iris
heady iris
#

"\n" is a string containing a newline character