#archived-code-general

1 messages Β· Page 455 of 1

dire pelican
#

!code

tawny elkBOT
fresh bay
#

ty for telling me about octo trees never new what they where before you mention it.

fiery steeple
#

Done but now I'm clueless on what to do because nothing even appears in my screen 😬 Also it puts the Canva (Environment) again when I'm inside the prefab scene πŸ€”

naive swallow
rigid island
fiery steeple
fiery steeple
#

I'm totally lost πŸ₯²

fiery steeple
#

Yeah i didn't put "Tile" inside the Canvas as you said I don't need Canvas anymore

rigid island
rigid island
#

remove the rect transform component then by deleting it

#

on the prefab view

rigid island
fiery steeple
round violet
#

im trying to return a delegate from my function but i get The assignment target must be an assignable variable, property, or indexer

here is my code


// Some class
MessageUI.CreateNewAndWaitForUser("") += () => {};

// The MessageUI script
 public delegate void OnClicked();
public OnClicked onClicked;

public static OnClicked CreateNewAndWaitForUser(string message)
{
   var GM = GameManager.Get();
   GameObject go = Instantiate(GM.messageUIPrefab.gameObject);
   MessageUI messageScript = go.GetComponent<MessageUI>();
   messageScript.SetText(message);
   return messageScript.onClicked;
}

rigid island
#

what is goin on += () =>

chilly surge
#

foo += () => {} is actually foo = foo + () => {}.

#

You cannot reassign an expression, like it wouldn't make sense to do Random.Range(0, 10) += 1.

#

I would personally rewrite that into MessageUI.CreateNewAndWaitForUser("", () => {}) (or async/await)

round violet
rigid island
#

cant you also do

