#archived-code-general

1 messages · Page 169 of 1

plain juniper
#

Hi everyone, I'm working on a card game and after having created them as a scriptableobject I'm trying to create a list to be able to use it when I have to create the player's deck. How can I do according to you? I would later like to set quantity limits based on rarity but that's something I can do later

proper flume
#

wait bruh i see why

#

ok

somber nacelle
#

where and how? because your mesh variable is private so no other objects can access it and i don't see you assigning it to any mesh filter anywhere

proper flume
#

basically

#

the triangle list is supposed to have arrays

#

but its numbers

#

big fail

gray mural
#

where is mesh attached to the specific GameObject?

proper flume
#

wait guys

gray mural
#

GetComponent<MeshFilter>().mesh = mesh;

proper flume
#

ohhhhhh yes

gray mural
#

I haven't mentioned this first time though.

#

actually that's what boxfriend said before

proper flume
#

bru

#

now

proper flume
#

so now it half works

somber nacelle
#

that's cool. you still weren't assigning the mesh to the mesh filter anywhere in the code you showed

proper flume
#

the first shape is created

#

something happens with the second one idk

#

and the second shape is never visible

gray mural
#

well, because you don't assign it

proper flume
#

wdym

#

its in the vertices list

#

and the triangles list

gray mural
#

you mean just mesh's 1st shape is visible?

proper flume
# gray mural you mean just mesh's 1st shape is visible?

CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(1, 1), new Vector3(1, 0), new int[] { 0, 1, 2, 0, 2, 3 });
CreateShape(new Vector3(0, 0), new Vector3(0, 1), new Vector3(0, 0, 1), new Vector3(0, 1, 1),new int[] { 0, 1, 2, 0, 2, 3 });

#

the first one is visible

#

the second one isnt

hidden gulch
#

ohh makes sense

proper flume
#

back when it was all I know is that its next to the square that appears

#

but now it doesnt

gray mural
#

try to create just the second shape

proper flume
#

itappears

#

it appears

gray mural
#

yes.

proper flume
#

i think i know why

#

is it because the triangles list

#

has numbers

gray mural
#

so problem is that you create the second shape on the first shape

#

so you don't see it

proper flume
#

wait

#

am i supposed to like

gray mural
#

you are supposed to fix it, yes

proper flume
#

give the mesh.triangles arrays

#

or what

gray mural
#

what does it mean?

proper flume
#

it accepts numbers for triangles

#

but i have a list containing numbers for each triangle

gray mural
#

just spawn it on another place?

proper flume
#

maybe I should put arrays into the lists

#

and then iteriate through it

#

for each triangle

#

would that be effective

gray mural
#

just change vector parameters

proper flume
#

what

#

thats not the issue

#

wait

#

can i like add triangles

#

to mesh.triangles

#

not set the mesh.triangles

gray mural
#

yes.

proper flume
#

how

gray mural
#

aren't you doing it already?

proper flume
#

no

#

im setting it

gray mural
#

triangles.AddRange(trs);

proper flume
#

no

gray mural
#

what's that?

proper flume
#

mesh.triangles

proper flume
gray mural
#

so?

somber nacelle
#

mesh.triangles is an array. arrays are not resizable, you have to reassign it

proper flume
#

mesh.triangles is in a different place

gray mural
#
triangles.AddRange(trs);
mesh.triangles = triangles.ToArray();
#

you do this

vagrant blade
#

Can you both take it to a thread so you're not flooding this channel?

proper flume
#

like

#

how ma i supposed to put several triangles at once

#

if i give it a array with more numbers itd oesnt work

vagrant blade
proper flume
#

wait bro then why does this channel exist

vagrant blade
#

To ask and get help, like every other channel.

proper flume
#

yes

vagrant blade
#

Great, make a thread since this conversation is clearly going long and so it doesn't flood this channel.

void remnant
#

Let's say we have a simple square. When it's at default rotation, the boxCollider2d.bounds corresponds with the collider edges. But when I rotate the object, will the bounds change?

void remnant
#

so the second image

gray mural
#

yes.

void remnant
#

thanks

swift falcon
#

Hi, ive been experiencing an issue when implementing recoil to m gun in my fps game and basically whats happening is that the animation plays on only the first shot and never after it, but when i aim and try again it recoils but again only on the first shot. keep in mind that both the aim a the recoil are animations. relevant scripts: https://pastebin.com/fkqrXRh4

#

also the animation controller

#

i think its probably somthing to do with the animation controller

smoky basalt
#

If anyone knows how to use profiler I posted a screenshot in #⚛️┃physics ! Would love help optimizing my game so it is playable! Thanks in advance

swift falcon
#

(T)Convert.ChangeType(maybeAnInterfaceHere, typeof(T)); vs maybeAnInterfaceHere as T

tepid brook
#

Hi guys i'm using cinemachine in the starter assets 3rd person and i don't know how to change the sensivity and there is nothing on google can someone help me pls

leaden ice
tepid brook
#

i use Cinemachine Virtual Camera but i found the Input action asset thx

leaden ice
#

the starter assets thing uses FreeLook

#

if you're doing your own thing, that's separate 🤷‍♂️

spring steeple
#

So im working on a multiplayer fps game but the audio is only being played locally so other players cant here sound effects i.e. shooting reloading etc. would anyone know how to fix this? any help would be appreciated.

lean sail
vivid heart
#

Hi

tawny mountain
#

Is AR a requirement for a barcode scanner in unity?

main shuttle
tawny mountain
main shuttle
tawny mountain
past karma
#

is it possible to have nav mesh in a prefab?

#

i am doing a 3d roguelike

devout solstice
#

Im pretty sure Ive done it before but I forgot, how do I set a gameobjects component to a variable and be able to manipulate that component like you could if you did gameObject.GetComponent<>(), I want to do gameObject.GetComponent<BoxCollider>().SetActive() but i dont want to use getcomponent multiple times, i just want to be able to set it to a variable but still do .SetActive()

leaden ice
devout solstice
#

I know but what type do i use for the variable to get the result i want

leaden ice
#

Whatever type you're getting of course

devout solstice
#

boxcollider doesnt work component didnt work

leaden ice
#

BoxCollider bc = GetComponent<BoxCollider>();

devout solstice
#

oh

leaden ice
#

Works just fine

robust dome
#

or use GameObject and SetActive false

devout solstice
#

id have to use getcomponent multiple times

#

i dont want to do that

leaden ice
#

SetActive is a GameObject function though

devout solstice
#

it let me do gameObject.GetComponent<BoxCollider>().SetActive(false)

leaden ice
#

Even if it does that's no different from gameObject.SetActive

#

There's no need to go through the collider

devout solstice
#

oh so that wouldnt set the component to false?

leaden ice
#

Components cannot be "set to false"

#

They can be disabled though

devout solstice
#

well im trying to turn it off temporarily

#

yea

leaden ice
#

With bc.enabled = false

devout solstice
#

ohhhh

#

yea that worked

#

thanks

formal gulch
#

im having trouble with render textures while trying to use a shader graph material

