#archived-code-general

1 messages ยท Page 67 of 1

plucky inlet
#

Welp, looks like you cant from the default animator methods

#

I mean, yuo can probably with reflection and editor tools, but thats not gonna work on runtime

#

and you want that enum to reflect the states in your animator?

#

You should make a transition then and check the next state

#

Why do you even use the animator then?

#

just use the animations you throw into it

#

It all depends on your animations tho

#

but your animations are clips inside your animator

#

every state holds an animation, right?

#

If you do not use the animator for anything transition like from one state to the other, you can just use the Animation itself, the AnimationClip

#

Or you just create an ANimationState on the fly and throw in the clip as state clip

#

just add an ANimation Component to your object instead and add your clips to the list

void glade
#

Hello, not too sure if this is the right place to ask this but, Im new to Unity's AR foundation, and I am trying to add an image as a background so that it shows behind the users face, Im trying to use the Custom material in the AR Camera Background but ll im getting is a black screen when I enable it. If anyone can help with that would be much appreciated.

void glade
#

Oh thank you , I dunno how I missed that channel ๐Ÿคฆ

elfin tree
#

Is it possible to modify this template so that it accepts interfaces too?
Or the interfaces so it's known that they are inherited by ScriptableObjects?

public abstract class LootTableBase<T> : ScriptableObject where T : Object {

plucky inlet
#

I was ๐Ÿ˜„

plucky inlet
#

Interface != class

elfin tree
plucky inlet
elfin tree
#

I'm trying to intergrate this into my code, but I'm using Interfaces on ScriptableObjects for my different type of loots

#

While this thing from Github expects ScriptableObjects

leaden ice
plucky inlet
#

to use an interface.

#

So you can use that interface of type ILootable or what not to do what you want

elfin tree
leaden ice
#

that it must derive from Object

#

(UnityEngine.Object)

elfin tree
#

Yeah, but could this be changed to not have that?

leaden ice
#

sure, delete the type constraint

plucky inlet
#

remove where T:Object

elfin tree
#

Alright, I'll import the whole code base then and try to modify it, thanks!

plucky inlet
elfin tree
#

Didn't want to get into it if it wasn't doable, it might break somewhere else but atleast it's a thing

formal quest
#

Is there a way to get Application.isMobilePlatform to return true; or Application.platform == RuntimePlatform.Android when running the game in simulator mode?

#

I have simulator setup to use Samsung Galaxy device, but both of these return false.

elfin tree
elfin tree
#

Okay yeah I can just remove it haha

#

Just had to remove it in many places

leaden ice
swift falcon
#

Does unity have built in multiplayer modules?

#

I havent dared to mess with multiplayer yet

leaden ice
#

Unity has lots of packages for lots of things

#

depends what kind of "multiplayer modules" you mean

swift falcon
#

Like, a basic way for 2 people to connect to the same server

leaden ice
swift falcon
#

Thank you

leaden ice
#

There's nothing "basic" about networking or multiplayer in general

swift falcon
#

Yeah thats why I havent messed with it lmao

swift falcon
#

What does this line indicate?

#

I am accessing the unity classes in the vs anyways. I dont think theres any better experience than having a configured ide

sage latch
#

As the warning says, go to settings and set vs as the external code editor. It'll give you better syntax highlighting, intellisense and autocompletions

candid trench
#

Alright, after having googled and thought about it for a long time, its now time to ask the awesome folks of discord for an answer to my question.

Im procedurally generating a mesh in my scene to act as a debug overlay in development.
The overlay is showing all the "tiles" of the map. This works great for one color.
But now my question becomes, can i have more than one color on one mesh?
And i dont mean two colors that blend, i mean two colors at two different spots in the mesh.

Do i have to somehow procedurally generate a texture and apply it?

swift falcon
#

ahh maybe needs a restart

sage latch
#

Why are you on ancient unity

swift falcon
sage latch
#

Probably has to do with the 6 year old version

plucky inlet
#

yep ๐Ÿ˜„

swift falcon
#

Restart did nothing *presses the Do Not Warn Again and continues life*

sage latch
#

Is there a reason you use that version of unity?

#

Cause I highly recomend updating if there's no reason

west lotus
swift falcon
sage latch
#

Fair enough

swift falcon
#

We can CTRL+Scroll on vs ๐Ÿ˜ฏ I might actually love vs

steady moat
candid trench
steady moat
candid trench
#

how do i then assign a specific material to the triangle?

steady moat
candid trench
#

and youre right btw, i dont need different colors inside of a triangle, single colours are good enough

#

ill check it out ty.

candid trench
#

hm, one question, this seems to use the Color class rather than a Material class. Am i correct?

chilly beacon
#

hey dude sorry for such a late reply i was in school the code you gave completely demolishes the procedural generation

#

this is the map it creates

steady moat
cobalt wave
#

its okay and hmm I understand it has to do with the "checkCellNeighbour" function since that one needs all of them to be generated

mental pine
#

hi, when I import models from Sketchup, my character can walk right through them, meaning they are not solid objects, how to fix?

steady moat
chilly beacon
#

@cobalt wave is this is the map i get when i generate with my code

cobalt wave
#

ill look into it when i waje up

chilly beacon
elfin tree
#

Hey, so for a few hours I've been trying to refactor this code so it can accept Interfaces too, my issues is that, even though my interface is of a ScriptableObject, which would work with the rest of the code, I'm unable to properly figure out what to do.

What I've done so far is refactor T : Object for T : INameable which has a GetName() method, but it becomes an issue because a lot of the code is based on Editor Serialized property so I get a lot of errors even though it builds..

The interfaces are always of ScriptableObjects but I'm not quite sure how to make that clear in the code, if it's possible.

https://github.com/Kellojo/Unity-Simple-Loot-Table

GitHub

A simple loot table for Unity. It's easily customizable and allows you to bring your own item classes and types. - GitHub - Kellojo/Unity-Simple-Loot-Table: A simple loot table for Unity. I...

fringe ridge
#

Any ideas why the font I downloaded displays as white squares? I tested it online and it is fine, but in unity with text mesh pro it just doesn't work

rocky laurel
#

Hello, voice chat is quieter in some places, but in the centre of the map, it is really loud? How do I fix this? I use Photon VR Voice

leaden ice
steady moat
elfin tree
rocky laurel
#

they are in the middle of the map

leaden ice
rocky laurel
#

players spawn in the house in the sky

leaden ice
#

that's why it's quieter farther away from it

rocky laurel
#

how do i get it to follow players

leaden ice
steady moat
candid trench
#

@steady moat mesh.colors worked wonders, helped me squash my pathfinding bug in no time, thanks!

rocky laurel
leaden ice
#

do what it says

regal marsh
#

How hard would it be to programmatically quiet everything but the announcer group here when something from that group plays?

steady moat
regal marsh
#

Okay, thank you. I'll let you know if I have more questions

rocky jackal
#

i have an object wich is a child of another object sometimes and i need to make it os the chil is always rotated upright. I tried it like this but it gave me very buggy results. what could i change ?

neon plank
#

How can I use NavMesh.SamplePosition in a two story building?
The method is sampling from the wrong floor.
Is there any workaround?

rustic ember
#

Do scriptable objects reset their data when the game is quit and reopened?

west lotus
#

Yes

#

But in a build not in the editor

rustic ember
#

Interesting. Thank you

hard sparrow
#

Hm, this is changing the color correctly, but it isn't changing the alpha

#

(the debug is showing the correct alpha number though)

dusk apex
#

Maybe you're wanting to change the color of the instance instead?

hard sparrow
#

No it was just bad naming. Should be instance

#

the color does change, just not the alpha for some reason

dusk apex
#

Might have to do with the settings of the material

hard sparrow
#

It's just the sprite unlit default material

uncut plank
#

calm down, it's been 2 minutes and you already crossposted it in 3 channels

#

post it in one channel and just wait

true vessel
#

ok

regal marsh
#

I am having some trouble with lerping my game volume. I am setting the values in Wwise and my mixer group, but although both of them appear to have updated when I debug them, they don't actually change in game.

#

Here is my log

#

As you can see the values when I get them directly from where I set them are updating correctly, but they are not actually changing at all when I play the game. I am testing this by calling it in Start. Does that not work? Or is there another problem?

buoyant crane
floral coral
#

How can I access one of two box colliders on a game object with GetComponent<>()? (one is a trigger, the other is for physics)

knotty sun
leaden ice
floral coral
#

what's that
and how that

leaden ice
#

It's unity 101

#

one of the first things you learn

#

declaring public variables and assigning them in the inspector

regal marsh
floral coral
#

I don't think I can do that, this is my code

public void Place(GameObject part)
    {
        partBeingPlaced = Object.Instantiate(part, new Vector3(), new Quaternion());
        // select one of the two box colliders of the game object "partBeingPlaced"
    }
leaden ice
#

put a script on your prefab, and add public fields to it. Assign those fields in the inspector

leaden ice
#

and Vector3.zero

regal marsh
#

But based on how pumpkin described it, it makes sense

floral coral
hard sparrow
leaden ice
#

you probably get a warning with your current way.

floral coral
#

I don't

leaden ice
#

Trying to teach you better practices, that's all. You don't have to accept them.

lunar forum
#

Is there some dumb reason that I'm missing as to why I cannot add new tags?

deft fossil
#

Can someone give me a hand? I'm trying to assign randomly a total of 26 tags to Instantiated gameObjects, but its assigning the first tag only, going over the limit.```cs
public GameObject floors;
private int MaxFloors = 26;

public Material Enemy;
public Material Weapon;
public Material Empty;


string[] tags =
{
    "Monster", "Empty", "Weapon"
};

int[] tagCounter = { 14, 5, 7 };

int index = 0;

void Start()
{
    for(var i = 0; i < MaxFloors; i++)
    {
       GameObject newFloor = Instantiate(floors, new Vector3(i * 20.0f,0,0), Quaternion.identity);
        for(int j = 0; j < tagCounter[index]; j++)
        {
            newFloor.tag = tags[index];
            index++;
            
            if(index >= tags.Length)
            {
                index = 0;
            }
        } 
    }
}
leaden ice
#

delete the inner for loop

fringe ridge
#

Any imported fonts in current project have 0 characters and glyphs when converted to tmpro asset. Now on another project, they are working fine. Any ideas?

deft fossil
#

its not tagging now

#

If you need more context, I need 14 of Monster tag, 5 of empty and 7 for weapon

leaden ice
coral hornet
#

i instantiate an object, i place an object with a collider for its child, i begin creating more objects as its child, i try to raycast from outside inward to see where it hits and try to place the child there, but it wont intercept a single collider despite it clearly intercepting colliders

#

im probably just not seeing something very simple that im overlooking

#

but ive debugged the ray, i can see it intercepting the collider, i checked that theres a collider on those objects, i dont believe the Z axis is interfering with the operation, i really dont understand the issue

#

i printed how many RaycastHit objects its returning and its telling me 0

#

so its just not hitting anything

#

but i can see the debugged rays hitting the objects, and honestly im just confused

#

my only real guess is that they might have inversed direction?!?

#

but wait.. that cant be because the origin value is set as the origin of the ray, i wouldve clearly seen if the direction was inversed because it would go the opposite direction from the origin value facing away from the object

#

im confused :/

leaden ice
#

So if you're placing colliders etc you won't see them with raycasts until either the next physics sim or you call that^

coral hornet
#

oh.. alright thanks

#

so every time i instantiate an object i have to sync transforms?

#

or do i do it after i position the object?

#

since it has to do with transforms

#

ill do it after positioning just to be safe

#

hey it works! thanks a ton, wouldve never guessed that

leaden ice
coral hornet
#

alright

regal marsh
lunar forum
proper nymph
#

How do developers approach programming their games? I'm aware that the potential answer will be "It depends on the project," but I'm more so referring to the common things people do when developing code for their project. How much online research do you find yourself doing to code something specific vs figuring it out on your own?

I've had experience programming outside of Unity and I tried to figure out how to answer programming questions from classes on my own save for very specific questions i wanted to find the answer to on stackoverflow. But those questions were pretty simple while doing a unity project is a lot more involved. A common thing I see online is that most of programming is looking up what your asking to code and then basically copy the answer to your own code base, but I'm worried that's going to develop bad habits.

If the question is confusing and need to specify anything please let me know.

rustic ember
# proper nymph How do developers approach programming their games? I'm aware that the potential...

I try to figure out a solution by myself, but will afterwards look for others' implementation if my code is too slow. Don't look too much for a single solution. I have found it to be better to ask for pointers. These pointers will introduce me to new concepts that I can then look up and experiment with. Examples could be dictionaries, Unity events, or singletons. All of these things I wouldn't know existed without asking people for help / looking up other people's code.

This is just my own experience, keep that in mind

#

Also, showing your code to other people and them telling you: "You suck! X is a much better way to do it", is what I learn the most from

proper nymph
#

lol glad you took it in stride. Thanks for the advice!

deep fable
#

How can I switch the noise profile of a cinemachine virtual camera from handheld to 6D shake from code?

clever lagoon
# proper nymph How do developers approach programming their games? I'm aware that the potential...

"A common thing I see online is that most of programming is looking up what your asking to code and then basically copy the answer to your own code base, but I'm worried that's going to develop bad habits." Agree, this is awful, at least if one is copy/pasting the exact code- one learns nothing, and introduces possible problems. Of course, there is nothing wrong with finding/learning an efficient way to do something, and applying that pattern in your code. The one exception to using others' code- well vetted libraries/packages: you don't want to spend time re-inventing the wheel when you can use a perfectly good one.

tidal shadow
#

what could be a better practise than showing a visual guide of a specific task after getting a hearing guide on how to do it?
not sure using an IEnumerator is such a good practise, but im not sure it isnt either

cerulean oak
#

how do I set the TextField size to a number, and it's label to fit?

#

editor TextFields

rustic ember
rustic ember
#

That makes sense

#

Where do you find the code? Do you look through the github, or is there a link in the docs?

leaden ice
#

I search their github org

knotty sun
#
absolute (abs(a-b) < eps) as well as relative (abs(a-b)/max(abs(a), abs(b)) < eps) 
rustic ember
lost night
#

Hey, I wanted to ask how I can detect collisions while an animation. Thanks for any help

leaden ice
lost night
leaden ice
#

animation or no

#

obviously if you're using an animation to move it, it's not dynamic

rustic ember
#

What would be a smart way to let the player select a character before going into a level/changing scene and let the GameManager in the level scene know which ones (characters) were chosen?

leaden ice
#

including chosen characters, equipment, etc...

lost night
leaden ice
#

you just can't use OnCollisionEnter

rustic ember
lost night
rustic ember
#

Can a DDOL object have a singleton script attached?

somber nacelle
#

sure, why not? in fact making a singleton DDOL is a common pattern

leaden ice
marble halo
#

So i've almost got my player to slide down steep slopes

#

However the way the player slides down is a bit bumpy

#
        {
            var normal = player.hitNormal;
            player.velocity += new Vector3(normal.x, -normal.y, normal.z) * 2;
        }```
#

mainly on really steep slopes

fluid lily
#

Wait does RaycastAll return hits ordered farthest first???

fluid lily
#

What why unity!๐Ÿ˜ญ

simple egret
#

Probably because of physics engine optimizations

#

You can still order in your own code though

rustic ember
#

I know that I could just rename the script, but is there a way to override the built-in and avoid the warning?

knotty sun
fluid lily
rustic ember
knotty sun
#

do you not know what a namespace is?

rustic ember
#

You mean not use UnityEngine?

#

I still need the MonoBehaviour part

knotty sun
#

if you have 2 CharacterControler scripts, you can seperate them by making one of them MyNameSpace.CharacterController, thus removing the warning

rustic ember
#

public class CharacterController : UnityEngine.MonoBehaviour

rustic ember
#

But will kind of suck in the future

knotty sun
#

only becaue you have spelt it incorrectly

rustic ember
#

What? I don't think so

knotty sun
#

Controler does not have a double l

rustic ember
simple egret
#

It does have two l's

knotty sun
#

sorry, my bad

rustic ember
#

Anyway, thank you

#

Is the C# version different from Unity versions?

simple egret
#

Yes

rustic ember
#

Great!

#

I should probably upgrade some of my projects then

simple egret
#

Though Unity controls the project file, so they are linked

somber nacelle
#

it actually depends on the unity versions. for example 2021, 2022, and 2023 are all on c# 9

simple egret
#

Can't bump the C# version alone, as Unity will override it when the project file is regenerated

rustic ember
simple egret
#

It's listed online

rustic ember
somber nacelle
#

because it depends on the scripting runtime version selected in your project settings like the text directly above that table says

rustic ember
somber nacelle
#

you can check the setting in your project to see which it is currently on. if you've never changed it then you know that is the default

#

but also is there a reason you are using 2018 and not a more modern version?

rustic ember
somber nacelle
#

the table you linked is from the 2018 page ๐Ÿค”

rustic ember
#

Yeah

#

I have a few old projects

solemn raven
#

Hey,
what is the right way to Convert string to int ?

leaden ice
#

Should only be done if you're handling user input basically

solemn raven
coral hornet
#

so uh advanced seems pretty dead right now so i guess ill ask here

vagrant blade
#

No, that's crossposting.

#

Regardless, it wasn't even an advanced level question. It's beginner at best. You look up how to do AI. That's where you start.

coral hornet
#

so i should remove it and post in beginner?

#

because ive looked it up and i dont understand a thing

vagrant blade
#

You don't need to post, the answer is: figure out the rules for your AI and implement it. Research as well.

#

There's no one way.

coral hornet
#

i have so many "rules" that im just sorta puzzled, i guess ill try my best

coral hornet
#

if you could atleast reccomend an article for where i could look it would be much appreciated

visual flare
#

If the image is off center in the camera, is there a way to center it without moving the camera?

coral hornet
#

like a ui element?

vagrant blade
visual flare
#

3d world stuff, centering this capsule

#

you'd do it with tilt shift lens IRL

velvet quartz
#
ContactPoint contact = collision.GetContact(0);```
Why first line exst if on the doc they said to not use this method ?
quartz folio
#

GetContact was introduced as of 2018.3

toxic notch
#

Whats the best way to scale movement between two different ranges? If I have 1 m arm and I rotate it so it's level with the base and then I want to take that distance that I rotated and apply it to a 10m arm but scale it in a way so that the 10m arm moves to be level, how would I do that?

velvet quartz
quartz folio
#

it's in the documentation

velvet quartz
#

ok

quartz folio
velvet quartz
#

ok

cosmic rain
#

Or slerp

polar marten
stray blaze
#

Hey! So I had something I've been trying to figure out for the past 2 days, I have prefab clones which are instantiated into my scene after the App has launched, part of these clones is a button that is supposed to disable a component of another gameobject that already exists in the scene from the start, but I'm not able to directly connect it through the inspector to the button click event due to it not existing in the scene, is there a straight forward method to assign it? Or would it have to run through a coded method in order to access that component?

onyx mango
#

I have a script that contain this line of code Application.targetFrameRate = 60;
and I have attached it to an empty game object and I also have like 5 different scenes on my game, do I have to attach this script to a game object in every scene ?

hearty lagoon
#

so i an using [ExecuteInEditMode] to place prefabs in my scene and give them a name related to their position.