MessageUI.CreateNewAndWaitForUser("") += () =>
{
    Debug.Log("User clicked!");
};```
chilly surge
#

+= is a compound assignment.

#

You cannot perform assignment on an expression like Random.Range(0, 10) = 5.

round violet
#

yeah ill simply do public static void CreateNewAndWaitForUser(string message, OnClicked clicked)

chilly surge
#

As a side note, you can also skip the delegate type altogether and just use Action (there are also Action<T>, Action<T0, T1>, as well as the equivalent Func<>s).

#

Some people do prefer an explicit delegate type though to make things clear.

agile talon
#

how do i improve this code

young yacht
leaden ice
#

Actually, start by configuring your !ide

tawny elkBOT
mellow sigil
#

Excluding the script template around them, both lines are nonsensical. You'll have to follow a course instead of just throwing random things in. See !learn πŸ‘‡ for example

tawny elkBOT
#

:teacher: Unity Learn β†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

sharp parcel
#

What do i actually need to learn of C# before i can start making something in unity

#

i'd just watch all of the tutorials i see but i dont actually know what i need to learn

leaden ice
#

There's no hard requirements. The basics of classes, structs, variables, functions, delegates would be good.

sharp parcel
#

I had zero C# coding up until 5 hours ago and all i know how to do is make the console say stuff and make variables and functions πŸ‘

sharp parcel
#

up until now i've just been watching a free C# tutorial course from codemonkey

mellow sigil
sharp parcel
#

Oh thanks

sharp parcel
#

Im just gonna open every tutorial pinned there

mellow sigil
#

Are you going to do them all at the same time?

sharp parcel
#

but ill most likely do all of them tonight/today

#

idk what to call it cause its 4 am

sharp parcel
mellow sigil
#

Start with one and then see where you're at

young yacht
#

then just think of a feature you wanna make and do it

#

you'll learn more as you go

sharp parcel
#

I know what classes are for but idk what they are, i do know what variables and functions are from prior coding experience with GML though

#

So for now ill just follow the unity learn one

#

thanks for the help

hardy pasture
#

What's the recommended way to handle player settings? PlayerPrefs are not quite it: it can only save and load int, float and string. Like I want to save and load vector2 right now and then in the future story mode progress and a bunch of things, doing it with only 3 types and doing it manually is going to be tiresome and error-prone.
Any advice on getting adequate serialization?

leaden ice
#

Long story short is use whatever serializer you want/are comfortable with and save the progress to a file.

#

JSON is common, as are MeasagePack and Protobuf, as well as custom binary formats.

last quarry
hardy pasture
last quarry
#

Nope

leaden ice
#

The actual "serialize this and write to a file" part is the simplest part

#

Just call your serializer and use standard C# File IO to read and write the files

hardy pasture
# leaden ice Yes I just mentioned them. The thing is there's no "out of the box" for describi...

The thing is there's no "out of the box" for describing what "MyObject" is in your example because every game has a specific bespoke set of data that needs to be saved
C# has reflection, you just go over all properties maybe marked with an attribute and you serialize them. If those properties are simple, you just serialize them. If they're complex: struct or class, you again go property by property. And you do it until you're done. And you dump it as json, yaml, whatever, then save to a file. Then you load it similarly. I've written this in C++, it's not that hard to do, it just takes time and then more time to make it platform-agnostic for Unity.

last quarry
#

No need

leaden ice
#

Use one

#

That's not the hard part of the save system

#

The real work is designing the data model that gets saved and there's nothing automatic about that because every game is unique in terms of what data needs to be saved

last quarry
#

Here's an example savegame system that works like mine:

public interface ISaveData { }

public class SaveGameManager
{
  private static Dictionary<long, ISaveData> _saveData;
  
  public static void AddSaveData(long id, ISaveData data);

  public static ISaveData GetSaveData(long id);
}

This just serializes the dictionary (plus a version number)

#

The one thing you want to do, at least for JSON, is make sure ONLY types inheriting ISaveData can be deserialized

young yacht
#
{
    "dateTime": "06/06/2025 09:24:47",
    "timePlayed": 0.0,
    "isTutorialFinished": true,
    "hasDied": false,
    "moveSpeed": 12,
    "playerHP": 15,
    "playerHPMaxValue": 20,
    "criticalChance": 4,
    "armor": 4,
    "pickupRange": 5,
    "healthRegen": 6,
    "harvesting": 2,
    "knockback": 1,
    "xpAmount": 0,
    "tunaCanAmount": 0,
    "silverCoinsAmount": 15,
    "bossCoinsAmount": 6,
    "scrapMetalAmount": 15,
    "weaponIndex": 0,
    "drinkIndex": 1,
    "drinkCharges": 5,
    "drinksUnlocked": [
        0,
        2,
        5
    ],
    "hasChosenPreset": false,
    "currentMiniBoxIndex": 0,
    "currentCity": 0
}

there's no such thing as a "MyObject" but you can have a list, save the index into JSON and when game loads you search through that list to match that index

so far works well for me

night harness
#

i mean there can be a myobject but just not out of the box (hence needing to design it)

last quarry
#

Yep

hardy pasture
# leaden ice I don't really see what you're asking here. Yes, serializers exist

How do I address different platforms then? Like I feel like it's going to be a big goose chase of supporting different platforms even if I use an already existing serializer. For example, on PC it's going to be a file maybe in Appdata, but then on the web it's in local storage. Am I going to have to address those differences myself?

last quarry
#

Unity has a thing for that

leaden ice
#

That handles it

young yacht
#

depending on your render pipeline of course

agile talon
night harness
leaden ice
agile talon
#

why

young yacht
last quarry
leaden ice
# agile talon why

Because you need a real IDE especially since you clearly don't know how to code and need all the help you can get

young yacht
#

only PC and consoles

night harness
#

(the switch is a console)

young yacht
#

console i mean by PS5 and Xbox

#

i knew you'd say that

#

smartass

night harness
#

i read the words you write

hardy pasture
night harness
#

(ue5 can build to switch btw)

last quarry
young yacht
last quarry
#

Not because of the directory but because of cloud saves πŸ˜„

night harness
#

save systems suck the more you care about them, like many things in life πŸ˜„

young yacht
#

with their API

#

do you just pass your JSON?

night harness
#

file

thick terrace
leaden ice
#

All you do is write your save file to disk. Steam handles the rest

last quarry
#

I believe you pass the files. But the nightmare part is all the edge cases

young yacht
#

ah thats nice

last quarry
#

Xbox Live requires you to sync WHILE THE GAME RUNS

#

So you need to handle all the edge cases yourself

young yacht
#

i keep thinking about it, its already hard enough to make the game

last quarry
#

User might press the cancel button

young yacht
#

then integrating steam API to it

last quarry
#

Internet may be down. There may be conflicts

young yacht
#

so much work man

night harness
#

thats why you make games without saving πŸ˜„

thick terrace
#

if you use a password system, you don't even need to spend the money to put a battery on the cartridge!

agile talon
young yacht
#

he's not roasting you

#

he's polishing you

mellow sigil
#

The code you showed is that bad

latent latch
#

Honestly I love to whip out a lightweight IDE when I can't be bothered as I've coded for years before IDEs started handholding devs, but there's a lot of reasons you do want something more custom to Unity because it takes advantage of a lot of reflection bullcrap which will leave you scratching your head

last quarry
#

I've also coded "for years before IDEs started handholding devs", which is exactly why I appreciate the computer highlighting mistakes before they happen.

latent latch
#

I mean I guess JS devs are used to the pain so they may be better off rofl

thick terrace
#

well typescript is massive for a reason too

mellow sigil
#

Also most code editors have a JS integration with intellisense available. Only a handful have a Unity integration

last quarry
sacred sinew
#

I have a script that generates a triangle for a collider. I need it to be able to create an isoceles triangle, whith control over the lenght of the median and the BAC angle. It then rotates it around A. But the BAC angle is fifferent each time. Can someone explain why ? Here's my code : https://paste.myst.rs/ek89nlm2

granite crane
#

If you ever need your code critiqued, just ask copilot! Careful though, you might receive..a few..roast back..(Includes AI Content)

night harness
#

Just a heads up that we have absolutely zero interest in this!

thick terrace
#

if my computer talked to me like this i would be submitting my next merge request handwritten on lined paper

granite crane
#

It really had to put the cherry on top at the end lol

shadow wagon
#

you can really tell that they fed it all the reddit data to be trained on

#

ever since then, its talks in such an incredibly annoying "look at me im so quirky and wacky" way, just like redditors do when they think its funny for 20 people in a row to start making the same joke over and over again

#

it never used to say crap like "held together with duct tape and hope...spaghetti monster"

#

its so embarrassing

mellow sigil
night harness
#

is this why the server gets an influx of people using this

shadow wagon
#

influx of people doing what?

night harness
#

Using Invoke & InvokeRepeating

sacred sinew
shadow wagon
#

"microwaving pizza with a hair dryer" did microsoft/openai really test it (their professional ai coding tool), see it could write things like this and say "thats good to roll out for our customers to use"

shadow wagon
night harness
night harness
granite crane
#

With that, is it recommended to only use InvokeRepeating for something that should run no matter what? But use a method for everything else that only runs on certain conditions? Copilot probably mentioned the invokerepeating part because I was previosly cooling the laser by just calling the cooldownlaser method every second. I've now added an if statement in the update method that only calls the cooldownlaser method when needed. Not sure which way is more effiecient though since before the method ran every second but now the if statement is being checked once per face.

Maybe invokeRepeating is better for this case?

night harness
#

there's nothing wrong with using a timer like you are doing

#

you asked AI to find problems and it gave you problems, doesn't have to give you real ones

fervent moth
#

I want to create a road system similar to the one in Manor Lords, always wanted to make a city builder without grids. I understand that bezier curves or similar alternatives are the method to achieve what they did, where the user is able to simply press along a path and the road(s) curve and align accordingly.

I would however appreciate a tutorial on this, and all I can find are tutorials of people doing similar things in the editor, not in-game.

You guys have any ideas?

vestal arch
granite crane
#

So running an invokerepeating would probably be the most effiencient way of cooling the laser since that'll be less call to things?

thick terrace
night harness
vestal arch
fervent moth
shadow wagon
#

I think providing the AI with code that functions well, but is badly written, and asking it to "fix/improve the code" the AI could interpret that as
"refactor, dont alter anything, but shorten and make it more clear"
or
"the user will likely want this code to be transformed into something more advanced, improving it to make it fancier"

Ive noticed it will do both of these, and its a coin flip. the solution is asking a better prompt so it doesnt risk doing stupid stuff to it that you clearly wouldnt ever want

vestal arch
#

the solution is not using AI at all tbh

thick terrace
night harness
fervent moth
shadow wagon
#

yeah, the fact that no matter what you ask it, will still lead to it misunderstanding what you really mean and what you really want, is a gigantic issue

night harness
#

(though if you can tell its bullshit you likely don't need it)

vestal arch
#

also the part that it takes your entire code and gives you a new block of code - you can't specify what to change and not to change reliably

shadow wagon
#

but new programmers dont have any way of understanding this, its something that you only better understand if you come from a time before AI tools existed. I cant think what its like as a new programmer and you have access to tools like this

vestal arch
#

it doesn't make changes, it remakes it based on the input

granite crane
#

I like to use it to help explain certain parts of code. It's decent on the beginner stuff

shadow wagon
#

a lot of simple stuff, things that tens of thousands of people will have done, AI is pretty good at replicating their code. But thats just how probability works with genai

night harness
#

you dont know if its decent

shadow wagon
#

gpt likely wont get a basic C# HelloWorld file wrong

night harness
shadow wagon
#

but "my inventory isnt working right and the UI is buggy, please fix" is never going to be right

vestal arch
fervent moth
shadow wagon
#

hey, at least now GPT is getting worse and its overly cheerful and informal crap is seeping into code, its making it easier than ever to spot!
greatest thing is that they dont stop it from putting emojis into comments

night harness
violet nymph
# granite crane

AI is pretty bad at that, the critiques it gave you most likely won't even work to be 100% honest here, I don't know how your code works, but that's bad advice from AI right there

granite crane
vestal arch
#

inb4 said articles are also from chatbots

night harness
naive swallow
shadow wagon
#

maybe I'm mean for doing it, but anytime I see code that I'm 95% confident is AI, especially if theres an emoji in a comment
I like to question that person who posted it, ask them a leading question about why/how they thought to write that specific thing

that way they either shy away from giving a straight answer, try and dance around the question
other times they admit it was ai written

safe flame
#

I remember receiving python code when i was asking for a C++ concept summarized

shadow wagon
#

after they admit it, my job is complete πŸ˜†

night harness
#

I saw that one thing (think it was on john oliver?) where a pdf was formatted incorrectly and had a paragraph on the left page and a paragraph on the right page format in a way where the string reads both as one big paragraph. AI read that and made up a fake science term by combining the word from the end of one paragraph with the word at the start of the other and as a result it ended up in a bunch of science studies.

It's funny and horrifying how shoddy processing that much randomly formatted data is

vestal arch
# granite crane

huh i didn't notice this at first lmao
this is kinda funny

really captures the pinnacle of what AI is
sometimes it's right but it'll fit weird BS in all the same

  • input smoothing is often an issue rather than the desired effect
  • error handling isn't really needed, can just fail fast, doesn't need to be fail safe
    and of course the weird InvokeRepeating recommendation
    "commented out code" as a code review issue is wild πŸ˜‚
safe flame
#

though this is leading into the AI Discussion thread topic now

night harness
vestal arch
#

gotta search for the thread and copy link

#

no clue what channel that thread is in though

round violet
#

to avoid allocating a new TransformAccessArray each frame, im making one "big" TransformAccessArray which hols some null entries, and fill it when i got entities to move.
when adding null entries im getting this warning: Adding null Transform to TransformAccessArray will result in degraded performance.

#

what does it mean by that ? inside my job im returning early if the transform at the given index is null

vestal arch
#

probably that it's still gonna have to process the null transform?

vestal arch
leaden ice
#

and only add the ones you need

round violet
leaden ice
#

Like Chris said, if you look at the API it's more of a list

#

it has a capacity for exactly this reason

#

there's no reason to add nulls

vestal arch
round violet
leaden ice
#

create it once

vestal arch
#

you don't need to though?

leaden ice
#

with the right capacity

#

and don't create it again

round violet
#

making a new TransformAccessArray

round violet
leaden ice
#

you don't need to make a new one

#

ever

round violet
#

thats why im making one at the maximum capacity

leaden ice
#

That's fine - you still don't need to add nulls

vestal arch
#

ok, so just, don't add nulls

round violet
#

then just setting the entries as the entities count varies

round violet
vestal arch
#

nothing

round violet
#

well that null

vestal arch
#

add only the transforms you need

vestal arch
naive swallow
round violet
#
var tempAloc = new Transform[bulletPoolMaxSize];
bulletEntitiesTransformAccessArray = new TransformAccessArray(tempAloc);
leaden ice
vestal arch
round violet
#

ik, its for conveniance later on

vestal arch
round violet
#

well thats just a refactor of what i shared ?

leaden ice
#

that takes an int instead of an array

round violet
#

its defining capacity

leaden ice
#

yes

vestal arch
#

TransformAccessArray is a list. you're nuking your options by using an array as an intermediate rather than just using the list directly

leaden ice
#

it's not the same, and doing it with the array the way you are is what's causing the issue

round violet
#

whats "default" here anyways
i can only think of null

leaden ice
#

default isn't really relevant here

round violet
#

since its a transform

vestal arch
#

no clue what digiholic was referring to

leaden ice
#

yes default for Transform is null

#

but it's not relevant really

naive swallow
leaden ice
#

that's why your array elements are null that's all

naive swallow
#

which is why it doesn't like putting nulls in

vestal arch
naive swallow
#

Transform[] will have nulls in it if you create it with capacity.

#

TransformAccessArray has some optimizations for memory and should not be created from an array with nulls in it

round violet
#

ill test that when i got time

#

for now it does impact enough to be noticeable in profiler

leaden ice
#

this is a double whammy

vestal arch
#

wdym when you have time lmao

#

it's a 1 line change

leaden ice
#

not only are you adding the nulls to the TAA which is bad enough, but you're allocating an extra useless managed array too

round violet
vestal arch
#

it's a one line change
ig unless you were using tempAloc to pass in transforms afterwards for some reason

round violet
#

ill have to do a few tests after "changing this only one line"

vestal arch
#

you would use TransformAccessArray's methods for managing its elements, rather than through the tempAloc

surreal adder
#

my code works in editor but not build

#

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

public class ShellPickup : MonoBehaviour, IUsable
{
public GameObject explosionEffect;
public GameObject puff;
public Sword sword;

[SerializeField] private AudioClip _clip;
// Start is called before the first frame update
void Start()
{
    sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();
    SoundManager.Instance.PlaySound(_clip);
}

// Update is called once per frame
public void Use()
{
    sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();
    if (sword == null)
        sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();

    if (sword != null)
    {
        sword.hasShell = true;
        Destroy(gameObject);
    }
    else
    {
        Debug.LogWarning("reference is null");
    }
}

}

#

its an ui button and it does nothing when clicked only in build

tawny elkBOT
surreal adder
#

sorry

rigid island
#

paste code onto one of the links, hit save and send link

surreal adder
#

i know its scripting order but i really dont knoiw

rigid island
#

make a dev build check for errors, also the Player log file to see if there are any erros anywhere

surreal adder
#

what exactly is the problem, i tried using awake() too

rigid island
#

also are you building the correct scene?

surreal adder
#

yes

#

but in general it can be used in many scenes

rigid island
#

it might just be a UI issue

surreal adder
#

what i dont get is that i have a ton of items similar to this one

#

same ui and stuff

#

but nah they work

rigid island
#

since in the build the resolution changes it could be shifting the UI and covering the clickable areas

surreal adder
#

also they work when u click 1 2 or 3 on keyboard

#

as shortcuts

#

i know its not a ui error its scripting order

#

but idk what exactl

surreal adder
rigid island
surreal adder
#

kinda

#

i remember it had a really really simple fix

#

but i lost that

#

and i cant remember how i did it it was a year ago

#

and also i think valid proof is that many other items

#

use the same thing

#

and also that they dont need UI to be activated ive implemented keyboard shortcuts for them

rigid island
#

idk what "other items" means in this context, havent really showed what it looks like

surreal adder
#

i can record if u wanna

#

but its just other stuff that use the same inventory system

#

like this

rigid island
#

or what exactly isnt working
"its an ui button and it does nothing when clicked " sounds like UI to me unless you can check the PlayerLog and see errors

surreal adder
#

and can be activated when picked up

#

they have same exact ui

#

and they work

surreal adder
#

is that i cant find that

#

i tried but my player log is nowhere

#

folder empty

rigid island
surreal adder
#

nothing

#

idk

#

nothing in the folder

#

its just nowhere to be found

#

i dont know what im doing wrong

rigid island
#

yeah it should be %USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log

#

are you sure you set them to what you expect in Player Settings ?

#

also try the Development build thing

surreal adder
#

ill try

#

wait

#

nope

#

nothing

#

i did

#

put the setting

#

script debugging too

rigid island
#

what does "put the setting" mean , also do use a complete sentence before hitting send

surreal adder
#

no

#

sorry, but i meant development build and script debugging

#

both are on but theres just no log file

rigid island
#

and what about the box in the Dev build does it show info, on the actual game

surreal adder
#

oh i just managed to do that

#

it says value cannot be null

#

still no log but the box is there

rigid island
surreal adder
surreal adder
rigid island
#

screenshot

surreal adder
#

ah sorry

#

Wait a sec

#

Till then i can just say that the only thing visible in the box is "value cannot be null, parameter: target"

#

I cant get the damn box to reappear

#

I really dont know how this debugging stuff works

rigid island
#

that could be anything really lol hard to know if its somethiing in your script or something else

surreal adder
#

My biggest problem is that i remember the fix was hella easy

#

All i know is its in that script

#

Or maybe one other one

#

But its not UI

rigid island
#

so you tried calling the same function with a Keyboard key press and works ?

surreal adder
#

I can send other items scripts

#

Theyre same formula

#

And they work

#

They get component of an object

#

Set it to true

#

Button dissapears and it works out

surreal adder
#

Other items do

#

And again to specify, other items have the same ui and logic

rigid island
surreal adder
#

Theres a shell that you can put on the weapon

#

Clicking the button gives the sword "hasShell = true"

#

And it's supposed to have it on

#

And it works fine in editor

#

I can send the sword code too

rigid island
#

all it changes is a bool ? that doesnt sound like the function itself is the problem if thats all it does.

#

I'm thinking more in terms with reference types and any possible nulls / order access issue

surreal adder
#

Well ye pretty much but the buttons find the sword

#

They fail to find it

#

The sword is an instance though

#

That also might be a problem?

naive swallow
surreal adder
#

I can re send the script

#

It finds the object with a tag

#

As i said it works in editor

naive swallow
#

Wait, scrolled up and found the link

surreal adder
#

So thats why i am sure its an error with code order

naive swallow
#

What is the point of this. You search for it, and if it's null, you just do the same search again?

surreal adder
#

Yes

#

I know its dumb but when youre sitting for more than one hour

naive swallow
#

That's just gonna get null again

surreal adder
naive swallow
#

GameObject.FindGameObjectWithTag is going to find whatever object with that tag has the lowest GUID which is essentially completely out of your control

surreal adder
#

But there is only one object with that tag

naive swallow
#

If you have more than one object with that tag, you basically can't guarantee which one you'll get

surreal adder
#

It should recognize it?

surreal adder
#

And wouldnt that then cause problems in the editor too

#

But it works perfectly in the editor

naive swallow
#

Then if there's only ever one, why the Find at all? Set it in the inspector

surreal adder
#

I cant

#

Its a prefab

#

It appears sometimes so it needs to find the sword automatically

naive swallow
#

Is this a prefab, or is the Sword a prefab? Or both?

surreal adder
#

No no sword is an object

#

Part of player

naive swallow
#

So, have whatever object spawns this pass in the reference to the thing it spawns

surreal adder
#

And the shells are prefabs you pick up, theyre supposed to be used with the sword

naive swallow
#

and have that object reference the sword in the inspector

surreal adder
#

Well kinda, this is a script for a button, and the button equips a shell when clicked

#

And u get the button by picking the shell off

#

I can record it if u wanna

#

It would be like 8s long

naive swallow
#

It's a prefab, so you're spawning it somewhere, right?

surreal adder
#

Yes

#

Its a UI prefab

naive swallow
#

So, have that script set the sword variable on this script after you spawn it

surreal adder
#

Its a button it needs ro be used

#

I can record , im saying again cause it explains whats thw issue better

naive swallow
#

I have no idea what it being a button has to do with this

surreal adder
#

I suck with words sorry

naive swallow
#

Spawn the prefab, set the variable on it

#

Sword is a scene object, right?

#

Is the thing that spawns this ShellPickup also in the scene or is it also a prefab?

surreal adder
#

Yes but when button is clicked prefab deletes and sets variable to true

naive swallow
surreal adder
#

Shellpickup is a button that spawns when u pixck the shell up

naive swallow
#

Clicking hasn't occurred yet

surreal adder
naive swallow
#

When you spawn the object, set the sword variable

surreal adder
#

They choose when they equip it

naive swallow
surreal adder
#

A that

#

But it finds the sword

#

When spawned

naive swallow
#

Spawn prefab, set sword variable

surreal adder
#

In editor

#

In game jt doesn't

#

Set the variable

naive swallow
#

Then the prefab can do whatever the hell you want

surreal adder
#

It just wont

naive swallow
#

Don't use Find

#

Set it directly, in code, after spawning it

surreal adder
#

And also i repeat, why does my method work in editor

#

And not in build

naive swallow
#

You probably have something else with that tag that you don't know about

leaden ice
#

also potentially execution order being arbitrary

naive swallow
#

and in a build it's finding that

leaden ice
#

How do you know what you don't know πŸ€”

naive swallow
# surreal adder I dont

How about logging the thing your Find returns and seeing what it says so you know for sure

surreal adder
#

I checked

surreal adder
#

The prefab just wont apply

#

I even removed the tag

#

And switched it with a new one

#

Special for this one object

#

And replaced name in the code

naive swallow
#

Well, either you want to find out why it's not working in a build in which case you're going to need to do some logging and find out what it's actually getting instead
Or you want it to just work in which case you should just set the variable directly when you spawn it

surreal adder
#

I need it to work in the build

#

Like it does in the inspector

#

And learn how to NOT cause that again

naive swallow
#

So, put the logs in to find out what is happening in the build

surreal adder
#

Also i think i should apologise for explaining terribly, help of everyone here means a lot

naive swallow
#

instead of just assuming you know what the problem is

surreal adder
#

In the folder

#

Even in dev build with debugging on

naive swallow
#

Do the find first, log the thing it finds. Then try to get the Sword component from it and see if that exists

naive swallow
#

and it won't log anything

surreal adder
#

Huh

#

Not having logs is the main reason i did come here for help

naive swallow
#

Break down your chained functions into steps so if any of them are throwing an exception you'll know exactly which part is the problem

#

So, find the object and store it in a variable. Then on another line, get the component from that

surreal adder
#

Why are they not throwing an exception in the inspector

naive swallow
surreal adder
#

And how do i know which ones ARE throwing it in the build without logs

naive swallow
#

Finds are not consistent

#

In the editor, your objects are running in one order, and Find is returning one object, and those could all be different in a build

surreal adder
#

But why is this happening

#

Even an order sword is always there

#

I managed to (kinda?) fix it by using JUST find

#

And then the name of the weapon

#

Instead of relying on a tag

#

Still, thank all of you for your help and again sorry for not understanding some stuff im still mostly new

mint zenith
#
    void Update()
    {




        float dist = Vector3.Distance(Player.transform.position, DoorMainS1.transform.position);

        Debug.Log(dist);


        KeyDisplay.SetActive(dist <= radius);


        if (dist < radius)
        {

            if (Input.GetKey(KeyCode.E))
            {
                SceneManager.LoadScene("Room2Scene");
            }
        }

        

    }

any idea why the

KeyDisplay.SetActive(dist <= radius);
doesnt work?

#

everything else works but that one line

#

it doesnt make the key display work as it should (its a canvas)

leaden ice
mint zenith
#

already did

#

im telling you bro everything

#

works perfectly fine

#

but that one line

#

even the debug.log(dist)

leaden ice
#

I only dsee Debug.Log(dist)

mint zenith
#

yea

#

everything works fine

#

but that line

leaden ice
#

I don't see any logging of radius or what the result of dist <= radius is

mint zenith
#

radius is a float 3f;

leaden ice
#

how do you know

#

log it

#

to find out for sure

mint zenith
#

yo are u ragebaiting me

#

im logging dist

#

and its working fine

leaden ice
#

No, I'm trying to help you.

#

YOu are making assumptions. When debugging, the best way to do it is to remove all assumptions

#

The other thing you can and should log is the active state of the object before and after:

Debug.Log($"Before, KD is {KetDisplay.activeSelf}");
KeyDisplay.SetActive(dist <= radius);
Debug.Log($"After, KD is {KetDisplay.activeSelf}");```
mint zenith
#