public class TestRenderTexture : MonoBehaviour
{
  // Start is called before the first frame update
  public Texture2D Icon;
  public Material ShaderGraphReference;
  public RenderTexture rt;
  void Start()
  {
    var mat = new Material(Shader.Find("Unlit/Texture"));
    GetComponent<MeshRenderer>().material = mat;
    rt = new RenderTexture(128, 128, 16, RenderTextureFormat.ARGB32);
    var frame = new Material(ShaderGraphReference);
    frame.SetColor("_Color", Color.red);
    Graphics.Blit(Icon, rt, frame);
    mat.SetTexture("_MainTex", rt);
  }
}``` this just results in a black texture. if i blit just the Icon to the render texture then it will work so its just the material not working. I have set the inputs on the graph to _MainTex and _Color and set each of them accordingly as the main input of that type.
tardy basin
#

Is it not possible to instantiate a prefab inside Task.ContinueWith closure?

#

My prefab does not get instantiated, but I get no error in the console.

#

I have confirmed with logging that that part of the code is reached.

leaden ice
#

Unity doesn't allow things like that in threads other than the main thread

tardy basin
#

okay, thanks, didnt know about that

#

so I guess I should send an event that triggers a callback on the main thread?

#

is this the correct way to do it?

leaden ice
#

whatver you need to do to get it to happen on the main thread ¯_(ツ)_/¯

steep citrus
#

Hi I'm trying to make a sensitivity slider and I'm not quite sure how to assign the slider to change my sensitivity. I'm new with sliders could someone possibly help out?

devout solstice
#

See how i have it passing to the variable button clicked with the => is it possible to have two => without having to do another listener

#

because i want it to set that variable as well as run a method

leaden ice
devout solstice
#

like that?

leaden ice
#

like how I wrote it

devout solstice
#

so like how i did it

#

i think it worked thank you

swift falcon
#

Hmm what would be the best and optimize way for finding equal item in a list?

lean sail
late lion
swift falcon
#

This is a small ScriptableObject and i am getting the items with O(1) and O(n) style. And no i did not see any problem when using LINQ's First() method but i would like to know if there is more optimize way

lean sail
#

This doesnt really tell us anything about the list itself, if this is a small list I wouldnt even worry about it

odd lotus
#

I want to get a specific Collision2D from the scene but the Collision2D field doesn't show up, nor does an array or list of it.

lean sail
#

!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.

late lion
odd lotus
#

no error codes, nothing

#

it just works fine

swift falcon
#

I searched about HashSet but a guy says List would be more accurate for that situtation. I dont know what he meant but it seems the storing strategy thing for each collection is different
Ref: https://stackoverflow.com/a/8110232/20905578

lean sail
odd lotus
#

nevermind i'm just going to use the colliders

swift falcon
odd lotus
#

yes

#

anyways i'm gonna not need help anymore

swift falcon
#

Try putting [SerializeField] at the top of public Collision2D collidable;

#

hahhaha

#

Just a thought dont laugh

lean sail
#

a collision isnt something that just exists in the scene as an object
and if its public, marking it [SerializeField] wont change anything

vocal hearth
#

If I am using an AssetReferenceGameObject to asynchronously instantiate a prefab with Addressables.InstantiateAsync, which returns a GameObject, what is the reason for calling Addressables.ReleaseInstance when done with the instance? I guess the question is why is it not correct to call Destroy on the instance? I would have thought it's then just another object in the scene.

valid minnow
#

is a box collider or raycast more reliable for detecting player jumps

wintry crescent
#

Is there a way to check if a component reference is part of a prefab or part of an actual hierarchy object?

#

I got a weird issue with a outline package, where outlines are generated for all objects with a certain script - even in unopened prefabs

swift falcon
# vocal hearth If I am using an `AssetReferenceGameObject` to asynchronously instantiate a pref...

I think Addressables Team explained like this: We cannot know if an object destroyed. So the reference count would be stay the same or show wrong things. So in Addressables.ReleaseInstance() acts like an Destroy() here.
Or maybe i remember wrong. I will try to find that conversitation now.

Also, there is #📦┃addressables channel. There are more experienced users in that channel maybe looking sometimes

wintry crescent
swift falcon
vocal hearth
valid minnow
#

its for detecting if a player is on the ground

#

2d

wintry crescent
#

I managed to not only make unity throw a missingReferenceException on a line
if (gameObject)
which is supposed to check exactly if it's a valid or non-valid reference
but on top of that, changing that to (this && gameObject) fixes the issue...

shy sonnet
#
using UnityEngine;
using UnityEngine.UI;

public class AmmoScript : MonoBehaviour
{
    public int maxRounds = 10;
    public int maxBulletsPerRound = 6;
    public Text ammoText;

    [HideInInspector]
    public int currentRounds;
    [HideInInspector]
    public int currentBullets;

    private void Start()
    {
        currentRounds = maxRounds;
        currentBullets = maxBulletsPerRound;
        UpdateAmmoText();
    }

    public void UseBullet() // Bullet Usage
    {
        if (currentBullets > 0)
        {
            currentBullets--;
            UpdateAmmoText();
        }
    }

    public void Reload() // Reloading lol
    {
        if (currentRounds > 0 && currentBullets < maxBulletsPerRound)
        {
            int bulletsToReload = Mathf.Min(maxBulletsPerRound - currentBullets, currentRounds);
            currentRounds -= 1;
            currentBullets = maxBulletsPerRound;
            UpdateAmmoText();
        }
    }

    public bool CanShoot()
    {
        return currentRounds > 0;
    }

    public void UpdateAmmoText()
    {
        ammoText.text = "Ammo: " + currentRounds + " / " + currentBullets;
    }
}
``` Can someone help me with this code? For some reason, the bullet count doesn't go to 0 when the round is 0.
somber nacelle
#

look at the conditions you have in the methods that call the UpdateAmmoText method

shy sonnet
#

You talking about public void reload?

#

Nvm got it

elfin tree
#

I have this code currently that calls my constructor:


// Constructor 
public TurnEffect(TurnEffectInfo turnEffectInfo) {
  ...
}

// Calls constructor
public TurnEffect(GameObject effect) : this(effect.GetComponent<TurnEffectInfo>()) {}

I want my constructor to have the following signature:

public TurnEffect(TurnEffectInfo turnEffectInfo, Battleable self) {
  ...
}

How can I change the "Calls constructor" constructor to work with this change? Thanks!

SOLVED

#

turns out i just need to put the type in the first part, like this :

fleet rapids
#

Hello! I've been working on this script for a little while now and just wanted a little feedback on it, like any ways to shorten it or make it cleaner, sorry if there are any typos, I made this on my phone and probably mistyped a few things, but there aren't mistyped on the actual script, thank you if you do end up looking at it

fathom geode
#

I have a list of names with a corresponding output. Some names are variations and point to the same output. Many people may need to add more names to the list over time. What are my options for doing this in a maintainable way?

I looked at enum flags, which seemed nice for the "get every name except this one" or comparing two names case, but needing to assign an int to each one seems fragile. People may add or remove names over time.

General suggestions or places to start?

light rock
#

a dictionary?

fathom geode
#

I'd do a dictionary with duplicates but I need it to be serialized or saved in some capacity

light rock
#

a dictionary is definitely the best solution for this problem. unity does not serialize dictionaries by default, but its possible to write your own serialization for dictionaries

#

in fact, the example on the documentation is literally a dictionary serializer

fathom geode
#

Ty I knew dictionaries weren't serialized by default but didn't realize serializing them was that easy

light rock
#

np 👍

light rock
#

having a bunch of curly braces is the easiest way to make code harder to read, just because of how it spaces out all the important stuff

#

so for example in update i would do if(throwTimer >= 1f && Input.GetMouseButtonDown(0)) ...

#

instead of having them on separate lines

fleet rapids
#

Okay, thank you! I will try to work on the amount/size of the if statements

light rock
#

np 👍

rocky basalt
#

Why is Vector3.Distance of (5, 1, 1) and (1, 1, 1) equal to 4, but distance of (5, 2, 1) and (1, 1, 1) is 4.123106 ?

#

Shouldn't it be 5?

silent quartz
#

its not that simple

rocky basalt
#

clearly

buoyant crane
#

rotate the line in your head over the blue dot, it should be slightly longer than 4 units

rocky basalt
#

Makes sense... i guess i will trust unity then

odd hedge
#

anyone have a problem with editorloop causing lag spikes in profiler?

rocky basalt
#

but isnt there some way to just disregard the editorloop stuff in the profiler

odd hedge
#

as in its causing me problems playing my game in editor to check out stuff ive added

rocky basalt
#

hmm nah i've never had the editor lag my game to that degree.. your pc isn't super old is it

odd hedge
heavy wren
#

could anyone who uses visual studio code recommend a good setup for writing c#? I have the unity roslyn analyzer package and omnisharp installed but omnisharp server is really slow. It takes a few seconds for code completion to kick in.

rigid island
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

heavy wren
ashen yoke
#

vs also handles the "just working" part

#

including debugger

spring creek
#

The debugger is soooo important. That alone makes vs worth it over code

The "just works" part is pretty great too

heavy wren
#

I'll give it a try

rustic furnace
#