        for (int PosX = 0; PosX < Width; PosX++) {
            for (int PosZ = 0; PosZ < Length; PosZ++) {
                GameObject tempTile = PrefabUtility.InstantiatePrefab(tile, transform) as GameObject;
                tempTile.transform.position = new Vector3(PosX, 0, PosZ);
                tempTile.name = PosX + "-" + PosZ;
            }
        }

it get disabled afterwards so it doesnt run the next time i click play. however the next time i click play all the prefab's custom names get reverted to the original prefab name. how do i fix this?

#

they dont change their name anywhere else

proven plume
leaden ice
lunar forum
#

Would this be the right place to ask for recommendations on my singleton implementation?

#

Or would that go in Advanced?

#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManagerScript : MonoBehaviour
{
    private static GameManagerScript instance;
    private static int points = 0;
    private static bool havePackage = false;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public static void AddPoints(int p) { points += p; }

    public static int GetPoints() { return points; }

    public static void LoadGameOver()
    {
        points = 0;
        SceneManager.LoadScene("GameOver");
    }

    public static bool CheckHavePackage()
    {
        return havePackage;
    }

    public static void SetHavePackage(bool hp)
    {
        havePackage = hp;
    }
}
#

So, that's currently what I'm doing. I suppose all the other methods aren't important, but I honestly just don't understand singletons.

leaden ice
#

it doesn't use DDOL so it won't persist between scenes but that's not always desired.

#

although

#

you should NOT make all your variables static

#

I just noticed that

lunar forum
#

Oh. I thought you had to.

leaden ice
#

the only thing in this whole script that should be static is this:
private static GameManagerScript instance;

#

everything else that is static should not be static

#

You should also make a public accessor for that field

lunar forum
#

Interesting. A video I watched about it said otherwise. Or maybe I just misunderstood.

leaden ice
#
public static GameManagerScript Instance => instance;```
leaden ice
#

or it was a bad video

#

remove static from everything except instance, and make instance public

#

then you're good to go

lunar forum
#

Awesome. I'll do that. As for DDOL, where would I implement that if I wanted that feature?

#

In the awake method?

soft shard
leaden ice
#

in Awake, yes

lunar forum
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManagerScript : MonoBehaviour
{
    public static GameManagerScript instance;
    private int points = 0;
    private bool havePackage = false;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
        DontDestroyOnLoad(gameObject);
    }

    public static void AddPoints(int p) { instance.points += p; }

    public static int GetPoints() { return instance.points; }

    public void LoadGameOver()
    {
        points = 0;
        SceneManager.LoadScene("GameOver");
    }

    public bool CheckHavePackage()
    {
        return havePackage;
    }

    public void SetHavePackage(bool hp)
    {
        havePackage = hp;
    }
}
#

woops

#

forgot to remove a couple of static references

#

But this is what I have now.

leaden ice
#

DontDestroyOnLoad(gameObject); should only be in the if statement right after instance = this;

proven plume
#

Do you have any more information about

lunar forum
#

So, okay, follow up question. Since I removed the static references, when I want to call one of the methods in my singleton, I'm have to say GameManagerScript.instance.[some method]();. Is that the expected way to reference methods from my singleton?

leaden ice
#

yes

lunar forum
#

kk

leaden ice
#

that's the typical way to use a singleton

lunar forum
#

thought so, but wanted to double check.

leaden ice
#

It's not generally good naming convention to use the word Script at the end of your class names

#

We already know it's a script

#

that isn't adding anything

#

in fact it's not a script. The type represents a GameManager instance itself

#

not the script.

lunar forum
#

I only do it cause I named a script "Camera" one time and it messed me up for days.

#

I'm just paranoid I'm going to name a script something that is already a reserved word and frustrate myself for days again.

#

Otherwise I agree. I don't like adding that word, but keeps me from using reserved words by accident.

leaden ice
#

that's a mistake you only really make once

#

(the mistake is not naming your script Camera, but not realizing what the issues was for so long)

lunar forum
#

I mean, yea, I think I'd recognize the issue a lot quicker next time at the very least. I'll have to try the cmd clicking thing you mentioned. Never done that before.

leaden ice
#

(ctrl if not on a Mac)

#

basically get familiar with your IDE

#

it's a tool to make your life easier

#

it has all kinds of features that let you jump around the code and understand the code you're looking at more easily

soft shard
# lunar forum I only do it cause I named a script "Camera" one time and it messed me up for da...

If it helps, I try to name my scripts based on what they do, just naming a script "Camera" on its own doesnt describe what it does, if it moves the camera based on input, maybe "CameraController" makes more sense, if it takes screenshots from the cameras position, maybe "CameraSnapshot" makes more sense, this way you know both what the script is intended to do by its name alone, and hopefully wont run into issues of confusing reserved names

lunar forum
#

I think that's why I've named my scripts the way I have - I have wanted all functionality for the player object to be contained in one script, which then contains all the functionality for the player object. So, naming them on the function they provide hasn't been very obvious for me (unless a script I've written only provided one function in the first place).

soft shard
# lunar forum Does this mean that you would also then use multiple scripts on the same game ob...

Typically I would, yes, I have a specific naming convention that helps me know the general intention of most scripts I write, which may come with time and developing your own naming convention that makes sense to you, but its actually easier when you get used to using multiple scripts instead of trying to have 1 script do everything - for example, if I wanted to make a playable character, I might have a "InputManager" to detect movement keys, and a "PlayerController" to hold functions for movement, maybe a "CharacterController" if I wanted to control the physics of movement, maybe a "AudioPlayer" if I wanted to have footsteps when you move, etc

This way if theres a problem with say input, I know which script its in and I dont have to scroll through a 2000+ line script to find 1 function, it also lets me reuse parts of a script for other systems - say I wanted to add AI, they move, I could reuse the "CharacterController" and "PlayerController" since the "player" only moves from input, while AI doesnt, but physcally moving is the same

waxen jasper
#

I posted this in the network channel as well but I'm casting a large net :D. Whats the best approach to sync clients joining a session in progress? The issue I'm currently facing is all the network objects that have been destroyed are frozen in place at the place they were destroyed at before the client joined. I'm using a ClientRpc as well as a ServerRpc to return objects back to the pool. There's also some other weirdness happening on the client but I'll tackle that next. In the screenshot you can see frozen missles left over from the host(on the left) on the client(right).

plucky karma
# leaden ice ```cs public static GameManagerScript Instance => instance;```

If it wasn't for MonoBehaviour inheritance, GameManager would've be as easy as calling

public sealed class GameManager {
  private static GameManager _instance;
  public static GameManager => _instance ??= new GameManager();
  private GameManager() {} // to avoid accidentally ctor elsewhere. Also - should not invoke any expensive ops.
}
solemn raven
#

Hey ,
why does the following sample fails sometimes ?

float _temp = default;
float.TryParse(textMeshPro.text, out _temp );
_temp = _temp + 0.1;
textMeshPro.text = _temp;

the function above is a response to a click of a button, the error I get ( not a console error but a visible one )
it works fine several times , the number is increasing 0.1 on each click , except that some times it increases 0.10000001 , whcih appears on the display instead of 6.2 > 6.20000000001
what is wrong with it ??

craggy veldt
#

is the format 0.00000000 necessary? if not you can just do ToString() with an overload to format it so you don't need to do roundings etc

solemn raven
craggy veldt
#

but with an overload to your floats

solemn raven
#

what do u mean ?

craggy veldt
#

myFloat.ToString("0.00")

proper nymph
solemn raven
craggy veldt
lusty kite
#

Guys how can i calculate this spawn location. The black circle is the map size. The red circle is radius from the main player. I want to randomly spawn enemy in the green area where is it not out of bound of map area (black circle) but also not in the area of main player. The player will always be inside map area.

#

i have a way to brute force the solution where i just find a random location inside the black circle, can calculate the distance to the player. If the distance is smaller than the radius from player, find another random location.

#

this seems really slow and inefficient in the worst case that it might keep randoming inside the red circle.

#

is there better way to do this mathematically?

plucky karma
#

Anything wasted would be a wasted call.

#

Could consider SDF, or reclamp value to nearest?

flint sage
lusty kite
flint sage
#

I tried asking chatGpt but seems like it does exactly like what you did

#

which is kinda inefficient

spice frost
#

you could maybe do a similar approach but instead of trying new random points every time. Take the old "wrong" coordinate and shift it towards the black circle center. so in a sense you would use the initial random position as a seed and then trying to correct it. in some cases you might have to shift it away from the black circle center. So i would take the first random position, then try both moving towards the circle center and away from it. then try a different distance if that wasnt successful. the trick is figuring out the sweet spot of how far to move and where. But im 90% sure that in all cases theres a solution by either moving away or towards the black circle center.

spice frost
simple edge
spice frost
# simple edge I reckon there's a lot of edge cases with this approach E.g. generating a point ...

hmm there might be, where there would definitely be some is if you move towards/away from the red circle center. i have to be honest i cant visualize edge cases for moving away/towards black circle center, but ill take your word from it. I mean once you get the distance just right i think it would work. I think they might also be able to figure out a safe min/max distance for this method with some geometry. If they simply move away enough to be further from red circle than red circle radius they're in the green zone. either away or towards the center, or anywhere if red circle and black circle share a center. once again, I may be missing cases though

ruby fulcrum
#

bascailly the blue arrow representst he opposite direction from the player

spice frost
ruby fulcrum
#

if the enemy is pushed out of bounds, make it go in the same dir from the player to the new location

#

to prevent things like the enemy moving weirdly around the map, make an invis gameobject that calculates the location for the enemy and make the enemy go to that spot

molten saddle
#

I'm trying to draw an XYZ axis and label for an empty gameobject in the editor window.

The sphere is a Gizmo so that I can click it and select the object.
The sphere and axes are also Gizmos so that they are hidden by objects in front of them.
I'd like to use Gizmos to draw the label as well, but it seems that you can only do that with Handles.

My problem is that the Handle.Label is always behind the gizmos.

How can I draw the label on top of the gizmos? Is there some other way to do this?

public class SpawnPointGizmo : MonoBehaviour
{
    private const float AxisLength = 0.5f;

    private void OnDrawGizmos()
    {
        // X axis
        Gizmos.color = Color.red;
        Gizmos.DrawRay(transform.position, transform.right * AxisLength);

        // Y axis
        Gizmos.color = Color.green;
        Gizmos.DrawRay(transform.position, transform.up * AxisLength);

        // Z axis
        Gizmos.color = Color.blue;
        Gizmos.DrawRay(transform.position, transform.forward * AxisLength);

        // Sphere
        Gizmos.color = Color.white;
        Gizmos.DrawSphere(transform.position, AxisLength * 0.25f);

        // GameObject name
        Handles.color = Color.white;
        Handles.Label(transform.position, gameObject.name);
    }
}
simple edge
molten saddle
#

It also says Default value is Always., which I took to mean it's always supposed to be on top

#

I'm assuming that Gizmos just aren't included in the zTest.

Edit: I tried all 9 of the CompareFunction options and none of them drew the label on top of the gizmos
Here's the setup I used

Handles.zTest = UnityEngine.Rendering.CompareFunction.Never;
Handles.Label(transform.position, gameObject.name);
spice frost
clever lagoon
molten saddle
#

Oddly, if I put the gizmo behind an object, then it will show the label on top.
I guess that's because the gizmo gets occluded but the handles don't

plucky inlet
#

Your issue is, you want to show the gizmo on top everytime?

molten saddle
#

I want to show the Label on top of everything. It's a Handle instead of a Gizmo, and the Gizmos are showing on top of it

#

As far as I know, the only way to show text in editor like this is with Handle.Label

plucky inlet
#

Cant you just offset the label in z axis towards the camera?

molten saddle
#

That sounds like it might work. I'm not sure how to translate the position towards the camera like that

clever lagoon
#

^ not gonna be Z axis in world space if your camera has turned- but I agree .. moving toward camera is a good idea.

#

-camera.transform.forward would work tho

plucky inlet
#

yep, but as said, you could also just not use Label but use GUI and draw on top of everything with the script I pasted. different approaches

warm fractal
#

Making an RPG: In the past I had used enums to reference and figure out which stats to effect by code, and them being a hard-coded allowed me to directly reference them without issue. At some point it was suggested either by tutorial or a video or whatever to use ScriptableObjects in place of enums, so I was wondering if anyone had input on replacing enums with SOs for the purposes of something like stats in an RPG?

#

To be clear I've already been using SOs to at least initialize them, but I've reached the point where its becoming a bit tricky to deal with as I can't hard-reference certain things that I would normally need to. Was hoping someone had some thoughts as to the design philosophy

clever lagoon
#

The way to access each stat would still be "hard" coded in an SO, they would be the names of each of your stats, as a member of the SO derived class. But honestly , I'm not quite sure what your doing with the enums.

plucky inlet
soft shard
#

One way would be to use Linq and call .ToArray() on Knots, then access the index that way, though the position I know is not a Vector3, rather a float3 so you may need to convert or use each individual axis as needed, otherwise I think the type being a IEnumerable there may be other ways to access it

plucky inlet
#

Are you planning on changing the SO values on runtime to store stats or just as template for base things like items or character roles?

warm fractal
#

Well for example, my SO for a StatType declares a localized string name for the stat, min/max value, and a start value. I have one for things like MaxHealth, AttackSpeed, and so on.

#

The thought process originally was if there was a stat I hadn't considered that I may need, adding it would be as simple as creating a new SO.

#

But I'm finding it difficult to sort through them for a specific stat, leading me to think of things like sorting through all the SOs for things like an "ID" which then resembles me hard-coding it anyway.

plucky inlet
#

In this case, you would rather have to categorise your attributes to get your values taken into account rather then hardcoding the attribute itself. You gotta decide some base values in the end, otherwise you would try to make a full generic system which is not going to work well ๐Ÿ˜‰

warm fractal
#

I wondered as much. I guess I'm still not confident in my coding skills despite my years of doing it.

plucky inlet
clever lagoon
#

as long as you are consistent with the keys, you could even save them, rather than the whole SO object- when you save the game state

warm fractal
clever lagoon
#

ah, I must misunderstand the goal ๐Ÿ˜ญ

warm fractal
#

Finding that my "attributes" simply aren't a good fit for this methodology though.

#

I mean thats basically what I was doing up until now for them

plucky inlet
#

You might want to combine that enum with a scriptable object. You might have the Health type in your enum, and you can create SOs with that type that affect your health. But base values as a SO does not sound the best way, actually thinking you can add base elements later on does not sound like the right thing to go for, but maybe I am missing something

warm fractal
#

No, I had been ruminating on the thought of things like Health or AttackSpeed being separate for a bit now. It'd make things much simpler/easier/faster to work with, and its doubtful that I'll need to worry about it too much later on.

#

Thank you all for the correspondence, you've been most helpful.

rain minnow
warm fractal
rain minnow
warm fractal
rain minnow
#

using an SO as an enum is not a bad way of doing things. i do smth similar. makes it easy to add any amount of types without needing to update a file or an enum . . .

warm fractal
#

Yeah the conclusion was that it wouldn't work well for replacing core gameplay stat mechanics; i.e. max health which may need to be later referenced directly as opposed to "searched" for.

molten saddle
# plucky inlet I suggest not using label then. Maybe something like this https://gist.github.co...

I tried a couple of the solutions in here and they had the same issue, the Gizmo spheres draw on top of the Handle labels.
I tried moving the labels closer towards the camera, and it is also not making a difference. @clever lagoon

Handles.color = Color.white;
var view = UnityEditor.SceneView.currentDrawingSceneView;
Handles.Label(transform.position - view.camera.transform.forward, gameObject.name);

I appreciate the help, but it is looking like Unity just draws Gizmos on top of Handles here.
In that solution they are using UnityEditor.Handles. Is there a different way to draw text in the editor aside from Handles?

plucky inlet
#

The problem is the wish of being able to extend the base stats later on with new stats but nowhere in the code are they referenced then (what he means with hardcoding)

rain minnow
plucky inlet
rain minnow
plucky inlet
hollow cliff
#

is it possible to somehow query unity services player accounts from asp.net core server to authenticate users making api calls?

plucky inlet
#

The issue is, that he has to hardcode at least a switch or something to know what the stats are for. ANd it sounds like, he is not quite sure about his own system yet, as it might hold anything from health relevant to attack relevant stats. I suggested combining SO and enum, so the SOs have stats and a enum for the type they target like health or attack base stat. But if the goal is to also create those base stats based on SOs, thats gonna be a hard time

plucky inlet
rain minnow
# plucky inlet I think he means on development process, probably

that what it will do. i just have a list of stats. when i want to add a new one, i add to the list, which creates a new Stat and then i drag the StatType SO that represents the name of the stat. during gameplay, it creates a dictionary based on the list using the StatType SO and their associated Stat class . . .

hollow cliff
plucky inlet
hollow cliff
#

probably what i wanna do is impossible since players need to be able to play without login via anonymous authentication to unity services, but maybe it exposes some tokens for these "local accounts"

#

so users cannot perform web api calls in behalf of another accounts

plucky inlet
hollow cliff
#

user is there on server but i dont want to hold login data, only limited authentication based on unity user ID in token or something

plucky inlet
#

Did you read about unity game services then?

hollow cliff
#

another developer is kinda responsible for it for now, i have limited knowledge ๐Ÿ˜›

plucky inlet
#

well he should assist you then, because those services are actually the portal for what you need Id say

rain minnow
plucky inlet
rain minnow
plucky inlet
rain minnow
#

i mean, if you're creating a stat, you have to know what the stat is for, that wouldn't make sense otherwise . . .

plucky inlet
#

And I am not sure, this is the case in the current OPs thoughts ๐Ÿ˜‰

rain minnow
#

@marble fjord (message was deleted so i lost the reply/mention)
these questions can't simply be answered as they depend on how the character controller is coded/designed. performance is based off how you write the code, not so much with method is used. your pseudo-physics can be more cost intensive than regular physics

you'll always encounter glitches when working with physics and fast or large-moving objects. you test and set limits to avoid these issues. also, nothing will be glitch free

you can have full control using a physics-based (rigidbody) character controller or writing your own. you will still encounter glitches with your own character controller; not using physics or part of it does not omit any controller from that

the only concrete answer i see is physics should be limited or carefully maintained if developing on mobile . . .

true vessel
#

mouse click event is not working ?
because im using a render texture in my camara
is there any other way to mouse click event in render texture?

plucky inlet
drowsy crest
#

Whats the best way to have different build modes, eg. I want to do a slightly different version of the game - one for my level editor to use, one for my artist to easily replace assets, a Demo build to upload to steam etc. etc. I was thinking of something where I can make Unity set preprocessor directives just by choosing a different build option, eg. "Demo build" , "Level editor build" etc,

obtuse plinth
#

Please help me i want to disable automatic clean scene after every test. Chatgpt said something like that but i dont have this option ๐Ÿ˜ฆ

Open the Unity Editor and go to Edit > Project Settings > Editor.
In the Editor Settings, scroll down to the "Test Runner" section.
Uncheck the "Exit Play Mode After Test Run" option.
Click the "Apply" button to save your changes.

cosmic rain
#

Maybe look at the docs instead..?๐Ÿ˜…

obtuse plinth
#

i tried

dawn nebula
#

Is Unity ECS actually good to use now?

quartz folio
#

It's still not out of preview

dawn nebula
#

Alright but that doesn't aaaaalways mean bad to use ๐Ÿค”

cosmic rain
true vessel
plucky inlet
tender sphinx
#

How do i make my character run speed increase as time goes on? like in temple run

#

this is my current code for the movement and speed

plucky inlet
#

!code

tawny elkBOT
#
Posting code

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

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

tender sphinx
#

Oh sorry

#

Im new to this

rustic ember
#
            if (listPositionKeys.Any(item => item.key == _listPositionKey))
            {

            }``` Is this a lambda expression?
river wigeon
#

Does anyone have a link to a good outline package on asset store? Or is there a pre existing unity solution to produce an outline?

#

I'd like a blurred outline on 3d objects

rustic ember
#

I have a class that looks like this: csharp public class ListPositionKeyData { public string key; public int listPosition = -1; }
How can I do something like this: csharp int index = listPositionKeys.IndexOf(item => item.key == _listPositionKey)? I want to get the index of the element in the list of ListPositionKeyData where key == _listPositionKey

mellow sigil
#

If listPositionKeys is a list then .FindIndex

peak pivot
#

Anyone have experience getting CPU profiling to work with Pix? I can't seem to get it to read the PDB files ๐Ÿ˜

#

I've tried adding all the paths I can find with pbd files in them.

#

Yet all I see is this

#

When looking at sampled functions

#

(I'm using Pix here rather than Unity profiler since I want to do a sampled function profile)

#

When I tried using VerySleepy it correctly displayed the function names to it feels like I'm just somehow failing at getting Pix to understand where to find the symbols

peak pivot
#

I think I figured it out

#

Apparently I had to add a source path to <game_root>\<game_name>_BackupThisFolder_ButDontShipItWithYourGame\il2cppOutput

winged pulsar
#

can someone help me find why I'm getting this error? I don't call SendMessage at all in any of my scripts, and I don't think any of the plugins I'm using do either. Is some other function I'm calling invoking it or something??

leaden ice
winged pulsar
#

this is all it says (if this is what you mean)

plucky inlet
winged pulsar
plucky inlet
#

Id say this is a bug, you might call something on OnValidate or Awake or something, that triggers this or your plugins do

rustic ember
rustic ember
#

Umm

#

I have a string that matches a variable of one of the list elements. I need to find the list element with the variable that matches.

winged pulsar
rustic ember
# peak pivot Can you elaborate?

Yes. Something like this. Is there a super simple way to do this? csharp List<string> keys = new List<string>(); for (int i = 0; i < listPositionKeys.Count; i++) { keys.Add(listPositionKeys[i].key); } int index = keys.IndexOf("My Key");

#

The listPositionKeys have other variables than key too. I need to find the one from only knowing the key

#

So I can get the rest of the information

peak pivot
#

Like Nitku said, .Find .FindIndex or just a simple for loop

rustic ember
#

How can I use find and findindex for this?

#

I think I probably don't understand what they do. Can I pass in a parameter to look for in .Find? I thought I needed it to be the same type as the list elements

peak pivot
#

listPositionKeys.Find(i => i.key == "My Key");

mellow sigil
rustic ember
#

Thank you both ๐Ÿ™ ๐Ÿ™

steady granite
#

Hi, anyone know how I would add a new item to the create context menu in hierarchy, inside UI for example?

rustic ember
# steady granite Hi, anyone know how I would add a new item to the create context menu in hierarc...
steady granite
flint needle
#

Why would any of these instructions replace my mesh (on meshFilter) for an instance of the mesh?

                var colors = mesh.colors;
                var triangles = mesh.triangles;

                int triangleIndex = hit.triangleIndex;

                var c0 = colors[triangles[triangleIndex * 3 + 0]];
                var c1 = colors[triangles[triangleIndex * 3 + 1]];
                var c2 = colors[triangles[triangleIndex * 3 + 2]];

                float red = (c0.r + c1.r + c2.r) / 3;
                float blue = (c0.b + c1.b + c2.b) / 3;
                float green = (c0.g + c1.g + c2.g) / 3;```
buoyant mural
#

ChatGPT answer: None of the instructions you provided should replace the mesh on the meshFilter component. These instructions are simply retrieving data from the mesh and performing calculations on that data. However, if you have other code that modifies the mesh or the meshFilter component, it could potentially replace the mesh at runtime.

flint needle
#

Thats what i thought, but commenting those lines erases the problem, the rest of the code is just reading the red blue green floats and playing a sound that

#
                {
                    return Surface.Grass;
                }
                
                if (red > VertexColorTolerance)
                {
                    return Surface.Path;
                }```
#

Its just that

buoyant mural
#

What about this?

flint needle
#

the only code left, i then have a switch that plays a sound and thats it

buoyant mural
#

Hmm

#

So what's your problem rn?

#

What exactly isn't working?

flint needle
#

It replaces the meshFilter for a mesh Instance

#

So the collider and the Filter dont match

buoyant mural
#

Mm

#

Ok

flint needle
#

also this is the only new code and i never had this problem before, so it has to be. (It doesnt interact with anything else, its just a sound player)

buoyant mural
honest citrus
#

Hello Unity peeps, is there a component for motion blur and animation frame rates?

flint needle
buoyant mural
#

By itself huh

flint needle
#

I didnt write any code for it afaik

honest citrus
buoyant mural
sweet inlet
#

I create screenshots using a renderTexture and save them as png, as a result of my approach i get transparent borders around my image (need to make the camera big enough so that different things are always in the frame), is there a way to remove these transparent borders somehow?
I also noticed the colors are different than whats seen onscreens, so i am not sure what todo about that

public void saveScreenshot()
    {
        foreach (var hideObject in hideScreenshotObjects)
        {
            hideObject.SetActive(false);
        }

        gameObject.GetComponent<RectTransform>().position = new Vector3(1372, 720, 0);
        gameObject.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
        
        mainCanvas.renderMode = RenderMode.ScreenSpaceCamera;
        mainCanvas.worldCamera = cam;
            
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture.active = cam.targetTexture;

        cam.Render();

        Texture2D Image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
        Image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
        Image.Apply();
        RenderTexture.active = currentRT;

        var Bytes = Image.EncodeToPNG();
        Destroy(Image);

        File.WriteAllBytes("Screenshot.png", Bytes);
        mainCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
        counter = 0;
            
        foreach (var hideObject in hideScreenshotObjects)
        {
            hideObject.SetActive(true);
        }
    }
hexed pecan
#

sharedMesh doesnt do that

flint needle
#

That must be it let me try

buoyant mural
#

Shared mesh modifies every object with that mesh

#

Same for anything Shared like materials

hexed pecan
#

I dont see them modifying it, just reading

flint needle
#

But im just reading

#

yeah

buoyant mural
#

Oh wait nevermind I just read his code

flint needle
#

It works yesss

hexed pecan
buoyant mural
#

Nothing

hexed pecan
#

It should, according to documentation

buoyant mural
#

I hadn't read the code

#

Correctly

#

You are right

#

Isn't it the same for materials?

flint needle
#

np guys its working, the return did indeed make an instance and assign it as the docs say. Just not in the mesh collider just the mesh filter ๐Ÿ™๐Ÿป ๐Ÿฅน

hexed pecan
buoyant mural
#

Hm

flint needle
#

appreciate your help have a nice day

stone rock
#

Hello, i have an event that doesn't seem to get fired or it does but the subscribed function isn't getting called
This is a part of the code in my script handling general events, it is a singleton but also has static events since i ran into an issue with the update cycles so needed to make sure the events were accessible at any time.

public static event Action OnPause = delegate { };
public static void Pause()
{
    OnPause();
}

This is a part of the script for my pause menu

private void Awake()
{
    GameEventsManager.OnPause += ActivateMenu;
}

private void OnDestroy()
{
    GameEventsManager.OnPause -= ActivateMenu;
}

public void ActivateMenu()
{
    Debug.Log("The activate menu function is called");
    this.gameObject.SetActive(true);
    _resumeGameButton.interactable = true;
    _mainMenuButton.interactable = true;
    _quitGameButton.interactable = true;
}

So i tested with some debugs and in the function Pause() the debug message get's called but after that it can't work it seems

#

I think it's probably the subscribing were the issue lies i assume

buoyant mural
#

Yeah

#

It is

hexed pecan
buoyant mural
sweet inlet
#

i get transparent borders and the colors are wrong, its not supposed to be that saturated

#

and these dark blue icons i added are way too dark aswell, not sure why

stone rock
hexed pecan
buoyant mural
#

Yeah

stone rock
#

i changed to on enable and on disable and it is the same

buoyant mural
#

That was an example

#

Don't change

sweet inlet
stone rock
#

But what could the problem be with my subscription, it's a static event so i don't think it should be a problem

swift falcon
#

I have an asset bundle which I want to reference it in a script. If I put "public AssetBundle myAssetBundle" and then try to add it from the inspector, I cant.

sweet inlet
#

nvm, i forgot to mention that everything is on the UI layer, so ortographic doesnt do anything here

hexed pecan
sweet inlet
#

that's a texture i have in my resources folder

hexed pecan
#

Okay, then you probably need to match that texture's size to your map

sweet inlet
#

i can try that approach

#

actually a good idea, i think i have a working idea

stone rock
#

Is it correct that Awake isn't called on disabled gameobjects that are disabled in the editor so at the start of the scene/game?

stone rock
#

Yeah, just found it in the docs

#

I need to remember that because this was my issue

cold parrot
#

its a good idea to treat edit-mode disabled game objects as if they don't exist by your runtime

stone rock
#

Yeah, i will make more use of disabling in awake or somethng if they don't need to be active or another method.
I just had an event i needed to subscribe to for my pause menu but the menu was disabled

cold parrot
#

its a very useful property that if you break it can make handling your project much more annoying... just my experience... might not apply in special situations

stone rock
#

yeah, it's just in this specific case that it wasn't that useful

cold parrot
#

i've found that disabling components is the more useful approach to disabling behaviour

leaden ice
stone rock
#

Yeah, i will do one of those in the future

elfin tree
#

Off the top, can you guys think of a cleaner way of doing this other than just having a method only for that in the _deckController?

                while (_deckController.RemoveCardByKeyword(Keyword.DISCARD)) {}

It returns true if a card was removed. Is this that bad?

plucky inlet
elfin tree
west sparrow
#

It's hard to say without seeing more. I'm assuming there is a reason you are using a while instead of an if. But the slowdown is going to be in the desk controllers code if there is a slowdown. In of itself, as long as that isn't in an update, I'm sure it's fine.

I'd probably go a different route and use an event when a card is removed, but I'm sure it makes little difference in functionality

elfin tree
#

And I don't know, I usually try to avoid those for some reason

elfin tree
mossy shard
#

if i wanna make an entity go to a specifc coord, do i just add the force forwward to the entity in the direction in which the position is and stop it when it reached it?

#

does it seam like a good idea?

#

or is something better

west sparrow
plucky inlet
mossy shard
mossy shard
#

i never got interested in seeing how it's done

#

i just assumed that's how

west sparrow
#

Yeah, one of our VR flying games, we abuse the bejesus out of add force. The client wanted a lot of unusual specific mechanics (bout 15 specific formulas he wanted to apply depending on hand movements), so manipulating the force that way was the best way while preserving physics

mossy shard
#

oh alr, thx

rustic ember
#

Can someone point me in the direction of an algorithm? I need an algorithm that is similar to A* search, except that it searches for tiles within a certain distance. All tiles reachable within fx. 5 moves should be returned

leaden ice
uncut plank
#

or perhaps theres an existing implementation

leaden ice
#

djikstras if your graph has weighted edges

#

BFS if not

uncut plank
#

oh right

#

got the name confused

plucky inlet
#

there is a github repo with examples, but its 4 years old, not sure its still relevant

leaden ice
#

Djikstra is basically a modified DFS/BFS with edge weights and a shortest-path table

#

but they don't really need shortest path

#

they just want to get the list of tiles

plucky inlet
rustic ember
#

Thank you both all for the suggestions ๐Ÿ™

leaden ice
#

exactly the same problem you are solving

#

they wanted to highlight walkable tiles in their hex grid

rustic ember
leaden ice
#

ofc it assumes some things specific to their grid implementation

#

o you'll have to adapt it

#

but it's just a BFS with a depth limit

rustic ember
#

Thank you. I really appreciate it

leaden ice
#

one thing you won't have is the neighbors() function

#

but it's just a function that returns the neighbors for a given coordinate

rustic ember
#

all 6?

leaden ice
#

yes

rustic ember
#

alright

leaden ice
#

how it worked out for them and their final script^

magic harness
#

hey guys, im having some trouble with 2D collisions not firing

leaden ice
magic harness
#

What is my set-up?
2 prefabs with 2 childs each. Each child has a trigger and a script attachted to it.
The prefab has a kinematic rigidbody 2d

#

layers are set to collide

#

i have tried disabling trigger and just seeing it if collides, and it doesnt

#

just went through all if that troubleshoot and still nothing

#

i am moving it using transform.position

#

but it is kinematic, so it shouldnt matter

#

i just need the trigger to fire

#

at least in the scene view, the collider moves correctly with the game object

#

im very confused

plucky inlet
#

if you use transform.position, you ignore collisions

#

and are the colliders the 2d version of it too?

leaden ice
plucky inlet
#

Ahh thanks for the link, I just couldnt find the unity how to thing ๐Ÿ™‚

magic harness
#

it was probably cause i was using transform.position

#

but not it just moves to 0,0 at start

plucky inlet
magic harness
#

they are kinematic

plucky inlet
#

So maybe you show your current script and where you debug log that it is not hitting

magic harness
#

so this is my move function which gets called on fixedupdate


protected void Move(Vector3 goalPos)
    {
        Vector3 direction = (goalPos - transform.position).normalized;

        Vector3 nextPos = direction * moveSpeed * Time.fixedDeltaTime;
        body.MovePosition(nextPos);

    }

and this is my very simples message callbacks

#

so... debug.log in the trigger enter is working actually. but they are just instantly moving to 0,0,0 position on start. kinematic rigidbody2d and gravity set to 0,0,0 in project settings

plucky inlet
leaden ice
#

MovePosition takes an absolute new position

#

not a direction to move in

#

also nextPos is kind of poorly named - as it's more like a movementVector or positionDiff, not a position outright

magic harness
#

holy... you are right

#

thanks

sonic stream
#

    private void FixedUpdate()
    {
        Vector2 playerDirection = (Player.position - transform.position).normalized;
        if (Vector2.Distance(transform.position, Player.position) > 1.6f)
            _moveBody.velocity = (playerDirection * _speed).WithY(_moveBody.velocity.y);
    }

so i am trying to make an enemy follow the player with an offset,but it keeps alternating between the player's right and left,any idea how to fix it?

#

brb video is black for some reason,gonna rerecord

leaden ice
#

because of newton's first law of motion

#

"An object at rest remains at rest, or if in motion, remains in motion at a constant velocity unless acted on by a net external force."

sonic stream
leaden ice
#

i mean... sort of? It's going to be very stuttery

#

also you didn't mention before but it seems you are only interested in the x position for this?

tidal locust
#

I dont know if this comes under coding, or it might. But does anyone know why this happens ?

leaden ice
tidal locust
leaden ice
#

Nobody can fix it except Unity

sonic stream
leaden ice
tidal locust
leaden ice
#

Turn off Error Pause in your console

tidal locust
#

I mean I did that, u mean click error pause right ?

leaden ice
#

In your screenshot, error pause is enabled

#

that's why your game is stopping whenever that error happens

#

turn it off to stop that from happening

tidal locust
#

Alright did that, but now the game is super laggy :/

hexed pecan
#

The error looks like a memory leak awkwardsweat

tidal locust
#

Go through all my scripts and try and fix them>

#

could that be doing it

hexed pecan
#

Probably unity itself, try googling that error

tulip violet
#

any unity dev with regards to generative ai?

solemn raven
#

Hi ,
what is the equivalent of Math.Round() in unity ?

tidal locust
#

I ran the profiler and found this ?

solemn raven
#

Math.Round() has overloards , but Mathf.Round() doesnt
is there is any other alternative ?

tidal locust
#

Something under LogStringToConsole

leaden ice
solemn raven
#

based on the equation

leaden ice
#

Well you can use Math.Round

#

no problem

#

but you can also do that with Mathf.Round

solemn raven
#

It higlights Math as unknown , do I need to add something ?

leaden ice
#

Take a guess

#

and maybe mouse over it

#

and see what it says

#

you should be used to fixing this by now ๐Ÿ˜‰

solemn raven
#

oh yeahhh ๐Ÿ˜„ , thanks actually , i need to trusth that hint ๐Ÿ˜„

#

I remember when I first started to learn C# that tip used to do things and add drivatives that I didnt understood and scared me, so I stopped using it all together lol, I will start trusting it again ๐Ÿ˜„

solemn raven
tidal locust
#

Just clicking in the editor gives me them error messages

#

Alright so I have restart unity and see if that fixes it, it has for now. I dont know if that is a full fix

simple edge
#

Restarting can fix quite a few unity issues sometimes
Unity's terrain system providing memory leaks comes to mind

tidal locust
#

You think its the the terrain ?

simple edge
#

No, that was just an example
Idk how long ago that was, but it used to have memory leaks

tidal locust
#

Ahhh I see, alright. well I think I might know what the issues was. I think it was the old first person controller ?

#

because I moved my game from 2018 version to the 2021 version

#

Nope it happen again

#

Do I just drop down a version ?

inner yarrow
#

Is there anyway to make an overlay camera use an oblique projection matrix?

lean elbow
#

guys

#

oculus dev hub

lean elbow
#

im trying to upload a build to oculus dev hub but it gives me a API error

leaden ice
lean elbow
#

thanks

inner yarrow
leaden ice
#

the fact that it's an overlay camera isn't really a factor

inner yarrow
#

Simply changing the near clip plane does have an effect, but I don't want it to always be flat, so I need the oblique matrix.

#

I'm using it in a camera stack. The preview for it is using the custom clip plane, but the image being stacked onto the main camera's view is not.

elfin tree
#

How can I find the element of a list with the highest value using a .Get() method on it in LINQ?

#

I know I want to use .Max (default list method) and .GetHP (specific to my context).

#

I know how to get the value, but I want to get the object itself.

#

This is how I would get the value in case it helps:
opponents.Max(o => o.GetHP());

tiny delta
#

Hey there folks, I've created a few math-related methods for myself that I can use for a bunch of different scripts, so I'm planning on putting them in a separate script where they can be called. Should these go in a struct or a class? I was planning on a class, but then I saw that Mathf uses a struct so I'm not sure anymore.

hexed pecan
#

Not sure why Mathf is a struct or if its common for these kinds of method collections

#

If someone knows the reason let me/us know

late lion
#

Looks more mathy, obv

#

I don't know the reason. There's no difference in performance or anything like that. But in my IDE theme, structs are a different color than classes, so Mathf is the same color as Vector3 and etc... Which I like, but ๐Ÿคทโ€โ™‚๏ธ

late lion
hexed pecan
#

Sometimes I forget how old unity is... 2007 damn

tiny delta
buoyant crane
#

pretty interesting

tiny delta
#

Oh that makes sense

worn crystal
#

so wondering, but is there any way I can overwrite the default behavior of serialization? so specifically for my case, I have a struct called UnlockableId and its pretty much a wrapper for a string. the problem is that when I apply Serializable to the struct, in the asset hierarchy it serializes like this:

#

_unlockableId being the field name thats to be serialized, but itll serialize the _value under it

#

is there any way I can make it so that itll be morelike _unlockableId: {value} rather than it like this?

#

same deal on deserialization

floral coral
#

How can I automatically subscribe to a public event (like OnClick() for the UI button) if I have a reference to the instance of the object with the script that has the event?

late lion
worn crystal
#

its in yaml so im trying to see if I can overwrite its serialization/deserialization behavior

late lion
oblique spoke
tepid river
#

Serializable will serialize all members, including privates

#

But its not the only qay to serialize things

worn crystal
#

thats sort of what im trying to figure out, a way to have it read/write differently so when it tries to fetch it afterwards itll implicitly convert it to the struct

late lion
worn crystal
#

also another reason i want to do this being im setting these values to firebase, so i dont want there to be a bunch of _value fields

#

^ biggest reason being this

#

firebase is json serialization so im confident i can customize that behavior before i sent out the request though

tepid river
late lion
#

Why do you want to rely on Unity's serialization for this instead of rolling your own?

worn crystal
#

hmm fair, something i should consider

#

also do note, i dont plan on directly sending out the entire yaml string to firebase or anything lol

#

but fair enough, ill make some changes

sonic stream
#
    private void Update()
    {
        if (IsCloseToPlayer && Time.time >= _nextAttackTime)
        {
            var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer);
            OnAttack?.Invoke();
            _nextAttackTime = Time.time + 1 / _attackRate;
        }
    }

so i am trying to make it so that enemies attack the player when he is close to them,but they have a weird attack pattern,any ideas why this is happening?

tepid river
worn crystal
#

this is for saving objects to firebase, so i need it to be as small and lightweight as possible (hence why im trying to remove the redundant field)

tepid river
#

In my experience using extra containers was the rught thing to do, since loading/saving is notnsomething you want to clutter your class with

#

And it makes mocking data for testing easier too

worn crystal
#

we arent making a save system

tepid river
#

Well same goes for networking etc

#

Anything serialization related

leaden ice
sonic stream
leaden ice
#

I watched it

#

wasn't sure what I was looking at exactly

#

it seemed like it attacked on a regular interval

sonic stream
#

it randomly attacks when the player leaves and when the player is still close,it doesn't attack

leaden ice
#

but you also moved your character at that same interval

leaden ice
#

We'd need to see the rest of the script

sonic stream
# leaden ice We'd need to see the rest of the script
private static Transform Player => GameObject.FindGameObjectWithTag("Player").transform;