yea it works

#

the thing u sent

leaden ice
#

wdym by "it works"?

mint zenith
#

lik

#

the bool value changes

leaden ice
#

Those were logs - share the output of the log

mint zenith
#

when the distance goes under the radius

leaden ice
#

ok good

leaden ice
#

the current active state of the object

mint zenith
#

doing it rn

#

alr so

#

it also prints completely fine

#

like as its intended

#

to do

leaden ice
#

so then the code is working fine

#

and your problem lies elsewhere

mint zenith
#

ye i js dont know

leaden ice
#

what exactly is happening that differs from your expectation

mint zenith
#

well

#

sometimes it just

#

appeasr instantly

#

and doesnt turn off

#

(the key)

#

or it just doesnt appear at all

#

dk

leaden ice
#

watching the console logs when that happens (now that they're all in place) should be helpful

mint zenith
#

ye sec

#

still

#

same thing

#

sameissue

#

but log works fine

leaden ice
#

What I'm saying is - when you see the issue happening - if this code is not the one activating it - then you have some other code activating it

mint zenith
#

defo not

leaden ice
#

Can you show a video of this?

#

Like with game view visible as well as the console visible

#

also - ideally have Collapse turned off in the console

mint zenith
#

collapse?

#

oh

#

ye

#

i cant send a video here

#

nvm

#

its just there

#

and then doesnt go away

naive swallow
#

I'm trying to find a way to visually indicate what a camera can see, I want to tint everything in view of a camera with a color, so you can see what's visible to it. Something that would basically work like a light, but only illuminating what that camera can see and nothing else

naive swallow
# mint zenith maybe a cone?

I don't want an approximation of the shape of a frustum. I want the exact things that are visible by the camera to be tinted a different color

mint zenith
#

idk

#

lemme think

naive swallow
#

Finish a thought then hit enter

#

You're going to push the question off the screen

mint zenith
#

so i helped u but ur being a weirdo

naive swallow
#

By your own admission, you were guessing at something, and were posting it one or two words at time, pushing the question off screen from someone who definitely knows a way

naive swallow
#

And whatever you were suggesting before deleting it didn't make sense anyway. There already is another camera. Hundreds of them, even. I need to color what a camera can see regardless of what the active camera is

#

I need to basically project a color out of the camera and tint everything it touches

#

just the visible area, not the whole object

sinful locust
opal geyser
#

How do you launch something rotating... And when it touches a ceiling or wall or floor... It attaches to it?

My enemy got a skill... It throws a turrent to the air and sticks to surfaces. Like - sticking on it with proper angle.

β€’ If its ceiling. Its up-down. 180Β°
β€’ If its wall. Its 90Β°. (- or + depends on left/right wall)
β€’ If its floor (didnt hit anything else) then its 0Β°

How is it done? Hmm right now turret gets thrown and spins... It has a raycast to its front with hitinfo to get "normal". Hmm

leaden ice
opal geyser
#

Yeah but once it gets surface normal - what is needed to make it stick with proper angle?

cold parrot
opal geyser
cold parrot
#

anywhere really

opal geyser
#

I dont understand how this get normals really work o.o

#

I mean, using maya - i know its the surface of an element. The "face" - but converts that into rotation if it hits a side or bottom... Not sure

cold parrot
# opal geyser I mean, using maya - i know its the surface of an element. The "face" - but conv...

If you want to stick a cube on a wall so that it sits flush to the surface you set its transform.up = hit.normal (+ some offset to the position along the normal depending on the object’s pivot), but that wouldn’t be the most plausible ’stick’ pose. β€˜stick’ implies it freezes in the rotation it has at the moment of impact. The β€˜flush’ pose would be more like a snap created by some form of gravity or magnetism.

opal geyser
night harness
#

Based on what i've seen online there's no like perfect option but any personal recomendation for solutions to identify different "islands"/"areas" of a mesh using it's verts and indicies?

#

I don't think i can 100% confirm all my usecases use proper vert indexing either so i think i need to do distance checks?

twilit scaffold
#

Any insight as to why this needs to be qualified/clarified now? (6.2.b4)

 error CS0118: 'Editor' is a namespace but is used like a type

i can fix it, so far, with UnityEditor.Editor but i am curious to know if this is a beta error, or is just how it is now

cosmic rain
#

How was it used?

twilit scaffold
#

public class SmartTools_SettingsEditor : UnityEditor.Editor @cosmic rain

#

i am not a programmer, so i am not sure if that is enough information

cosmic rain
#

Did you try with using UnityEditor?

twilit scaffold
#

interesting.. i was not seeing that error in 6.0, or 2022.3, but i upgraded this project, and had other issues, so perhaps related.

#

yes, that using is set

#

Better Folders also caused the same error

cosmic rain
#

If you have the using, and inherit from Editor does it error out as well?

twilit scaffold
#

it will take me a minute to figure out how to do that, code-wise

cosmic rain
#
using UnityEditor;
public class SmartTools_SettingsEditor : Editor
twilit scaffold
#

yes., and i 'fixed' it by adding adding the qualification

cosmic rain
#

Oh, I see. Then it must be a namespace either in your project or in one of the namespaces you include with usings.

#

Which creates an ambiguity for the compiler

twilit scaffold
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Overlays;
using UnityEngine.UIElements;

#if UNITY_EDITOR
namespace SmartTools
#

interesting

cosmic rain
#

maybe in SmartTools?

twilit scaffold
#

although i do not know if it is true, this is what the AI told me:
"You have a folder or class named Editor somewhere in your project that is overshadowing the UnityEditor.Editor type.

Unity 6000.2 introduced stricter parsing of ambiguous identifiers, and now it prioritizes the Editor namespace over the Editor class."

cosmic rain
#

That's more or less what I've said. Aside from the latter sentence. Need to confirm that.

twilit scaffold
#

Yep, just included that first sentence to be complete

twilit scaffold
#

Logging off for the night. good hunting

vestal arch
#

@twilit scaffold if your ide is configured, you can hover over Editor when it errors to see what it's pulling from

night harness
#

Just sanity checking, I think it's ok? I want to check if a point is within a bounds but with consideration of rotation. Collider.ClosestPoint works well but not all my bounds use a collider.

My attempt at solving this is just making a "singleton" collider where i just sample a rotation + the bounds. This should work fine right? Assuming my Bounds is in world space

    internal static bool Contains(Bounds b, Transform t, Vector3 point)
    {
        BoundsCollider.transform.rotation = t.transform.rotation;
        BoundsCollider.center = b.center;
        BoundsCollider.size = b.size;
        return (BoundsCollider.ClosestPoint(point) == point);
    }
leaden ice
#

So the premise is confusing

#

Do you want to check if the point is inside a collider?

#

What do you mean by this exactly?

night harness
#

Bounds cannot ever rotate but I have a scenario in which I have a bounds on a rotated transform, but not a collider

leaden ice
#

Why not just use a BoxCollider on that object

night harness
#

reasons

leaden ice
#

And maybe that's what you're actually doing here with BoundsCollider

night harness
#

it is

#

i would love to go that route but no dice

#

hence my idea of using a single new one that gets kinda shared around during the check

leaden ice
#

So I mean... Yeah the code makes sense in that way but the whole setup is confusing to me

#

Why is it "no dice"

night harness
#

Stuff we can't talk about specifically on this server

#

call it an arbitrary requirement πŸ˜„

leaden ice
night harness
#

oh good call

mossy snow
#

that snippet does not do what it says it does and it would be incredibly buggy even then. Delete BoundsCollider, inverse the point into local space of t and use bounds Contains if you want to determine if a rotated bounds contains the point

#

and Praetor has a good point here: you are probably supplying renderer bounds (world space) to this method and that doesn't consider rotation (it's an AABB), so your setup is definitely weird. If you make the change I suggested, you will probably want to provide mesh bounds instead in local space