Hello all, I am trying to resolve a problem that I am encountering when trying to make the player be able to damage enemies. I made a EnemyStats non monobehavior script so that I can make a list of that in 1. The problem, is that I need to reference the Hp of enemyStats in EnemyBehavior script. It says I cannot do that because enemyStats does not derive from monobehavior. Is there a better way to do this? Am I doing this the wrong way?
ping me please, thanks
1.script that gives all of the enemy prefabs an EnemyBehavior script via a list: https://gdl.space/pifeluwazu.cs
2.The EnemyBehavior Script: https://gdl.space/etiqetoguc.cs
3.The EnemyStats non monobehavior script: https://gdl.space/erodumadiv.cs

ashen yoke
#

create code files through vs, folders included

ashen yoke
#

one object per enemy type

#

reference that SO in the enemy prefab directly

#

that is for edit time, immutable data

#

if you want to implement some sort of runtime abstraction for stats, it needs to be dynamically resolved/found on the enemy

#

the structure would be something like

#
GameObject
  Enemy
    references EnemyStats
  EnemyStats
    references EnemyStatsData, with initial stats values
    contains:
       class EnemyStat - created at runtime from EnemyStatsData

EnemyStatsData : ScriptableObject
  contains initial float/int/bool stat values
  gets converted to List<EnemyStat> at runtime
#

@rustic furnace

enum Stat
{
    Health,
    Armor
}
class EnemyStat
{
    public Stat stat;
    public float value;
}
class EnemyStatsData : ScriptableObject
{
    float health;
    float armor;