    private bool IsCloseToPlayer => Vector2.Distance(transform.position, Player.position) > 1.3f;

    public event System.Action OnAttack;
    [SerializeField]
    private LayerMask _playerLayer;
    [SerializeField, Min(0.01f)]
    private float _attackRate = 1;
    private float _nextAttackTime;

    private void Update()
    {
        if (IsCloseToPlayer && Time.time >= _nextAttackTime)
        {
            var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer);
            OnAttack?.Invoke();
            _nextAttackTime = Time.time + 1 / _attackRate;
        }
    }
#

this si what is inside the class

leaden ice
#

this seems like it does the opposite of what its name is

#

it's checking if you are at least 1.3 meters away from the player

#

don't you want < instead of >?

sonic stream
#

let me see

leaden ice
#

(also this line var enemies = Physics2D.CircleCastAll(transform.position, 0.5f, transform.right, 1.5f, _playerLayer); seems to be unused entirely)

sonic stream
leaden ice
#

how so

#

you already have a reference to the player

#

Oh I see it's the attack range or whatever

sonic stream
leaden wharf
#

Hello, im making a 2d platformer and want one part of the collider of the tilemap to be disabled when if press "s". Can anybody help me?

uncut plank
# leaden wharf Hello, im making a 2d platformer and want one part of the collider of the tilema...