night harness
#

its not renderer bounds but is world space. I don't have mesh bounds here

#

will look into your suggestion though, I don't fully understand how transforming points works in regards to rotation so that might be my blind spot

steady bobcat
#

bounds are axis aligned so to have some kind of rotation you need to counter rotate the point around the bounds pivot/center before checking
this can be done with a matrix or quaterion if you work in local bound space instead.

mint zenith
#

hello, i wanted to ask if there is a way to make a wait/delay inside of update

vestal arch
mint zenith
#

im detecting a keypress

#

to load a scene when that key is pressed

#

but it loads it instantly

#

i want it to load 2 seconds late

#

like :

click e
2 sec passes
loads the scene

vestal arch
#

you would use a coroutine for that

mint zenith
#

yea but the funny thing is idk how to use those

vestal arch
#

call a coroutine from that button press, then in the coroutine you can easily make a delay

mint zenith
#

ik what they are but idk how to set themup

vestal arch
#

the internet is full of resources
you have a keyword to search for now

#

being able to find information yourself is a very crucial skill, may as well practice that now πŸ˜‰

mint zenith
#

alrighty

#

ok

#

i think i got it

#
IEnumerator DelayedSceneLoad()
{
    isWaiting = true;
    yield return new WaitForSeconds(2f);
    SceneManager.LoadScene("Room1Scene");
}
#