    public List<EnemyStat> GetRuntimeStats()
    {
        List<EnemyStat> list = new List<EnemyStat>();
        list.Add(new EnemyStat(Stat.Health, health);
        list.Add(new EnemyStat(Stat.Armor, armor);
    }
}

class EnemyStats : MonoBehaviour
{
    [SerializeField] EnemyStatsData _data;
    Dictionary<Stat, EnemyStat> _stats;
 
    void Awake()
    {
        var list = _data.GetRuntimeStats();
        foreach(var s in list)
           _stats.Add(s.Stat, s);
    }

    public EnemyStat GetStat(Stat stat) => _stats[stat]; 
}
rustic furnace
#

woah, thank you, I will study this

ashen yoke
#

start with scriptable objects

#

that is the key to understanding the pattern

rustic furnace
lethal rivet
#

Is there a way to customize the element names in serialized arrays like this one using editor code or another way. I want to make it an abbreviation of the element it so I can see it at a glance.

ashen yoke
#

unity will use first string in the class as a "name"

lethal rivet
#

I see, is there another way that just overrides the gui draw of the editor. It's a struct the represents a crafting recipe so I'd like it to be lightweight.

ashen yoke
#

a string is a 8byte reference

lethal rivet
#

Ok ok it's just a preference of mine

ashen yoke
#

alternative is property drawer

#

i have no idea if it will work in array

#

as arrays are drawn by unity in a very specific way

rustic furnace
ashen yoke
rustic furnace
#

is this a function?

#

oh okay

lethal rivet
ashen yoke
#

solutions to this vary wildly

#

i really suggest just to use a string

#

one good thing about it is that you only need it in editor

#

so you can if it

rustic furnace
ashen yoke
#
#if UNITY_EDITOR
[SerializeField, HideInInspector] string DEBUG_NAME;
#endif
#

im not sure how serializer will handle it, should be no issues

ashen yoke
#

?

rustic furnace
#

yes

ashen yoke
#

returns the relevant stat object, by the enum value from a dictionary

#

this is in essense how you reference the stats at runtime

#

you grab the relevant runtime stat instance

rustic furnace
#

make sense

ashen yoke
#

im trying

rustic furnace
#

I'm trying to understand how I could implement this

ashen yoke
#

start with a scriptable object

#

make a container for your initial stat values

rustic furnace
#

Alright, I'll do that soon

rustic furnace
ashen yoke
#

read this

light rock
# rocky basalt Makes sense... i guess i will trust unity then

i have a feeling you might be interested in two concepts called "manhattan distance" and "chessboard distance." euclidian distance is the straight line (thats what unity uses in Vector3.Distance) but there are other types of distances that are more useful in different scenarios

rocky basalt
earnest mortar
swift falcon
#

This code makes my game go from 140fps to 40fps on a 4090 and it's drawing a few lines... I assume I'm doing something wrong? lol

#

I mean I could probably make the lines a lot longer instead of drawing squares, that'd make more sense but still... it shouldn't be that expensive?

#

Okay... so rewriting it fixed it, it turns out that it is expensive to do a lot of lines awkwardsweat

#

Does the same thing but costs less than 1fps instead of 100fps lol

swift falcon
#

Turns out my chunks were turned up too high too... meant to be 3x3 but was 9x9 and drawing 44,100 tiles so... guess that's why the lines added up

sacred burrow
#

How do I send a message to a client from a c# server

supple rampart
#

Guys tell me a good question to ask to discord bot

prime sinew
ancient crag
#

Hello,
I want to Instantiate a 3D Model in my UI but it doesn't get shown. I have my camera set to only show the UI layer and after I Instantiate the 3D Model I also set the layer of the GameObject to the UI layer. When I play and Instantiate the 3D Object, in my Scene view the 3D Object gets displayed in the right position but the UI Camera doesn't show anything there.
How do I fix this?

Here in my Method to Instantiate it:

    {
        Transform parent = characterMenuUIParent.transform.transform.Find("Character Model Container");
        for (int i = 0; i < parent.childCount; i++)
        {
            Destroy(parent.GetChild(i).gameObject);
        }
        GameObject characterModel = Instantiate(selectedCharacter.CharacterModel, parent);
        characterModel.transform.SetParent(parent);
        characterModel.layer = LayerMask.NameToLayer("UI");

        characterModel.transform.localPosition = new Vector3(0f, -350f, -45f);
        characterModel.transform.eulerAngles = new Vector3(0f, 180f, 0f);
        characterModel.transform.localScale = new Vector3(370f, 370f, 370f);
    }```
mossy valley
#

My Editor is stuck on this, how do I stop this without having to restart my editor since I didnt save progress 😭

#

Wait nvm it crashed now

mossy valley
#

But it was an editor if I am right

lean sail
#

Ah weird, probably not much you couldve done once it started

tired elk
ancient crag
tired elk
#

you should change the layer for the children objects of your gameobject too

#

I didn't notice before, but the object you're moving into UI layer is only the holder, but it doesn't move the actual mesh (which is its child) in the right layer

#

@ancient crag

ancient crag
#

Oh, thanks. I completely forgot to change the layer of the children

#

Ye, it works now. Thank you

tired elk
#

Great ! 🙂

proper flume
#

new int[] { 0, 1, 2, 0, 2, 3 }
What does this do?

tired elk
#

An array of 6 ints that contains 0, 1, 2, 0, 2 and 3

#

Are you by any chance coding with chatGPT @proper flume ?

tired elk
#

OK

proper flume
#

why

#

is it banned

#

or what

proper flume
#

whats the {} for

#

cant you just do

#

new int [0,1,2,0,2,3]

tired elk
#

It's not, but this part was in your code yesterday and it's weird you don't understand your own code haha

proper flume
#

yeah its a tutorial

#

im trying to understand it

tired elk
#

[] is for the size of your array

proper flume
#

w

#

what

tired elk
#

{} is to initialize the content

proper flume
#

size of array??

#

like how many things it can hold??

tired elk
#

Yes

#

Arrays have a fixed size

proper flume
#

well

prime sinew
proper flume
#

then how am i supposed to pass multiple triangles to mesh.triangles

tired elk
#

but if you do new int[]{0,1,2} you initialize it with 3 elements

mossy valley
#

I have a road that is circular and is divided into three lanes, kinda. So, I need to instantiate different objects on that road which fall under 3 different categories names Gates, Obstacles and Coins. How do I approach this in such a way that the spawning would kind of look organic? Like, I don't want objects spawning on top of each other, I don't want too many obstacles spawning in one area that it makes it impossible to navigate through that area without getting hit etc.

I just need ideas, dww I don't need scripts, I will try to figure it on my own :D

lean sail
tired elk
proper flume
#

well im making squares so 6

#

so if i pass like

#

9 numbers

tired elk
#

Yes, because a square is 2 triangles

proper flume
#

it will create 3 triangles?

tired elk
#

Yep

proper flume
#

ohhhhhh ok

#

is there a way to like

tired elk
#

Doesn't your tutorial explains it ?

proper flume
#

unpack a array and add the values to another array

#

because im accepting it as a parameter

tired elk
#

I could link you an intro to mesh generation if you lack the fundamentals

proper flume
#

for a function

#

and i want to add them to another array

#

oh wait fuck.. i forgot you cant

tired elk
#

Well

proper flume
#

but the other dude

#

somehow does it

tired elk
#

Is it to happend to the array or override ?

proper flume
#

happend

#

append?

tired elk
#

sry, english is not my main language, i can make spelling mistake ^^'

proper flume
#

its ok

#

i just got confused a bit

tired elk
#

Maybe the person from the video make a new array that contains both the old and the one passed as parameter

#

hard to say without seeing the actual tutorial

scarlet viper
#

i have issue with One or more cyclic dependencies detected between assemblies

#

what people do to go around it ?

proper flume
#

I dont know how to make another square

tired elk
#

The numbers ? In the triangles array ?

proper flume
#

yes

#

How do they work

tired elk
#

Well

scarlet viper
#

each number in a triangle array is an index of a vertex in vertices array

proper flume
#

It doesnt show any position its just pure numbers and i dont understand it

tired elk
#

Read this

#

Explaining it would take time, but this should cover the basic of mesh generation

proper flume
#

fuck this is getting complex

tired elk
#

But as Geeko said, numbers in triangles array are indices of vertices contained in the vertices array

tired elk
thin aurora
#

This aint Roblox, this is big people game development

tired elk
#

If you're more of a video person than a reading person, look at this https://www.youtube.com/watch?v=ucuOVL7c5Hw&list=PL5KbKbJ6Gf9-d303Lk8TGKCW-t5JsBdtB

Learn the basics of making a custom 3D object with code in Unity -- also known as a procedural mesh. In this video we do a quick review of what information is required for a simple mesh to take shape.

Support Board to Bits on Patreon:
http://patreon.com/boardtobits
Check out Board To Bits on Facebook: http://www.facebook.com/BoardToBits

▶ Play video
proper flume
#

i think im getting the hang of it

#

How do i check the largest index in a array

tired elk
#

largest ? you mean last ?

proper flume
#

yes

tired elk
#

well, last index should be array.Length - 1

proper flume
#

why -1

#

oh

#

theres a 0 index

tired elk
#

because index starts at 0

lean sail
#

you could also do [^1]

proper flume
#

why cant i do array.length

tired elk
proper flume
#

ah right

#

for some reason im a idiot and changed it to a list

#

actually thats gonna make stuff easier

#

does list.count require a -1 too

tired elk
#

yep

proper flume
#

ok

tired elk
#

You should really look what Wytea sent you

proper flume
#

how to check if a list has 2 the same values

lean sail
tired elk
timid quest
#

hello i need help integrating unity with vscode

lean sail
proper flume
#

one of them

tired elk
lean sail
#

array.length - 1 is the same as ^1

tired elk
lean sail
#

idk maybe im missing some context then, i assumed you were gonna do [array.length - 1] from the beginning

tired elk
#

like if you do triangles = new int[]{0,1,^1} does it store it properly ?

lean sail
#

^1 is an index, so no you cant store it in an int array. I just saw that they wanted to get the last element so like

var triangles = new int[]{0, 1 , 2};
var val = triangles[^1];

would be grab the last. Im unsure what you're referring to now because idk why its being stored

tired elk
#

Well that's why I'm using Length - 1. they're doing mesh generation. They have an array of vertices. to build triangles, you have to store vertices index in a certain order

#

Meaning at some point you'll use the last vertex, which I suppose they wanted to access

proper flume
#

Why is i underlined

quartz folio
#

Hover over it and read

#

and please use full sentences, I see you've been posting quite spammy

proper flume
#

cannot convert from UnityEngine.Vector3 to System.Predicate<UnityEngine>.Vector3

lean sail
quartz folio
proper flume
#

Ok

quartz folio
tired elk
proper flume
lean sail
proper flume
#

Thank you guys i figured it out

tired elk
#

Well played 🙂

proper flume
#

Wait instead of indexes

#

Can i pass to the mesh.triangles array vector3's

tired elk
#

No you can't

proper flume
#

Why do the unity devs need to make this so much more complex

tired elk
#

You'll always have to build triangles from vertices indices

tired elk
#

Actually, in comparison of some other 3D library, it's pretty easy the way you can do it with Unity

proper flume
#

Im getting lots of issues now because when i generate the terrain vertices I will need to add vertices below existing ones in order to achieve a blocky terrain

#

But then they will have messed up indexes

thin aurora
#

For this particular question you also have solutions, like Distinct, Intersect and some other methods

#

Just know that c# comparison is failrly basic so you might want to indicate what exactly must be compares for them to be "the same thing"

wintry crescent
#

Is there anything important at all in EditorUserSettings.asset, or can I safely add it to gitignore?
It KEEPS causing conflicts and while it's 2 clicks to resolve, it's happening so often it's driving me crazy

thin aurora
wintry crescent
#

This file keeps being randomly edited by unity for no reason at all, but unlike OpenXRPackageSettings.asset (which also keeps being changed allll thee timee) which can have important things in it, I'm not sure if EditorUserSettings.asset does

tired elk
#

(was the old way)

wintry crescent
tired elk
#

no no, I posted something that was wrong

#

My bad

unique robin
#

When making a hardcoded (no rigid body) 2D Character controller, what is the least performance heavy way of ensuring the player does not glitch into the floor/ceiling/walls. I've tried ray casts but they are relatively performance heavy and have a few inconsistencies. The glitch into the level is because I am using Fixed Update and in the frame of reaching the ground it moves enough to go properly inside the ground, so setting velocity to 0 when touching the ground does not work.

wintry crescent
#

raycasts are heavy when you go into thousands per frame

#

before that I think you're fine

unique robin
wintry crescent
#

or spherecast or whatever else of that type

unique robin
#

could be solved by changing logic too, but box casts are probably far more reliable

wintry crescent
unique robin
#

problem with that is you can glitch into the ground if jumping on a tile thinner than your character

#

ill try out box colliders, thx

ancient crag
#

Hey,
How do I get the specific UI Element I started dragging with the IBeginDragHandler Interface? It only detects the canvas but not the GameObjects/Transforms inside of the canvas. Is there a way to check if I started dragging a specific GameObject or Transform inside of the canvas?
This is how I have implemented the check right now.
if (eventData.pointerDrag.transform == characterModelParent) isDraggingCharacterModel = true;

fleet furnace
ancient crag
fleet furnace
ancient crag
#

I can't find the graphics component

#

And if you mean the Graphic Raycaster, it doesn't work as well. The only object it hits is the Canvas itself but not its children

fiery hill
#

does the child you want to move have a graphic component, such as an image?

quartz folio
fiery hill
#

you need to have one in order to make it clickable

quartz folio
#

You don't put it on the canvas or something, you put it on the objects you actually want to drag

#

and to get what you're dragging? Well, it's this

ancient crag
fiery hill
#

having a 3d model as a child of a canvas doesnt look so good..

#

maybe you want to think about it, like having a script to move it in world space

#

or maybe having a camera recording it in world space and a RawTexture showing it in the canvas

ancient crag
#

I currently have an extra light just for the 3d model in the canvas. It looks fine that way

fiery hill
#

It may look fine, but it's not recommended to add non-ui elements to canvas

#

it can lead to a lot of problems

ancient crag
#

Okay, thank you. I'll try it the other way then. It's my first time using non ui elements in a ui.

fiery hill
#

A quick guide to using a render texture to show a 3d object in your UI. This is a real-time object you can light, rotate, scale, etc as needed.

In the video I'm using a pirate ship from Synty Studios - Polygon Pirates.

Leave a comment below and let me know what you think and any content you'd love to see in future videos.

Grab yourself some ...

▶ Play video
ancient crag
#

Thank you. I appreciate it.

fiery hill
#

this may help, I'm not really sure what you want to do, but this is one way to show a 3d model inside a canvas

ancient crag
fiery hill
#

can you do a screen recording showing the issue and also showing a little of how your camera is positioned, please?

ancient crag
#

sure

fiery hill
#

ok, i see it
a question for you, does all the children of your model have the same layer as their parent?

#

UICharacterModel

ancient crag
#

Yes

#

They do

tired elk
#

Is there a reason you have 2 character models in your hierarchy ?

ancient crag
#

One is for the UI and one for the player to move in the world. I want the model to be shown and rotated in a menu

fiery hill
#

it looks like something is in the ui causing this visual issue

#

have you deleted the 3d model in the canvas already?

tired elk
#

Did you change the layer from the model that is in the scene (that is supposed to be in game) ? you set it up as UI this morning

ancient crag
fiery hill
#

make sure the other model that you dont want to be shown does not have the same layer as the ui one

tired elk
#

It just looks like one is overlapping with the other

ancient crag
#

They are not on the same layer

tired elk
#

Even children ?

ancient crag
#

No, the one in the RAW Image is on the "UICharacterModel" Layer including children and the other one is on the "Default" Layer including its children

tired elk
#

OK.

#

Did you check your camera clearing settings ? I suppose so, but sometimes we can forget

ancient crag
#

Do you mean the Culling Mask?

tired elk
#

yep

#

The preview doesn't show the other model, so i suppose it's properly setup

ancient crag
#

Yes, it should be set up properly

tired elk
#

But one camera is rendering both characters

ancient crag
#

But how does it even happen? My other Cameras are not showing that layer and the other model is at a completely different location

tired elk
#

Try disabling Character Model Image to see if it's related to the render texture

#

Because it looks like something is going through it

#

And the preview looks fine, so it's shouldn't be a rendering problem on this side

ancient crag
#

When I disable the image it works as inteded. Doesn't get shown anymore and nothing but the blue backgrounf behind

tired elk
#

Now that's weird

ancient crag
#

Maybe it's my Render Texture?

tired elk
#

I don't think so, you're just feeding it what the camera renders

#

And you checked the camera with preview

#

Try disabling the character to see if the render texture display anything else

ancient crag
#

It's not showing anything when the model is disabled

tired elk
#

This behavior is puzzling

#

There's no reason for an arm to appear there

#

Wait a minute. What's your canvas setting ?

ancient crag
#

My Render Mode?

tired elk
#

yep

ancient crag
#

Screen Space - Camera

tired elk
#

Set to main camera I suppose ?

fiery hill
#

Move the Canvas camera away from the character

ancient crag
ancient crag
fiery hill
#

oh, that may be a problem

ancient crag
#

The Raw Image is on the UI Layer though

unique robin
#

Is there a built in function to say how much distance of a raycast intersects with a specific layer. I know the .distance function for 2d raycasts returns the distance till it reaches that specific collision, and that could be implemented to make a function like described, but just checking if there isn't an easier way

leaden ice
late lion
#

Not if it's for modding/cheating.

tired elk
#

since they're both vectors

unique robin
late lion
#

Still, the rules are clear: #📖┃code-of-conduct

DO NOT:
• Directly discuss modding or decompiling.
There isn't an exception for games that allow modding.

tired elk
#

Sry, didn't understand your question that way. What i said won't help you

ancient crag
# ancient crag

It was my render texture. I had to set the Depth Stencil Format to something else

tired elk
#

Sry, I wasn't of much help

late lion
#

The rule applies to the whole server.

tired elk
#

you shouldn't ask anywhere on this discord

late lion
#

Regardless, everyone here is making their own games. Even those who have used Photon, will not have used it in the way you're trying to.

foggy moth
#

Ok, I'd like to learn it from the perspective of a developer.

tired elk
#

But you'd have to consider every scenario...

#

Neverming, I would have suggest RaycastAll to get the amount of item you go through but it won't be enough

buoyant bridge
#

Anyone know of a discord channel existing for developing for Quest 2 in Unity? this latest v56 firmware update has wrecked my app and need help figuring out what the heck they did

tired elk
leaden ice
rustic furnace
scarlet viper
#

should i start from layer 3 or layer 6 when adding my own layers? why is there a hole?

somber nacelle
#

it doesn't matter. but this is also a code channel

unique robin
buoyant bridge
#

ok this is really frustrating... going to just ask here to see if anyone else is seeing this but right now Unity v2023 and Meta v56 firmware is an absolute mess when it comes to the microphone. sounds like a chipmunk having its voice interrupted every tenth of a second. only happens on device. in-editor is fine

#

if anyone has that combo working would greatly appreciate a DM so i can figure out what about my project is making it break

late lion
thick socket
#

Is this how I should be doing game inputs?

if (SystemInfo.deviceType == DeviceType.Handheld)
        {
            // move based on joystick right/left with deadzone
            if (joystick.Horizontal >= 0.3f)
            {
                movement = 1f;
                //Debug.Log("Right");

            }
            else if (joystick.Horizontal <= -0.3f)
            {
                movement = -1f;
                //Debug.Log("Left");

            }
            else
            {
                movement = 0f;
            }
            // if Joystick down, fall through platforms
            if (joystick.Vertical <= -0.4f)
            {
                down = true;
                //Debug.Log("down true");

            }
            else
            {
                down = false;
            }

        }
        else
        {
            movement = Input.GetAxisRaw("Horizontal");
            if (Input.GetKeyDown(KeyCode.W))
                jump = true;
            if (Input.GetKeyUp(KeyCode.W))
                jump = false;
            if (Input.GetKeyDown(KeyCode.S))
            {
                down = true;
                //Debug.Log("Down");
            }
            if (Input.GetKeyUp(KeyCode.S))
                down = false;
        }
real sequoia
#

I have a question regarding how to use android phone sensor data in my game as explained here #📱┃mobile message
I would need your suggestions on how can I solve this issue.

gray mural
#

why I cannot change cursor visibility until I clicked?

private void Hover(bool value)
{
    if (button.interactable)
    {
        isHover = value;
        Cursor.visible = !value;
    }
}
#

is there any way I can simulate cursor click in code?

trim ferry
#

Guys how to i lerp a float value? Just the value not some transform.position or smt like that.. is there somethig like: intensity = new Mathf.Lerp(values) ??

trim ferry
#

thx

gray mural
#

and takes 3 floats as parameters

#

so yes, you do lerp a float value, just float value

trim ferry
#

thanks anyway

gray mural
#

what did you do?

steep saddle
#

I'm working on a project with someone, and we're using github. Yesterday I created a couple new script folders and maybe 5 or 6 new scripts. I pulled his most recent commit, and it deleted all my new scripts and folders. I can't find them anywhere. So, A) any pointers on how I might recover them? And B) best practices so that this sort of thing does not happen again?

leaden ice
#

at worst you would have gotten a merge conflict

pure cliff
pure cliff
leaden ice
#

at best you would have gotten a clean merge

leaden ice
steep saddle
leaden ice
#

or it would just say "can't pull changes due to local changes" or whatever

#

git does not delete stuff randomly

pure cliff
leaden ice
#

well if you force anything you're asking for trouble

steep saddle
#

I'm using the desktop version, and I indicated that I wanted to stash changes. But now I don't see those changes anywhere

leaden ice
#

if you had committed changes and then pulled your teammates changes and they merged and his wiped out yours then your code is still there in the commit history

pure cliff
leaden ice
#

so you stashed them

#

then you just need to unstash them

#

idk how to do it in your desktop version

#

but the command would be git stash pop

steep saddle
#

Unless I clicked "Discard" by mistake, those scripts don't appear to be anywhere.

#

oh wait wait wait

leaden ice
#

are you looking at the right branch?

steep saddle
#

thank gopd

#

found them

leaden ice
#

Yeah it's very hard to lose your work with git

steep saddle
#

I have only ever used github to back up my own work. Still learning the collaboration/multibranch aspect of it

leaden ice
#

If I were you

#

I would go ahead and commit your changes now

#

you don't have to push yet, but at least make a local commit

#

that's a lot more stable than the stash

pure cliff
#

I also heavily recommend both you and your buddy do work on your own seperate branches

#

and then when you have stable working changes, commit and merge your branch into main

#

and when you want to use your buddy's changes, you merge main into your own branch

leaden ice
#

^This is a good idea. It's also a good idea to periodically merge main into your feature branches if there are a lot of changes happening there, otherwise your branch can get kind of "stale".

#

i.e. you may end up with lots of annoying merge conflicts going back to main if you wait too long without merging main into your branch periodically

#

Then again I might be scarred at my day job where our main production branch gets like 100 commits per hour

steep saddle
#

Yeah, we definitely do not have enough discipline or procedure in place. Right now we just have one big project that has all of our scripts, many of which will conceivably be reused in future projects. At what point does it make sense to bundle up your prefabs/scripts into packages?

pure cliff
trim ferry
#

Im trying to do a blinking effect with vignette but its all snappy and it doesnt lerp all the way
idk if this is correct or nah

steep saddle
pure cliff
#

cuz you might blow all that time on it and never actually end up using it

#

also its hard to tell if you need just 1 big package, or if you want it divided up into a couple ones, etc etc

steep saddle
#

Well, current project and future project are sorta one and the same, in this context. This whole thing is going to be the handler for an escape room, and we'll use the same underlying guts for each of our experiences

pure cliff
#

So I wait til I hit that "oh man I really could use that stuff from my last project, we keep re-using it" point, then I package it up cuz now Im 100% sure I need it

steep saddle
#

Gotcha

pure cliff
#

the other thing is you may package it up, but then when you start the next project you actually have a bit of "If I was gonna do it all over, I now know there's a way better way to do it" and then the package you made is useless anyways XD

leaden ice
pure cliff
leaden ice
#

it's not a magic function that goes off and does things over time

#

it's just a math formula that takes in a few numbers, and returns a number

pure cliff
leaden ice
#

or any tween library of your choice

#

but DoTween is the best tweening library for Unity imo

pure cliff
#

does it support IEnumerators?

trim ferry
leaden ice
trim ferry
leaden ice
#

if you pass in 1 you'll get B

#

If you pass in 0 you'll get A

#

pass in .7 you'll get 70% of the way from a to b

trim ferry
pure cliff
# leaden ice you can make a coroutine wait for a tween, yes

Im almost imagining a "lerping" interface for a couple common structs (float, vectors, etc), lets call em Lerpers, that are "bound" to a local member.
And then a Lerp IEnumerator for time, that takes an array of "lerpers" and a time value

leaden ice
unique robin
#

is there a way to select all uses of a variable and change the name on all of them

leaden ice
trim ferry
leaden ice
trim ferry
leaden ice
trim ferry
leaden ice
#

there's nothing to control the speed of

#

Mathf.Lerp(1f, 0.13f, 0f) is equivalent to 1

#

if you want to do things over time you need to write code that is going to change the value a little bit every frame over many frames

#

agaoin Lerp is just a simple math function

#

This is literally the definition of Lerp:

        public static float Lerp(float a, float b, float t)
        {
            return a + (b - a) * Clamp01(t);
        }```
#

just some very simple arithmetic and clamping t to [0, 1]

trim ferry
#

so i cant control the speed?

#

doing this frame by frame would take a long time

leaden ice
#

who said you couldn't

#

it will only take as long as you want it to take

trim ferry
leaden ice
trim ferry
leaden ice
#

if you wrote code that was actually changing things over time, there would be

pure cliff
opal bluff
#

hey i need some help, in a general sense how would you begin to make a code for mashing a button

trim ferry
#

kinda moving the position every frame with code

pure cliff
#

do you mean it will take a long time to run, or do you mean take a long time to physically write the code

pure cliff
leaden ice
#

I recommend DOTween

trim ferry
leaden ice
#

it will make it much easier

trim ferry
#

bruh

leaden ice
#

it will immediately set it to 0.4

#

how many times do I have to say that Lerp is just a simple math formula lol

#

you're not seeming to understand this

trim ferry
pure cliff
#

Hint: you prolly want something roughly like this:

while (vignette isnt done blinking) {
   var timePassed = Time.deltaTime;
   vignette.intensity.value = Mathf.Lerp(....);
   yield return null;
}
#

(further hint: You prolly need to use timePassed variable inside of Mathf.Lerp)

#

yield return null basically just means "WaitForFrames(1)"

trim ferry
#

woops

buoyant crane
leaden ice
#
float duration = 1f; // time in seconds the interpolation will take
float timePassed = 0;
while (timePassed < duration) {
  timePassed += Time.deltaTime;
  float t = timePassed / duration;
  intensity = Mathf.Lerp(startintensity, endintensity, t);
  yield return null;
}```
So see how we're using the elapsed time to create the "t" value?
Lerp is not making anything happen over time. It's happening over time because we are doing a loop with `yield return null;` (which waits one frame) in it
trim ferry
#

stand by please i need to process

charred rock
#

Hello! Quick question: Can someone give me a reference/link to documentation that indicates how I would go about making a package I created be imported into the Packages folder instead of the Assets/root folder?

opal bluff
#

hey can i get help, i'm not understanding how to make logic behind mashing a button script

leaden ice
#

that's kinda my bad I guess

leaden ice
#

it should be vignette.intensity.value = Mathf.Lerp...

trim ferry
#

i think i understand

#

oh nvm

gray mural
#

Is there any way to force enter a game? Cursor class doesn't work until I click on smth inside my game.

private void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}
leaden ice
#

this is so you can still do editor things while the cursor is locked

opal bluff
gray mural
leaden ice
#

Play Focused / Play Unfocused

trim ferry
leaden ice
#

go over it line by line

trim ferry
leaden ice
#

and tell me when you get confused

leaden ice
#

it's just the percentage of the way through the animation we are

#

if duration is 10, and timePassed is 3

#

t will be 0.3

gray mural
leaden ice
#

make sense?

leaden ice
gray mural
trim ferry
leaden ice
#

time passed is representing the actual amount of time that has passed

#

we wouldn't want to change it from that

trim ferry
leaden ice
#

this way it always represents the amount of time that has passed since we started the process

#

which is what we want it to be

trim ferry
#

hm

#

and the duration is the speed or smt?

leaden ice
#

duration is the duration

trim ferry
#

like the length

leaden ice
#

it is the amount of time the animation will take

#

in seconds

trim ferry
#

wait

leaden ice
#

if it's 1 it will take 1 second

#

if it's 10 it will take 10 seconds

rigid island
leaden ice
trim ferry
#

like this?

#

i cant represent too much

leaden ice
#

you're overthinking it

#

I explained what lerp is above

somber nacelle
leaden ice
# trim ferry that is what i said

i didn't really understand "he t float value clamps it based on a fraction of it" but if it means the same as what I said then sure

trim ferry
opal bluff
#

so like if the player mashes under a certain amount of seconds they can get out

trim ferry
#

man

somber nacelle
trim ferry
#

thank you guys

leaden ice
leaden ice
# opal bluff so like if the player mashes under a certain amount of seconds they can get out
float height = 5f;
float sinkSpeed = 1f;
float mashAmount = 0.2f;

void Update() {
  height -= Time.deltaTime * sinkSpeed; // always sinking
  if (Input.GetButtonDown(KeyCode.Space)) {
    height += mashAmount; // mash the key to go up
  }

  if (height <= 0) {
    print("You died!");
    enabled = false;
  }

  if (height >= 5) {
    print("You lived!");
    enabled = false;
  }
}```

Something like this?
opal bluff
#

yea okay i see, yea something like that

thick socket
#

so my code works perfectly...I switch scenes, come back and now it breaks...am I missing something obvious?

#

anytime heroshowing is set it should debug

leaden ice
# thick socket

probably due to some static variables or non serialized state on your scripts?

thick socket
#

it prints the debug here
then the code is ran here....

#

and the heroshowing is now different....
its now Aizen even though no where in code it should change and even the debug shows it doesn't change

leaden ice
#

yes, any variable that isn't serialized

#

it will go away on a domain reload, but if you don't have domain reloads enabled for entering playmode it can stay unexpectedly

#

it's also unclear what the scope of this heroShowing variable is

thick socket
#

just a private inside the script

leaden ice
#

and what's the lifecycle of the script

#

is it a DDOL singleton?

thick socket
#

no

leaden ice
#

but where is this HeroInfo from the button coming from?

thick socket
#

hmmmm

#

this is inside of start

#
 GameManager.instance.playerInventory.ResourceAmtChanged += () => AddMatsToInventory();
        GameManager.instance.playerInventory.HeroStatsChanged += () => AddMatsToInventory();
        GameManager.instance.playerInventory.HeroStatsChanged += () => UpdateHeroInfos();
#

I probably needed to remove these when script was destroyed first time?

#

or when script is destroyed should these be destroyed also?

thick socket
leaden ice
#

is GameManager a DDOL singleton?

thick socket
#

yeah

leaden ice
#

yeah... this isn't going to fly

#

especially since you're using those anonymous lambdas - you won't be able to unsibscribe them properly

#

rewrite like this:
GameManager.instance.playerInventory.ResourceAmtChanged += AddMatsToInventory;

#

then unsub in OnDestroy:
GameManager.instance.playerInventory.ResourceAmtChanged -= AddMatsToInventory;

#

I have no idea if this is your current issue

thick socket
leaden ice
#

but this is definitely an issue

leaden ice
thick socket
leaden ice
#

yeah it might not be related

#

but definitely something you should do anyway

thick socket
#

appreciate the fix reguardless 😄

#

everything works correctly first time, I then go into another scene, come back and then the issues happen

#

welp

#

I'll try again but unsubscribing those fixed it

#

yeah that fixed it thanks! not entirely sure how that caused the issue but it works now 😄

#

how I've just got to figure out why if I doubleclick super fast it breaks something else when clicking regular speed it works fine when popping up first item lol

#

oh the fun of debugging

swift falcon
rigid island
#

eg animation for shooting root pos /rotation not matching the one for idle or w/e

thick socket
#
BackgroundButton.clicked += () => StartCoroutine(buttonClicked());
pure cliff
thick socket
pure cliff
#

so in your case

private void OnClicked() => StartCoroutine(OnClickedRoutine());
#

and then you can -= / += OnClicked

swift falcon
thick socket
pure cliff
#

Its just typically safer to always have the "top" level of your event subscriber method be an actual concrete method, not an anonymous lambda

#

if you need to unsubscribe at least. I try and avoid ever having event subscribers that can be destroyed/disposed of in the first place, then you dont even need to worry about it

swift falcon
leaden ice
gray mural
#

Is if possible to do this kind of shadow in unity?

#

there is a shadow around this panel

thick socket
#
GameManager.instance.playerInventory.HeroStatsChanged += () => UpdateHeroInfos();```
#

so when it was this before....the right side script was destroyed before the left side so I need to unsub it

thick socket
#

would just need a list of the params from the method to pass back into the unsub method then 🙂

devout solstice
#

so theres a scrollbar component right, the value is in decimals, i need it in whole numbers based on what step its on, so if its on step 1 the value is one etc how could i do that

#

i just realized theres something called a slider

#

that seems to fit what i need better

#

yup that works way better

thick socket
#

awesome thanks!

gray mural
shell scarab
#

Is there ever a reason to use System.Single instead of float? Like, ever in any case?

somber nacelle
#

they are literally the same thing

#

float is just an alias for System.Single

shell scarab
#

yes i know but I'm just wondering because I see some things in the unity documentation and c# documentation say they return System.Single not foat.

somber nacelle
#

i mean, if you know that they are literally the same exact thing then why are you confused?
float is System.Single

#

just like string is System.String and int is System.Int32

shell scarab
#

yes but I'm wondering why they say System.Single and not float, when in other cases they say float

somber nacelle
#

because they made that arbitrary decision

#

it makes literally no difference

shell scarab
#

it just seems like an odd choice and I was wondering why they would do that, maybe there's an actual reason I'm not aware of, etc.

somber nacelle
leaden ice
#

float is just a convenient alias for System.Single that the C# language respects to improve the experience of developers who transitioned to and from other programming languages, since float is used in many, many languages

#

e.g. if you do Debug.Log(5.5f.GetType().Name) you will see System.Single

shell scarab
#

thank you for the explenation. The automatic tool thing makes sense.

earnest gazelle
#

Why there is not PreUpdate like LateUpdate. It is useful really in some situations

#

I hate to use execution order

lean sail
obtuse sonnet
#

I'm trying to write a Unity playmode test, but I need it to run in different scene (not the autogenerated one). How can I do that? Switching to the scene directly leaves my test pending and throws exception somewhere in OnPlayModeStateChanged

#

(there is an error when assigning the workplace because there is no workplace in the scene)

lean sail
#

all i can see is that your coroutine never yields in this code

somber nacelle
#

I want to load entries as Object and then cast to specific type in a library script
why

primal wind
#

I would honestly make a custom class holding both the object and its type but i'm no professional so there might be better ways

somber nacelle
#

yeah a generic class sounds better than just dumping everything into a single list as Object

#

i mean, yeah. that's called downcasting. but why should you have to do that, when you can just, you know, not

#

you're basically trying to circumvent c#'s type safety by storing everything in a big ol list regardless of whether they should be together or not.

#

what happened to "I want to keep this code as clean and straightforward as possible"?

#

then why do you need to store them in a List<Object>

#

fine, then have fun with your convoluted code where you have to type check and cast constantly 🤷‍♂️
i won't help you try to find a cleaner and better solution if you're just going to be a dick about it

#

and your simple question is very likely a bad way to do whatever the fuck it is you're attempting. of course you won't actually say what you are attempting because you are so adamant on going through with your bad solution so a proper solution cannot be suggested

sleek heath
#

this channel is becoming steamy hot very quickly

pure cliff
#

how many distinct types do you actually need to load

#

only 5? Then I would make a wrapper class for each type instead of doing casting, as "is a" checks are fairly costly and perform very poorly, pretty much always a big code smell, very difficult to maintain, etc etc

#

What are you doing with these asset objects after you cast them?

#

So do you have some kind of switch statement on Type happening somewhere, and then you do a cast to its concrete type inside the different options

#

And you have distinct unique logic for each of the 5 types, largely speaking?

#

what method are you using to load them?

#

Like are you just calling Resource(s).Load()?

#

I see.

LoadAll() has a hard typed via generic overload, use that

#

What do you wanna do with the _loaded in the end? Like you just got 5 distinct dictionaries you wanna fill up with their respective assets?

#

right but just to confirm, do you wanna end up with effectively 5 seperate dictionaries, 1 per type?

#

Like
Library.Sprites, Library.Materials etc?

#

Perfect!

Use Generics.

somber nacelle
#

but Pixxel, they just wanted to cast and it was a simple question and they just wanted an answer for just their simple question. they know what they are trying to do and their approach

pure cliff
#
public class AssetLibrary<T> {
    public AssetLibrary(string folder) {
        _folder = folder;
    }
    
    private string _folder;
    private Dictionary<Id, T> _assets { get;} = new();
    protected async Task NextIndexAsync(Index index) {
        ...
        var _loaded = Resources.LoadAll<T>(folder).ToList();
        foreach (var entry in _loaded) {
             _assets.Add(...);
        }
    }
}

Something vaguely like that like that

#

because its extremely expensive and will be very difficult to maintain

#

Its a lot like if you took a box of spaghetti pasta, ground it up into powder, hydrated that powder, formed it back into spaghetti noodles, and then cooked those.

Like yeah sure I guess it works... but why didnt you just cook the spaghetti you had in step 1?

pure cliff
#

I dunno it would just do whatever you need it to do, but in a type safe way

#

And then yeah your "parent" object would just have 5 instances of AssetLibrary which is what you wanna end up with anywho

#

I just copied your method's name, you would make it do whatever it is you are hoping it will do :p

#

you cast a foo to a Bar simply via (Bar)someFoo

#

what error are you getting?

#

Texture2D contains a ref to a sprite, but is not the sprite itself, prolly what caused that

#

My motto is "do it right, or you'll just have to do it again"

pure cliff
#

LoadAll has a hard typed version

#

You also dont need string type anymore

sterile shell
#

So I finished my player movement script and I was moving

#

But then I finish my MouseLook Script

#

and I can move mouse but not player

mellow barn
#

Hey guys! I'm using the Unity Terrain object and while my character interacts fine with level ground, if I attempt to make hills of any kind my character collides with them and proceeds to clip under the level. Is there any way to fix this?

deft coyote
#

I'm trying to use a non-MonoBehavior class, and it's setting itself to null every time that the code recompiles during runtime.
Is this an error I'm making, a workflow that Unity doesn't support, or a bug that I somehow can't find on google?

This behavior can be recreated with the following steps:

  • create an empty 3d project in 2022.3.1f1
  • delete all objects in scene
  • create a new empty object
  • attach the script, Foo.cs to the empty object
using UnityEngine;

public class Foo : MonoBehaviour
{
    private Bar _bar;

    void Start() { _bar = new Bar(); }

    void Update() { Debug.Log(_bar); }
}
public class Bar
{
    public Bar() { }
}
  • press play in Unity editor
  • console should be logging Bar every update, showing that the private instance variable _bar to hold an instance of the object Foo
  • edit Foo.cs by adding white space to the end of a line, and save the file to force a recompile
  • console should now be logging Null every update, showing that recompiling has set the private instance variable _bar to Null

This has been baffling me for months before I thought to ask for help here, so thanks in advance for providing some form of closure to this!

lean sail
#

i dont fully know why its even an option honestly

leaden ice
#

Since Bar is not [Serializable] nor is the field serialized, it will not be preserved

#

that feature sucks though

#

but it will be "fixed" if you do this:

public class Foo : MonoBehaviour
{
    [SerializeField]
    private Bar _bar;

    void Start() { _bar = new Bar(); }

    void Update() { Debug.Log(_bar); }
}

[Serializable]
public class Bar
{
    public Bar() { }
}```
#

(also Start will become redundant since Unity serialization doesn't allow nulls anyway)

ashen yoke
#

completely confused why do you assume Bar should be null on recompile

#

it will be assigned in Start at runtime

deft coyote
#

@lean sail @leaden ice Thanks! That's really good to know! I thought I was doing something really stupid that was creating the error for months until I spent today minimizing down to the example project above in an attempt to solve it. It's nice to know that this is mostly just something that everybody lives with, and even better to know that there is a way around it if I feel I really need it! Although serializing all of those fields just to support recompiling during development seems like more effort than its worth in a larger project.

deft coyote
ashen yoke
#

lets just take this and break it down

#
public class Foo : MonoBehaviour
{
    private Bar _bar;
    void Start() { _bar = new Bar(); }
}
#

_bar will be null in editor, guaranteed

#

after your run it, if the scene reload is disabled, it may retain the value of the _bar from Start in editor

#

at runtime no matter what you did in editor the Start will be called and _bar will not be null

leaden ice
ashen yoke
#

yep, there is no sane way to retain the ability to hot reload

#

maybe you can have some isolated environment specifically for developing very barebones scripts that will support it

deft coyote
ashen yoke
#

so what i missed was that you were recompiling while the game was running?

#

makes sense, since Start will not be called after compilation, but the whole domain will be dropped

#

meaning any non serialized values will be lost

lime niche
#

I'm having a dillemma, should I learn Cpp or C#?

deft coyote
buoyant crane
ashen yoke
lime niche
#

Cpp is highly regarded iirc.

ashen yoke
#

this is offtopic, but nothing stops you from learning both

#

with preference given to c++

buoyant crane
#

Whatever you end up focusing on first depends on your goals

ashen yoke
#

as a lower level language with direct memory management you will generally understand computers and programming better, with c# while being similar in syntax and structure, it is a language that runs on a virtual machine, that takes memory management and many other things out of your control

lime niche
#

Yeah I can learn both but it is better to give my full attention to one thing so I can master that one thing.

lime niche
#

Yeah.

ashen yoke
#

yes there are jobs for any language, however those jobs will rarely include engines, servers

lime niche
#

Yeah, I am really fascinated by the engines bit.

#

and servers.

#

Soo probably CPP right?

rigid island
#

you really want to make your life decisions based random people on internet ? lol

lime niche
#

Idfk. 😭

#

I'll do my research.

rigid island
#

learn whats more comfortable for your learning

lean sail
# lime niche I'll do my research.

you probably wont have a great time learning c++ if you severely struggle with c#. And tbh most jobs wont even consider you for these roles if you dont have a degree.

#

so I wouldnt consider learning a language in terms of which job itll get you

lime niche
rigid island
#

i think jobs care more about good logic being written then the syntax itself or what specific one you know. Ofc if its a job geared towards a certain language then it matters, You can prove you can write good easy to extend code, syntax is kinda irrelevant

lime niche
#

Ah

rigid island
#

AI can write syntax, but their logic/systems are frail or make no sense

#

that's where human comes in

#

you write code for purpose of getting shit done(solving problems?), if you get it done well the language of code is really irrelevant I think

lime niche
#

Ahh okay.

#

Im so fucking torn.

rigid island
#

just a suggestion though, you should really think hard on what you think is best for you

lime niche
#

Yeah.

#

Thanks!

pure cliff
# lime niche Yeah I do want to use Unity but I also want to prepare for jobs in the future.

My recommendation is, if you wanna get into it as a career, first talk to local recruiters in your area and find out what your specific area prefers.

Typically a given city/local area usually over time adopts a particular tech stack and it becomes like, 80% of the jobs, because if company A and B use <tech stack> and then company C starts up, they often have 1-2 folks who used to work at A and B so they also wanna use the same stack, and soon enough everyone is mostly using the same stuff.

The vast majority of tech stacks tend to be one of 2 (there's others but I see them way way less often):

  1. Asp.Net backend, microsoft stack of Azure, MSSQL, etc.

  2. Node backend with express and mongodb, often running on AWS but can run on Azure too

The front end is pretty much always 1 of React, Angular, or Vue, and once you learn one of em it gets very easy to pick up the other 2.

So basically find out which of those is the popular one in your area, and learn that one

lime niche
#

Ahh.

#

There are not many software engineering or IT game dev listings in my area weirdly.

warm geyser
#

Somewhat of a UI coding issue I believe:
I need it so that when I click the transparent part of a button, it doesn't register as a press (or the raycast just ignores it).
alphaHitTestMinimumThreshold will work for the image if it has alpha built in. However I want to use "Image Type Filled" with a radial fill method and this method doesn't seem to work for that, any ideas?

#

Thanks

safe ore
#

I really didn't want to have to ask for help with this but I really can't figure it out. can someone help me reverse the bulk buy and do it in the bulk sell?

public void CalculateBulkBuyPrice()
    {
        fakeBulkBuyPrice = 0f;
        int fakeBuildingsBuy = upgradesBought;
        float currentUpgradeCost = upgradeBaseCost;

        for (int i = 0; i < bulkAmount; i++)
        {
            fakeBulkBuyPrice += currentUpgradeCost * Mathf.Pow(1.15f, fakeBuildingsBuy);
            fakeBuildingsBuy++;
        }
        fakeBulkBuyPrice = Mathf.Round(fakeBulkBuyPrice);
        upgradeBulkCost = fakeBulkBuyPrice;
    }

    public void CalculateBulkSellPrice()
    {
        fakeBulkSellPrice = 0f;
        for (int i = 0; i < sellCorrect; i++)
        {
            fakeBulkSellPrice += upgradePastCost / 1.15f;
            // upgradePastCost /= 1.20f;
        }
        fakeBulkSellPrice = Mathf.Round(fakeBulkSellPrice);
        upgradePastCost = fakeBulkSellPrice;
    }
lean sail
safe ore
#

which one bulk buy?

lean sail
#

yes, like what the goal is. it looks like each item you buy gets more expensive but a lot of these variables are also not in scope so its kinda hard to run through it in my head

safe ore
#

so yeah, its basically to buy a building, it will loop for how many bulkamount is = to, give you the final price of how many buildings you want to buy and how much it will cost correctly. and then in another function use the outcome to do the buy part. but reversing the process has been a bigger pain than i thought it would have been. say i have a building worth 15, next is worth 17, then 20, then 23, then 26 etc
but i want to buy 10 so at a base cost of 15, it will cost me 305 to afford 10.
I want to reverse this process so lets say I have 10 buildings and i want to sell all of them. it will then sell for 305 right? I'm sorry I have just finished my nightshift job and really tired so please excuse me for being a bit overly confused

#

starting to feel like i had solved it before and just ignored it thinking it was wrong and thats gonna annoy me

#

nah I'm still very much confused about it

#

do note I'm not the best at maths

lean sail
safe ore
#

Alright thanks!

#

the strange thing is the math works perfectly if i sell 1 at a time

#

but when i do 10