In this short tutorial we will have a look at how to create one way platforms - ones that you can jump through and how to allow player to fall through them by pressing the down button. I hope you enjoy it :).

Got any questions? Join our discord:
https://discord.gg/hrZF93sCkc

#UnityTutorial #Unity #Platformer

Feel free to join our discord: h...

โ–ถ Play video
leaden wharf
#

Yes, but does this work for parts of a tilemap? Because i cant add components to them

candid trench
#

Got a bit of a problem i need solved.

I have > 25 "units" in my game.
on the prefab of each unit i have a camera that is assigned a RenderTexture as a target texture that is created via code when the unit is instantiated.
This rendertexture is then used in my canvas to display sort of what units are selected during runtime.

This is working great, exactly as i want it.
Now here's the problem.
All the cameras ofcourse render all units, not only the parent unit that it is attached too.

I thought of using the Culling mask option of the camera to only render the specific unit. But that'd mean that i have to create some +25 layers for each of the units.
Is there any better way of doing this?

uncut plank
leaden ice
#

only one of them will be in that layer at a time, so the culling masks will work

candid trench
#

hm. good idea. But will the rendertexture change over time then? or do you mean to just take a "snapshot" to get a still picture?

leaden ice
#

I assumed you meant still pictures

candid trench
#

I suppose i can swap then in and out every frame