something like this?

#

then call the coroutine @vestal arch

royal violet
#

how can i make my player always look at where the 3rd person camera is pointing? animation blends? (Even when moving sideways like fortnite)

cosmic rain
royal violet
latent latch
#

Lookat probably fine, but can maybe get 4 animations in blender to get the constraints you want then throw them into a blend2d/3d

outer quail
#

!code

tawny elkBOT
outer quail
#

In 3D FPS games, is shooting typically done by instantiating a bullet prefab and shooting it forward or is it done with raycasting?

errant smelt
#

hey is anybady a gtag mod menΓΌ guy i need help maiking one

stark wing
# outer quail In 3D FPS games, is shooting typically done by instantiating a bullet prefab and...

I mean, raycasting is the most typical way of doing that in those game from my experience, but some games do also use bullet prefabs if, for example, an NPC enemy's shot is intended to be dodged by the player.

so, basically, raycasting is more common in FPS games, but many such games have both bullet prefabs and raycasting (depending on whether or not a specific weapon shot is meant to be avoidable by the target). I myself tend to use bullet prefabs, since I am so used to them (and also because I haven't figured out a way to script a visible line between the raycast starting point and the impact point, so I could have a visual effect...)

swift falcon
#

for some reason this is still giving me an error when i attempt to unload the current scene, unsure as to why tho

public class CustomisationDoneButton : NetworkBehaviour
{
    GameObject player;
    public GameObject playerPreview;
    public void CustomisationDone()
    {
        StartCoroutine(LoadGameplayScene(playerPreview));

        GameObject[] allClients = GameObject.FindGameObjectsWithTag("Client");

        foreach (GameObject client in allClients)
        {
            if (client.GetComponent<ClientInfo>().clientID == NetworkManager.LocalClientId)
            {
                client.transform.GetChild(0).GetComponent<PlayersObjects>().playersColor.Value = playerPreview.transform.GetChild(0).GetComponent<PlayerColourPreview>().playerColor;
            }
        }

        StartCoroutine(UnloadCustomisationScene());

    }

    public static IEnumerator LoadGameplayScene(GameObject playerPreview)
    {
        SceneManager.LoadScene("MainGameplayScene", LoadSceneMode.Additive);

        yield return null;
    }

    public static IEnumerator UnloadCustomisationScene()
    {
        SceneManager.UnloadSceneAsync("PlayerCustomisationScene");
        yield return null;
    }
}
swift falcon
# cosmic rain What error?

"Unloading the last loaded scene Assets/Scenes/PlayerCustomisationScene.unity(build index: 3), is not supported. Please use SceneManager.LoadScene()/EditorSceneManager.OpenScene() to switch to another scene."

cosmic rain
#

Speaking of which, your coroutines don't do anything at all

#

I suggest you check the documentation on coroutines. This is not the correct way to use them.

leaden ice
swift falcon
#

how come the LoadGameplayScene() coroutine isnt loading in?

cosmic rain
#

The scene starts loading, but you don't wait for it to complete loading.

leaden ice
#

Are you ever running it?

#

Oh I see

#

Yeah LoadScene (non async) takes one frame to complete

#

So you'll need to wait at least one frame for that to finish before unloading this scene

#

Conveniently, you're in a coroutine already so that's very easy

#

Just
yield return null;

#

( the one in your bottom coroutine doesn't do anything)

swift falcon
#

i already am doing that though?

cosmic rain
#

The top one doesn't do anything either. It just delays the end of a coroutine after the scene is loaded.

#

The bottom one also. Basically, you're not really delaying anything.

#

All of the shared code executes immediately

swift falcon
#

how would i get it to wait until the scene is loaded before unloading the new scene then?

cosmic rain
swift falcon
#

yeah that worked thank you so much

tidal moss
#

Hello! So when instantiating gameobjects while the character is moving, they lag behind the spawn transform. for a prefab im instantiating i set a flag and check it in LateUpdate to spawn the obj, this worked for that. but i have vfx prefabs, doing the same thing, instantiating in LateUpdate, but its still behaving like its happening before the movement.

somber nacelle
#

are those objects being moved to follow the "spawn transform"? if so, are they being moved in LateUpdate too?

tidal moss
somber nacelle
#

then describe what you mean by "they lag behind the spawn transform"? because if that object is moving and an object is spawned at its location then the locations will only be the same for the first frame that new object exists

tidal moss
somber nacelle
#

you should throw a Debug.Break in when you spawn the object so you can see exactly where it spawns in relation to the spawner object

#

Debug.Break will pause execution at the end of the frame so theoretically you should see it at the same location

upper karma
#

Hey, im pretty sure this can be more compact but im not sure how.

        if (TotalEnemies <= 12)
        {
            level = TotalEnemies / 6; //if 6 returns 1 if 12 returns 2
        }
tidal moss
#

ill do that, i just turned the time scale wayy down to see it in slo mo and ye its spawning at the correct pos, it just looked like it wasnt because of the vfx being in the same spot

vestal arch
upper karma
#

so there wasn't a way to put an if statement (aka condition) on equals?

vestal arch
#

not one sided like that, no
c# doesn't have that kind of modifier

#

you could do ```cs
if (TotalEnemies <= 12) level = TotalEnemies / 6; //if 6 returns 1 if 12 returns 2

lean sail
#

You might be thinking of the ternary operator here? but you dont have anything here if the equation is false.
Anyways needlessly making everything more compact is a waste of time. It is readable, that is good

lean sail
vestal arch
#

other languages could use && to short-circuit i guess, but c# is not one of those languages

upper karma
#

btw can i make functions take optional arguments?

swift falcon
#

How in render graph can I apply full screen pass to culled objects texture then blend into original texture ? The culling pass from RG samples works, but I can't have the culled objects to have a pass on it, and can't blend it into original texture. If I try to do this with camera stack as camera overlay with culling layer set, the pass is used by the other camera

rigid island
lime onyx
rigid island
lean sail
#

I am trying to research how games (like elden ring) get clean movement when enemies are jumping/dashing around. I don't have a specific video example but for example an enemy could jump up in an arc then lunge at you from the air.
My question is how should I replicate these kind of movements from a code perspective?

Correct me if wrong: My understanding is animations + root motions would work here, but not respect physics since this moves the transform itself. What I'm thinking is I should still use the animator but use OnAnimatorMove() and the .deltaPosition to move it in a way that would respect physics. Then i just disable other stuff like gravity in the meantime. I'm not exactly sure how that'd work in regards to aiming the lunge but does this sound like a reasonable approach?

cold parrot
#

most "movement" in ER is just an animation that is oriented to play towards the player.

#

it appears to me there is no physics simulation in ER (for combat)

lean sail
cold parrot
#

they will probably validate if a "dash" is possible through a navmesh

#

but the dash itself is an animation and the arenas are designed to be quite open and non-obstructive

lean sail
#

I understand its a different engine though so I cant really ask how they coded it. I'm more so wondering if my current idea with OnAnimatorMove would let me replicate it

cold parrot
#

if a fight is in a complex space that is usually tied in with the boss' move set

maiden orchid
#

does anyone know an extension for vscode where i can see a preview of a color next to a color32

cold parrot
#

the entire combat design of ER is built around playing out animations fully. the player's actions have no impact on the boss' animation (once started).

#

the boss decides on an action, moves to a start position, (optionally) aims for the player, and executes it, that is really all there is to it

lean sail
gloomy hornet
#

Hello everyone, I am trying to make a ball simulation. But i have a problem with my fps. Every ball in the scene has Update method to calculate if they're outside the cirlce or not.

public class BallScript : MonoBehaviour
{
    public float distance;
    public BorderManagerScript manager;

    private void Update()
    {
        distance = Vector3.Distance(transform.position, new Vector3(0, 0, -9));
        print($"{distance} + {manager.borderRadius}");
        if (singleBorder)
        {
            if (manager.borderRadius <= distance)
            {
                Destroy(gameObject);
            }
    }
}

This code cause's a lot of FPS drops, how I can optimize it?

cold parrot
# lean sail unfortunately i just dont have examples because ive only seen friends play it. t...

might be worth considering that the hit-responses in ER seem to be 'overlays' on top of an animation that is playing uninterrupted, and that in idle/walk states these hit effects are stronger. Knockback etc. may be allowed on top of the underlying root motion. you often see the animation clip slightly into the environment. so they aren't too worried about making the root motion "perfect"

lean sail
#

especially not so much to be running at 1 fps

gloomy hornet
#

what is the profiler

lean sail
gloomy hornet
#

how can i use it to find out what is causing the lag

lean sail
gloomy hornet
#

ok i understand it, it is beacuse of physics calculation here. too much colliders and rigidbodys. thank you for help

bright arch
cosmic rain
twilit scaffold
#

Oh, it also shows this:

#

none of the 'Potential fixes' it offers are valid though. That is ok, for now. i am fine qualifying it as UnityEditor.Editor

vestal arch
#

thinkies well that doesn't seem right

twilit scaffold
#

it seems to be just a 6.2 issue, and does not seem to apply to previous versions. a little research suggested the new roslyn compiler integration is stricter

faint tree
#

anyone had problems with unity editor scripts not working in unity6?

twilit scaffold
#

showing the actual error would be the best, to get help

faint tree
#

yeh theres no error, it just doesnt run

mossy snow
#

you did something wrong and nobody can tell you what unless you supply more info

faint tree
#

well i have a script like this WaypointsEditor : Editor which includes this [CustomEditor(typeof(Waypoints))], i expected that OnSceneGUI() would be called when i click on an object with Waypoints script on it

#

and i see people in forums talking about it like it works fine, so was wondering if maybe it was unity6 bug

faint tree
mossy snow
faint tree
#

damn i worked it out, there was another editor script with the same name

#

lol oh wait im completely wrong, thats something else

cosmic rain
#

You can F12 it and it would show you the definitions:

faint tree
#

hmm so yeh i cant get OnInspectorGUI() or OnSceneGUI to call even if i make a test editor script

twilit scaffold
cosmic rain
twilit scaffold
cosmic rain
#

Sounds like it's in the new AI tools. Well, nothing you can do about it. Just qualify the Editor type explicitly.

twilit scaffold
#

cool deal, thank you for the insights

faint tree
#

DOH, WAS MISSING editorForChildClasses: true

mighty ivy
#

Hi, I'm trying to create a tracking UI arrow for objects in my 3d env. Right now I'm trying to stick the UI object to the 3d object, I followed some guides online but it doesn't work right. The canvas is set to overlay, and the UI object moves in the lower quarter of the screen, as if the screen was 1/4th the real screen... That's the code:

#
public void UpdateTrackingArrow()
    {
        Camera cam = Camera.main;
        Vector3 screenPos = cam.WorldToScreenPoint(trackingObject.transform.position);

        if (screenPos.z > 0)
        {
            Vector2 viewportPoint = new Vector2(screenPos.x / Screen.width, screenPos.y / Screen.height);

            Vector2 refResolution = canvas.GetComponent<CanvasScaler>().referenceResolution;
            Vector2 canvasPos = new Vector2(
                (viewportPoint.x - 0.5f) * refResolution.x,
                (viewportPoint.y - 0.5f) * refResolution.y
            );

            trackingArrow.GetComponent<RectTransform>().anchoredPosition = canvasPos;
            trackingArrow.gameObject.SetActive(true);
        }
        else
        {
            trackingArrow.gameObject.SetActive(false);
        }
    }```
tawny elkBOT
mighty ivy
# vestal arch !code

Ugh, sorry but it's a real pain to use the code markup with the italian keyboard. It has no backtick key and the Drevo keyboard I'm using doesn't have the numpad so I can't even use alt + 96 to write it 😭 I have to copy and paste that from Google

mighty ivy
vestal arch
#

i think referenceResolution is not the right property
it's not the actual resolution, it's just the one you design at, and then it can be scaled up or down according to the actual resolution

mossy snow
vestal arch
#

probably don't need/shouldn't have that !

mighty ivy
#

that's the position of the square

#

(the object is NOT behind the camera)

#

oh right nevermind

vestal arch
#

that would only matter for the z position

mighty ivy
#

the 0/0 is the center of the screen

mossy snow
#

are you sure you're using the right camera? maybe your screen point is just not right

mighty ivy
#

Yeah.. it is also right, the position of the square is just "scaled down" to the lowest quarter of the screen, but it's correct

#

is it a problem that the camera output is a texture?

#

With the debugger I noticed that the cam output is the same size as the render texture. I'm pretty sure that's the problem, since the canvas has a larger size

mighty ivy
#
public void UpdateTrackingArrow()
    {
        Camera cam = GameManager.instance.player.GetComponent<PlayerController>().playerCamera.GetComponent<Camera>();
        RectTransform canvasRect = canvas.GetComponent<RectTransform>();
        float widthRatio = (canvasRect.rect.width / cam.pixelWidth) * canvasRect.localScale.x;
        float heightRatio = (canvasRect.rect.height / cam.pixelHeight) * canvasRect.localScale.y;
        var screenPos = cam.WorldToScreenPoint(trackingObject.transform.position);
        RectTransformUtility.ScreenPointToWorldPointInRectangle(trackingArrow.GetComponent<RectTransform>(), screenPos, null, out var worldPos);
        worldPos.x *= widthRatio;
        worldPos.y *= heightRatio;

        trackingArrow.transform.position = worldPos;
    }``` This fixed it, thanks for the debugging help πŸ™‚
dire crown
#

I made it work on 2022 LTS, but can't get it working on 2021

chilly surge
#

Hopefully you are only using it for debugging stuffs, and not using it for some dark magic.

dire crown
#

I'm using it for some dark magic

chilly surge
#

You would have to patch the C# compiler in your Unity installation, not something you want to do.

chilly surge
dire crown
#

In 2022 it works quite straightforward

dire crown
chilly surge
#

Whatever you are doing, can likely be written in alternative and less magical ways.

dire crown
#

less magical, but longer

#

Something as pretty as this

protected override void SetInputValues(BranchData branch)
{
    TryGetInputData(branch, out Input);
}

would become

protected override void SetInputValues(BranchData branch)
{
    TryGetInputData(branch, out Input, nameof(Input));
}

🀒

chilly surge
#

Absolutely better to write it longer.

#

I wouldn't even use nameof(Input).

#

When you read code, the fundamental assumption about things like member names is that the names don't matter. If I press F2 in my IDE and rename Input to something else, it should behave exactly the same as before. The fact that renaming a member can potentially completely change the logic of a piece of code, is very problematic.

dire crown
#

In the scenario of this specific code which relies on purely runtime stored data, the logic wouldn't be affected by the name itself, it's only being used both when storing it, and when retrieving it. Technically, requiring the typed name/key would make it worse since there's another place where the names could differ from storing and retrieving

chilly surge
#

Without context I'm not exactly understanding what that means, but if your problem is "what if I have two pieces of code that wants to deal with the "Input" key and they might accidentally drift out of sync" then the answer is simply centralize the access.

abstract garden
#

how do i fix a redundant varible???

hidden compass
safe flame
abstract garden
#

nvm

#

i did it

vestal arch
median onyx
#

!code

fiery steeple
#

Hey,
I'm trying to check if the left tile isn't out of bound, but apparently I'm doing something wrong and it says about never being "null", so I'm not sure to understand how to check for out of bounds please πŸ€”

vestal arch
fiery steeple
vestal arch
#

if you're sure i itself is in bounds and j is in bounds, sure

rigid island
steady bobcat
fiery steeple
steady bobcat
fiery steeple
steady bobcat
tall coral
#

Hey, can someone help me understand where my procedural generation code is going wrong? The GenerateChunks() function infinitely loops because for some reason it is getting to a point where it doesn't think there are any valid chunks left to be placed. However that shouldn't even happen, any advice?

https://pastebin.com/BUegYJNU

hardy mulch
#

How do I use a C# that supports Halfs? I am using unity6

somber nacelle
#

you don't because unity does not use a .net version high enough that includes that type

hardy mulch
#

Half's have been out for over 5 years :/

somber nacelle
#

yes, but unity does not yet support .net 5

hardy mulch
#

Well in that case is there a solution (ie library/package) to convert two bytes (that represent a float16) into just a normal float, or am I going to have to just write that myself

late lion
hardy mulch
#

Im reading some serialized data that contains halfs

late lion
#

Mathf.HalfToFloat converts a ushort, a 2 byte primitive, to a float. So if you reinterpret the 2 bytes you have into a ushort, you can use Mathf.HalfToFloat.

hardy mulch
#

ah I see ty

short flame
#

i have a json file formatted like this, is it possible to turn it into a list of strings?

#

i tried this but it gave me an error

somber nacelle
#

jsonutility does not support collections as the root object, you would need to use a different json serializer to deserialize that

short flame
#

any suggestions on what one might be? if not thanks anyways

somber nacelle
#

json.net is a popular one with a unity package available and should support collections at the root

#

or if you have control over where this json comes from you could instead just make the list a property of some object and deserialize that

short flame
#

will look into it, thanks again

fickle sand
#

Heyo, feel free to bump me to another chat if applicable but I've got a strange one - I'm having issues compiling new files in Unity (2022.3.23f). I've been trying to write an AudioManager script to handle SFX & Music, but I'm unable to actually compile my progress in-editor. I did a little investigating and the issue is only affecting newly created files - I've created three C# scripts all under different names and none have compiled, but I have managed to get existing scripts to compile successfully & update in-engine. Anyone have any idea what could be going on?

leaden ice
fickle sand
#

so when I update any script I'd created prior to today, it functions totally fine (see first image) - showing that unity registered the changed script and recompiles. I even added a comment and confirmed in the script preview that it did update.

this simply isn't happening when I create & update a script. the script is added totally fine, it can be a component on an object as normal, but any changes I make aren't detected by unity and doesn't cause a script recompile. The second and third images are what the script actually contains in my IDE vs what unity percieves it as containing.

Unity isn't flagging any errors at all - it's just not noticing the changes.

leaden ice
fickle sand
#

no - as stated it isn't flagging any errors

#

actually hold that thought - jetbrains is flagging that it wants an update now

leaden ice
fickle sand
molten musk
#

I'm reworking the movement system in my game for the last time.

First i just set the final position and rotation immediately.

I updated it to move between using MoveTowards.

The final solution i want to use is using AddForce and Torque to simulate a ships actual engines but i dont know how to use these to get to an exact position in the world

vale walrus
#

AddForce is very good for a space ship thruster. But having it arrive at certain position is not easy.

Engine power, drag, mass and gravity are parameters that define the behavior and top speed.

Why would you want to control where the ship ends up, and not let the player just steer?

molten musk
#

because the ship has automation which the ai versions use to navigate and they have an ordered mode which works like an rts controller

thick terrace
#

if you want totally realistic behaviour i imagine there's a lot more maths involved, but in my experience with a similar type of spaceship game it's usually good enough to get the ai 90% of the way there then fake the rest πŸ˜„

molten musk
#

tried faking the last alignment before, it messes up the physics

hidden compass
#

ever heard of PIDs? its how quadcopters keep their flight smooth
Proportional Integral and Derivative..

#

it may be something that could be added to ur system to make it perform better.. and let u focus on the bulk of the ai

fiery steeple
#

Guys why my code (mainly the method GenerateOtherTiles()) does mess everything and mines don't show up and look so empty.
When I remove the line tiles[i, j].Value = minesAmount (line 142), Mines are visible again but the other numbers saying how many miens are around each tiles don't show up, so I'm kinda confused on why it doesn't work properly πŸ€”

Does anyone know please ? πŸ€”

somber nacelle
#

!code

tawny elkBOT
somber nacelle
#

reread the conditions in your GenerateOtherTiles method

fiery steeple
somber nacelle
#

Okay let's start with the first condition you have in that method. What value do the mines have?

somber nacelle
#

Okay so how do you know if a tile is a mine tile?

fiery steeple
#

oh ok

#

so that's the first issue

#

because I have to skip it when it's == -1 and not != -1

somber nacelle
#

Yes

fiery steeple
#

Stupid mistake πŸ€¦β€β™‚οΈ Thanks, I think it works properly now πŸ˜„

fiery steeple
#

and the minesAmount++ that's repeated alot 😬

somber nacelle
#

i would personally store all eight directions (just the directions as a Vector2Int) in some collection and just loop through the collection, then check if currentPosition + direction is a valid tile and if it has a mine. that way you don't have eight separate if statements for pretty much the same thing

fiery steeple
magic heath
#
public struct TroopInfo
{
    public TroopData data;
    public GameObject visual;
}
public class Tower : MonoBehaviour
{
    public int CurrentLevel;
    [Header("TROOP")]
    [SerializeField] TroopInfo Info;
    public void SpawnTroop(Vector3 spawnPosition, Troop generic)
    {
        Troop troopToSpawn = PoolManager.SpawnObject(generic, spawnPosition, Quaternion.identity, PoolManager.PoolType.PlayerTroop);
        troopToSpawn.Initialize(Info.data, Info.visual, CurrentLevel);
        CurrentSpawnTime = SpawnTime;
    }
}
public class Troop : MonoBehaviour
{
    [Header("STATS")]
    [SerializeField] TroopData data;
    [SerializeField] TroopStats stats;
    [SerializeField] GameObject visualsHolder;
    public TroopData Data => data;
    public TroopStats Stats => stats;
    public GameObject Visuals => visualsHolder;

    public float currentTime;
    private void SetData(TroopData newData)
    {
        data = newData;
        stats = data.ReturnStats();
    }
    private void SetStats(int TowerLevel)
    {
        stats.MoveSpeed = stats.MoveSpeed * TowerLevel;
        stats.Damage = stats.Damage * TowerLevel;
        stats.Health = stats.Health * TowerLevel;
    }
    private void SetVisuals(GameObject troopVisual)
    {
        visualsHolder = troopVisual.gameObject;
        visualsHolder.transform.localRotation = Quaternion.identity;
    }
    public void Initialize(TroopData data, GameObject troopVisual, int TowerLevel)
    {
        currentTime = 0;
        SetData(data);
        SetStats(TowerLevel);
        SetVisuals(troopVisual);
    }
}

Hello, I'm trying to set-up a pooling system for a tower-defense game. Thing is, player can spawn towers which spawn troops. In my pooling system, i'm setting up a "generic" troop prefab which is supposed to override the info of the curren troop it holds, allowing every tower to use it.
I'm having issues with the visual aspect of it. Is there any way to replace the empty GO with the prefab one?

#

Maybe there's another approach that would work better than what I'm trying to do.

latent latch
#

If you want to use a single prefab solution you'll be swapping out all the rendering parts so stuff like the mesh renderer and mesh filter

pine ivy
#

movement lines at 44 and 62 but dont work for some reason

vestal arch
pine ivy
#

the character that was beat moves away through the animation, then the next character should move with the bugged code to the next position

#

so the animation shouldnt be affecting the next character

vestal arch
#

if the animator has "root motion" enabled i believe that kinda controls the position directly? i'm not too familiar with that aspect of animations tbh

#

you could check for it by commenting out the animations and just doing .gameObject.SetActive(false) or similar

#

and also disabling the animator

pine ivy
#

realized i probably shouldnt have the character objects as children of the spawn point images, but also realized that i cant actually move them around

#

tried pulling all the axis arrows and they dont budge

#

any suggestions?

#

or maybe theyre stuck in the animation...

quartz peak
#

hey guys, i'm currently new with unity. Im having an issue with my char prefab. it keep flickering the whole time. when I uncheck the animation controller the flicker are stopping.
Could anyone help me solve the problem ??

somber nacelle
#

if disabling the animator makes it stop, then the issue is likely in your animation(s)

rigid island
#

doesnt seem this is code related though..

#

but yeah could be the animation also messing with the positioning or something

quartz peak
fair jackal
rigid island
#

are you using asmdefs in your project?

fair jackal
#

i'm not sure about what asmdefs are so probably not, but i forgot to install the package πŸ€¦β€β™‚οΈ

#

do you know the name, i can't seem to find it

rigid island
#

the name is in the link itself

#

I guess its com.unity.testframework.graphics

fair jackal
#

oh wait i have this

#

ah never mind

rigid island
#

is that the same ? i have no idea I never used

fair jackal
#

i used com.unity.testframework.graphics

#

ok thankss

rigid island
fair jackal
#

i believe so, the package is downloading and it says experimental

#

which makes sense

#

wait

modest mural
#

hello and good day to everyone,
i tried to make a couple of games with raycasting interaction in them, and when the player interact with an interactable object mouse randomly gets dragged down to a random position on the screen, and it only happens when player looks at the first interactable object and after that looking at every other interactable object is normal and cause no issues
and i know the problem is with my raycasting script. here is the raycasting script

public class RaycastInteraction : MonoBehaviour
{
    public static float distanceToTarget;
    public static RaycastHit currenthit;
    RaycastHit hit;
    float _maxDistance = 5f;

    void Update()
    {
        Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

        if (Physics.Raycast(ray, out hit, _maxDistance))
        {
            distanceToTarget = hit.distance;
            currenthit = hit;
            Debug.Log(hit.collider.name);
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;
        Gizmos.DrawRay(transform.position, transform.forward);
    }
}

does anyone came across this problem before? any help is Appreciated.

fair jackal
#

i still get the error The type or namespace name 'Graphics' does not exist in the namespace 'UnityEngine.TestTools' (are you missing an assembly reference?)

somber nacelle
rigid island
# fair jackal i still get the error `The type or namespace name 'Graphics' does not exist in t...

Using the Graphics Test Framework

Before you can use the Graphics Test Framework in your project, you need to add the Engine and Editor TestTools.Graphics assembly definitions to the test assembly (asmdef) in your project. Alternatively, you can add com.unity.testframework.graphics to the testables section of your manifest, but that will add the Graphics Test Framework tests to your test runner window.

fair jackal
#

ah ok thanks

modest mural
somber nacelle
#

how could i possibly know why that is happening if you haven't shown relevant code

fair jackal
modest mural
# somber nacelle how could i possibly know why that is happening if you haven't shown relevant co...

sorry for that

here is the script:

[SerializeField] GameObject interactionText;
[SerializeField] GameObject interactionKey;

void Update()
{
    if (RaycastInteraction.distanceToTarget < 1.3f && RaycastInteraction.currenthit.collider != null && RaycastInteraction.currenthit.collider.CompareTag("Key"))
    {
        interactionText.GetComponent<TMP_Text>().text = "TO PICKUP";
        interactionText.SetActive(true);
        interactionKey.SetActive(true);

        if (Input.GetMouseButtonDown(0))
        {
            GameObject key = RaycastInteraction.currenthit.collider.gameObject;
            Destroy(key);

            GlobalInventory.hasKey = true;
        }
    }
    else
    {
        interactionText.SetActive(false);
        interactionKey.SetActive(false);
    }
}
rigid island
fair jackal
#

lemme send a sc real quick

somber nacelle
modest mural
fair jackal
somber nacelle
modest mural
rigid island
fair jackal
#

right now i'm using get pixels and then literally just getting the difference of the histogram values (like the total rgb), i'm assuming that's what you're talking about?

rigid island
#

yeah something like that I was thinking

fair jackal
#

hmm ok

#

do you have any other ideas, since right now it's not the greatest

rigid island
#

I think you can do check if the color values of each pixel match exactly,
color difference, use a color difference formula, such as Euclidean distance in RGB space.
or structural similarity ?
I don't know much about this stuff to give a concrete answer here, I'd research if there is maybe a github/asset that already solved this problem or maybe a thread

fair jackal
#

i see i see

#

well thanks for your help πŸ˜„ imma look through this stuff you talked about

#

by the way thank you so much for mentioning euclidean distanace in rgb, i was trying to hard to think of something like that but i couldn't put my finger on it

rigid island
#

best of luck

fair jackal
#

thanks πŸ™‚ do you want me to ping you if it works or should i just sent it somewhere and maybe you'll see it

rigid island
somber nacelle
#

then something is probably rotating the camera

modest mural
somber nacelle
#

the canvas's settings would not rotate the camera. it's likely something you're doing in an object's OnEnable or OnDisable

latent latch
#
//member variable
private bool initialized = false;

public void Deserialize()
{
    Debug.Log(initialized);
    if (initialized) return;

    Debug.Log("honk");

    var copy = new List<BlockEntry>(blockEntries);
    blockEntries.Clear();
    occupiedCells.Clear();

    foreach (BlockEntry entry in copy)
    {
        RegisterBlock(entry);
    }

    initialized = true;
}```
Any reason why initialized stays true after domain reload in the editor? Shouldn't it revert back to false? I've nothing else acting upon it. Even tagging as Nonserialized still returning true. Maybe Unity bugged
somber nacelle
#

!code

tawny elkBOT
modest mural
#

my bad

modest mural
wintry crescent
#

how to most efficiently allow a test assembly to be able to access the internals of all other assemblies?

#

I'm doing tests

#

I have about a million testing-only functions and this really isn't making much sense anymore

somber nacelle
modest mural
somber nacelle
#

how should i know? i haven't seen it

modest mural
#

i just sent it

somber nacelle
#

i said the rest of your code

modest mural
#

i copy pasted all of the codes here

#

there is no more

rain minnow
wintry crescent
pine ivy
rain minnow
wintry crescent
#

I figured out I can access internal ones with a file I put in the assembly, but not private ones

lament dragon
#

I'm trying to dynamically change font on my TMP asset in script
I have this, but the text will display "[...] <font=Vintage Poison SDF>f"
Help?

#

I've verified my imported font is spelled correctly. Multiple times.

long bison
#

I have two circle prefabs for a college project, one is supposed to be a fruit and the other one is supposed to be a bomb. How can I differentiate them in code (not color) so that my program can do certain things depending on which one it's handling? I'm really unfamiliar with how Unity works so I'm not sure how I would go about doing this

lean sail
long bison
#

forgot to mention about that. I should and how I have it currently isn't good, but I'm low on time and I can't entirely rewrite how that stuff works right now. Is there another way?

vestal arch
#

well, what do you have to differentiate them?

#

graphics? tags? layers?

long bison
#

one is supposed to add points and the other is supposed to subtract lives and delete all of the former ones

#

visually they will be differentiated

lean sail
vestal arch
#

or is that where the issue is

#

if you don't actually have any real difference between them, now would be a good time to introduce that difference, with separate components or tags or something

long bison
long bison
#

thank you, sorry about such a question

cunning pivot
#

hello quick question so i made an assembly definition file in a folder to put all utility plugins but how do i know which assembly reference a script (plugin) uses so i can add them without just guessing

leaden ice
cunning pivot
#

how can i avoid that

leaden ice
#

Can you back up and explain what you're trying to do?

cunning pivot
leaden ice
#

So what are you trying to do? Put your game code in an assembly?

cunning pivot
leaden ice
#

Which editor tools

cunning pivot
#

if i recall correctly this is the vid i watched

cunning pivot
leaden ice
#

What is heirarchy designer?

#

Is that a plugin?

cunning pivot
#

3rd party asset

leaden ice
#

Does it already have an assembly definition?

cunning pivot
#

i call them plugins XD it caused some confusion my bad

cunning pivot
#

hmm i don't think it does have a file of its own i checked but if i move it to the folder i made it throws an error cause it needs a reference but i don't know which one or do i have to check each script to see

#

sorry for the confusion

leaden ice
naive swallow
#

You shouldn't be creating Assembly Definitions for third-party assets or moving them anywhere

leaden ice
#

one for the editor, one for the runtime

#

and the editor one generally needs to refer to the runtime one

#

Your plan of just throwing all of your plugins into a single folder and plopping an asmdef in it probably won't work out.

#

most plugins already come with their own assembly definitions out of the box though

#

the ones that are well put together at least.

cunning pivot
#

well i already got 10s of them in the folder then 2 or 3 that errored out won't be a problem anyways

cunning pivot
#

i'll leave them be

cunning pivot
mighty ivy
#

Hi! I create a tracking arrow that follows an object (or a waypoint) offscreen around the player UI. It helps the player follow waypoints and objects.

#
Camera cam = GameManager.instance.player.GetComponent<PlayerController>().playerCamera.GetComponent<Camera>();
RectTransform canvasRect = canvas.GetComponent<RectTransform>();
        
//Calculating width to height display ratio to adjust the values
float widthRatio = (canvasRect.rect.width / cam.pixelWidth) * canvasRect.localScale.x;
float heightRatio = (canvasRect.rect.height / cam.pixelHeight) * canvasRect.localScale.y;
//Creating a Vector3 fromt the waypoint coordinates with the Y set the same as player (always under the camera)
Vector3 waypointCoordinate = new Vector3(trackingObject.waypointData.coord.x, GameManager.instance.player.transform.position.y, trackingObject.waypointData.coord.y);

var screenPos = cam.WorldToScreenPoint(waypointCoordinate);
//Getting the (unscaled and unadjusted) Screen position of the object
RectTransformUtility.ScreenPointToWorldPointInRectangle(trackingArrow.GetComponent<RectTransform>(), screenPos, null, out var worldPos);
//Scaling for display ratio
worldPos.x *= widthRatio;
worldPos.y *= heightRatio;

//Removing half the screen size
worldPos.x = worldPos.x - ((canvasRect.rect.width / 2) * canvasRect.localScale.x);
worldPos.y = worldPos.y - ((canvasRect.rect.height / 2) * canvasRect.localScale.y);

//Normalizing to get the edge position
Vector2 normalizedAxis = NormalizeByMaxAbs(worldPos.x * (canvasRect.rect.height / canvasRect.rect.width), worldPos.y);

//Applying back the normalization to the edges and applying the Canvas scale, finally having the arrow position
worldPos.x = ((normalizedAxis.x + 1) / 2) * canvasRect.rect.width * canvasRect.localScale.x;
worldPos.y = ((normalizedAxis.y + 1) / 2) * canvasRect.rect.height * canvasRect.localScale.y;``` That's the main code (edit: comments and format)