#

them*

candid trench
#

otherwise id just make an icon in photoshop or whatever

candid trench
#

do you mean move it to the snapshot layer before i call Create() on the rendertexture?

rustic ember
#

When was this added to C#? csharp List<Transform> objs = new();, specifically the csharp = new();

#

Wait nvm, its 9.0

#

I'm on 8.0 still ๐Ÿซก๐Ÿ”ซ

leaden ice
#

You could also do it with manual Render calls on the cameras

#

but it's going to be really slow

near crown
#

All I added was a RB.AddForce ; but even removing it won't resolve this... help

leaden ice
#

possibly setting it to 0 each frame

near crown
#

it isnt

#

the addforce

leaden ice
near crown
#

adds, doesnt it?

leaden ice
#

show your code

near crown
#

wait

#

it got modifyed

leaden ice
#

!code

tawny elkBOT
#
Posting code

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

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

leaden ice
#

Post code this way^

near crown
#

ok

#

I really tryed anything, the Rigidbody bahaves weird even without the script

leaden ice
#

some script on a different object

near crown
#

and what is it^

leaden ice
#

try disabling all your ther objects in the scene

#

until it works normally

near crown
#

nothing

#

on an empty gameobject tho the rigidbody works normal

leaden ice
#

show your whole scene

#

you've got some other scripts around

near crown
#

um no

candid trench
near crown
#

I don't

leaden ice
#

you must

near crown
#

I don't have other scripts that could mess with it

leaden ice
#

copy mario into another scene

near crown
#

okie dokie

leaden ice
#

also show what the script looks lioke int he inspector when you select it

#

maybe you forgot to save your changes

#

Like what's this "Player" script I see in your assets

near crown
#

Player script? You mean MarioMove?

leaden ice
#

no

#

I mean the one called "Player"

#

it's in your screenshot

near crown
#

ah that one

#

it just gets the new input system

#

btw Mario in a new scene works just fine

#

maybe smth with that camera script... let me check

leaden ice
#

like I said - probably one of your other scripts

near crown
#

I'll show you them all while I check wich scripts mess up the whole thing

leaden ice
#

show the camera one

near crown
leaden ice
#

bruh

#

you're doing this

#

every frame

#

and you're confused about why you're seeing what you're seeing??

near crown
#

but it's on the camera

#

it has its own rigidbody

leaden ice
#

It doesn't matter where the script is

near crown
#

I belive

leaden ice
rustic ember
leaden ice
#

that will find ANY Rigidbody2D

rustic ember
#

On line 13

leaden ice
#

not just the one on that object

leaden ice
#

Sorry that can just be out _ @rustic ember - we don't actually care about it

sterile tendon
#

I'm trying to make a 4-track audio player that lets you swap out different "stems" of a song in real time, but I'm running into issues with getting the total amount of "beats" elapsed since the start. Since you can change the tempo in real time, I'm using
beatsSinceStart += Time.deltaTime * tempo.value / 60; which works on lower tempos but gradually becomes inaccurate with faster ones. is there any better way to do this?

rustic ember
leaden ice
leaden ice
#

that's how it returns the value

#

but we're not using it

#

so HasKey is better

rustic ember
#

Right, okay. Thanks again ๐Ÿ˜…

sterile tendon
#

oh nvm AudioSource.timeSamples exists

leaden ice
rustic ember
leaden ice
#

plausible

rustic ember
#

Unless that is something differnt

leaden ice
#

I just pulled it out of my ass ๐Ÿ˜‰

#

ContainsKey is probably right

sterile tendon
#

thanks

rustic ember
near crown
#

Ty @leaden ice now the rigidbody works as usual

candid trench
#

actually managed to get memory leaks in a language with a garbagecollector. wonderful, good job me

candid trench
rustic ember
candid trench
rustic ember
#

Alright. Thanks

candid trench
#

there might be some internal optimizations to queue tho. Since its kind of designed for that kind of thing.

rustic ember
candid trench
#

aye ofcourse, but thats just a quality of life sort of a thing. you can easily make your own dequeue for list

private Item Dequeue(List<Item> list)
{
  Item item = list[0];
  list.RemoveAt(0)
  return item
}
somber nacelle
#

single ` ` around text instead of triple

candid trench
#

or if youre using Linq you can use list.First()

#

or just save yourself the hassle and use a Queue if you intend to have a list that is a Queue ^^

rustic ember
#

Oh, nice. I like how clean the Queue thing is though

leaden ice
#

list.RemoveAt(0) will be an O(n) operation

#

queue.Dequeue will be O(1) or O(log(n)) or something fast like that

candid trench
#

how is not queue a O(n) operation ? ๐Ÿ˜ฎ

#

i may have forgotten something from my class in datastructures...

leaden ice
candid trench
#

hm, right

leaden ice
#

with a list, RemoveAt(0) requires you to shift all elements of the backing array

rustic ember
candid trench
leaden ice
somber nacelle
#

when you remove from a list it has to shift all of the following elements down. queue just removes from the end without needing to perform any other operations and it always has a reference to the end position making it O(1)

candid trench
somber nacelle
#

also o(1)

leaden ice
candid trench
somber nacelle
#

ah perfect, was just looking for that

leaden ice
#
        private int _head;       // The index from which to dequeue if the queue isn't empty.
        private int _tail;  ``` 
Basically it keeps these head and tail index pointers into the array to know where the ends are to add/remove from
rustic ember
#

What happens when it reaches the end of the allocated memory?

#

If that is even a thing

leaden ice
#

it will have to reallocate the array as a larger array

#

same thing List does

leaden ice
#

that's an O(n) operation but it's amortized across all add operations in the analysis so it's still considered O(1) to add

rustic ember
#

Damn. Computers are so cool

candid trench
#

haha, no. People are so cool

#

someone came up with it you know

#

๐Ÿ˜‰

rustic ember
#

I guess

neon plank
#

Question: I'm using NavMeshSurface collect CurrentObjectHierarchy. How can I in addition to collect all objects from the hierarchy, to also include some cherry-picked gameobjects from outside?

sterile tendon
# leaden ice yea you should use this and/or dspTime whenever possible

weird I'm still running into tempo issues

    void Update()
    {
        if (started)
        {
            float totalTime = (float)AudioSettings.dspTime;
            float newTime = totalTime - oldTime;
            beatsSinceStart += newTime * tempo.value / 60.0f;
            oldTime = totalTime;
            if (beatsSinceStart >= 32)
            {
                beatsSinceStart = 1;
            }
        }
        else
        {
            oldTime = (float)AudioSettings.dspTime;
        }
    }

could the fact that I'm changing the speed of the audioplayer be impacting precision?

leaden ice
nova roost
#

The Unity documentation for Input.GetAxis states that the value is frame independant. This doesn't mean we won't need to multiply by Time.deltaTime, correct? For movement it's still
float movementX = Input.GetAxis("Horizontal") * movementSpeed * Time.deltaTime;
Is there a difference between GetAxis("Mouse X") and GetAxis("Horizontal") regarding this? I've noticed the values for the mouse exceed the -1 to 1 range. Is this a special case? Which line would be correct?

float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;```
leaden ice
#

and they are mentioned in the docs

#

you should not multiply mouse input by deltaTime

#

it is already framerate independent

nova roost
#

Great!

leaden ice
sterile tendon
#

or just add it every frame

leaden ice
#

oh right

sterile tendon
#

thanks though! this is really helpful

leaden ice