#💻┃code-beginner

1 messages · Page 552 of 1

tiny vault
#

thank you SO much!

ivory bobcat
#

Place some logs to see if you're actually getting input

ivory bobcat
#

Did it enter the if statement?

dense anchor
keen dew
#

The most common reason is that the normal movement code also sets the velocity directly which overrides the dash velocity

ivory bobcat
#

Either the statements aren't ever reached, velocity is changed elsewhere, rigid body isn't in the physics simulation or etc

keen dew
#

Also that line is what stops the dashing so if the problem is that it doesn't dash at all then that line isn't the problem

dense anchor
ivory bobcat
#

Is dash duration zero?

#

What about dash direction and speed?

dense anchor
#

and also i stopped walking when dashing

kind skiff
#

I have a very wierd bug that happens with the layer

#

So I have a projectile

#

When I put it in other layers

#

The effects around it will not appear

#

And when I put it inside the default layer

#

It just magically appears

silk comet
#

does anyone knows a bit on photon and ml-agents? I would need help with a little but deadly problem in my "game"

civic cradle
#

Hey friends,
quick question:

I'm setting up a small quiz-game for a local network.
WebSockets and stuff like this are working already, but I don't know how to add the connected player to my text-canvas.

I think it has something to do, that the TextMeshPRO isn't in the update-method, but I wasn't able to find a redraw() or something.
Please, have a look at this:

    public class ChatBehavior : WebSocketBehavior
    {
        protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
        {
            // check if it is a connecting player
            var payload = Newtonsoft.Json.JsonConvert.DeserializeObject<MessagePayload>(e.Data);
            var username = payload.Username;
            var type = payload.Type;

            // add player to list
            GameObject.Find("PlayerList").GetComponent<TextMeshProUGUI>().SetText(username);
        }
    }

is it because I'm not referencing MonoBehaviour in this?

grand snow
# civic cradle Hey friends, quick question: I'm setting up a small quiz-game for a local netwo...

its .text to change the text but why are you using Find() each time... use [SerializeField] to have the tmp text reference or find it on Awake/Start.
If you want to "add" the name you can do .text += username or keep a list of all usernames and re construct the whole text on each connect/disconnect.
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.0/api/TMPro.TMP_Text.html#TMPro_TMP_Text_text

civic cradle
#

i know that. This is something else I have to make nicer anyway. Right now I'm simply lost on why it doesn't update the text.
I think it has the correct value, but it isn't displaying it.

Whole code.
https://paste.ofcode.org/Wz7r4iUyvtJPxMxreibQxm

I'll adjust to make use of SerializeField now, though. Gimme a second

#

I think part of it is also the fact that I have multiple classes in one file

teal viper
grand snow
#

if you have more than 1 monobehaviour in a file it wont work properly or at all

teal viper
civic cradle
#

i mean, I have a GameObject called "PlayerList". This PlayerList has the TextMeshPRO-component.
onMessage() i want to add the playername (taken from an external form-element) in my GO to display it on screen

languid spire
civic cradle
#

I tried, but everytime I set my breakpoint the IDE crashes. not unity in general, only VS 2022 🤷

swift crag
#

what is a WebSocketBehavior?

#

hopefully no relation to MonoBehaviour

grand snow
swift crag
#

That's fine, as long as it's not actually a kind of unity object

#

it appears to be a class from the webshocket-sharp library

grand snow
#

if vs is crashing could be some dumb old mono thing

civic cradle
swift crag
#

I would at least verify that the method is running at all

civic cradle
#

which method? I mean, I verified that it hooks correctly. I can post my WS-messages from my javascript file and unity (the logger) does display stuff

swift crag
teal viper
#

I bet they have an error or a warning about this in the console as well...

civic cradle
grand snow
#

That is true, unity will throw an exception if this happens (using the unity api on another thread) and this is NOT logged in editor, only debugging will let you know this

civic cradle
#

(roughly translates: message recieved: {"Username.....}

civic cradle
swift crag
#

it doesn't matter if some other unrelated thing is working

civic cradle
#

this logging from the screenshot above is placed in onMessage

swift crag
#

Ah, so you just added that

civic cradle
#

no

#

that was there the whole time

swift crag
#
   // Verhalten für den WebSocket-Endpunkt
    public class ChatBehavior : WebSocketBehavior
    {
        protected override void OnMessage(WebSocketSharp.MessageEventArgs e)
        {

            // check if it is a connecting player
            var payload = Newtonsoft.Json.JsonConvert.DeserializeObject<MessagePayload>(e.Data);
            var username = payload.Username;
            var type = payload.Type;

            // add player to list
            GameObject.Find("PlayerList").GetComponent<TextMeshProUGUI>().SetText(username);
        }
    }
#

I am talking about this method.

civic cradle
#

oh, yea. agreed. i got rid of that

swift crag
#

Prove that it is running.

civic cradle
#

i removed the loggers to keep the code simple

swift crag
#

Don't do that.

#

Show us the code you are running

teal viper
#

Never do that when asking for help

civic cradle
#

will keep that in mind. I really thought I would only show the relevant parts. But you are right, that made a hickup where it didn't have to be one

#

one second

swift crag
#

If you knew what was relevant, you would have solved the problem already (:

thin birch
#

Can I ask a question related to the screen resolution? I would like my game to build at a square resolution (960x960) and if possible be risizable but remain at a square ratio... Is this possible?

teal viper
#

Anyways, I still bet it's due to it running on a thread.

civic cradle
swift crag
#

well, now it doesn't set the text at all!

#

that'll sure slow you down a little..

thin birch
civic cradle
#

updated the paste. Please press F5

teal viper
civic cradle
#

and this is the GO I'm talking about

thin birch
swift crag
grand snow
civic cradle
#

weird, should have

teal viper
civic cradle
swift crag
#

yeah, i presume it generates a new path

civic cradle
#

yea, thought "edit" might save the url

thin birch
grand snow
#

I will laugh if username is ""

swift crag
#

You should ensure that username is not an empty string

civic cradle
#

no, it isn't. Let me show you something real quick

swift crag
#

I know that "Username" appears in the JSON

civic cradle
#

as well as in any debug-log i had prior. I isn't in the code anymore, agreed. But I verified the username as well as the type.

swift crag
#

but when software is not working, you must verify every assumption you're making

teal viper
civic cradle
#

it does. Let me see if I can make a quick screen-capture real quick

grand snow
civic cradle
#

maybe easier to visuazlize it

swift crag
#

I do see a ThreadPool in the library's source

thin birch
#

2nd thing it fixes itself in 2 days after restarting it a bunch of times

swift crag
teal viper
#

It's a library non related to unity, so of course it's gonna receive messages on a separate thread.

thin birch
#

ty

grand snow
civic cradle
grand snow
#

reference the tmp text via a serialized field and use .text to make 100% sure its going where you wish...

civic cradle
#

will do

grand snow
#

if all else fails delete and make a new tmp text and assign that and pray it makes it work. I use tmp ugui text all the time but havent seen this myself.

civic cradle
#

i mean, I would assume that since it isn't placed in the update()-method, the TMP simply isn't rerendered.
I could also try to retrieve the text from TMP after setting it and log it. That way I could at least verify, that the TMP holds the correct value.

Because if it does, I would assume the redrawing isn't happening, which makes sense, because why would it

grand snow
#

no changing the text will make it re draw

#

if the text is changed, it will set an internal dirty flag to re build the mesh

civic cradle
#

good to know

grand snow
#

Ideally you would use a debugger to confirm the text property changes correctly

civic cradle
#

on it

#

interesting 🤔

#

 // this here is logged
 UnityEngine.Debug.Log($"Username is: " + username);

 // this isn't
 UnityEngine.Debug.Log("Current Value of TMP: " + GameObject.Find("PlayerList").GetComponent<TextMeshProUGUI>().text.ToString());

 // add player to list
 GameObject.Find("PlayerList").GetComponent<TextMeshProUGUI>().SetText(username);
 
 // this isn't either
 UnityEngine.Debug.Log("Current Value of TMP: " + GameObject.Find("PlayerList").GetComponent<TextMeshProUGUI>().text.ToString());
#

no warning of a null-reference or similar as well. not the static text in the Debug-Log either (Current Value of TMP...)

languid spire
#

NRE in Console?

teal viper
#

I think find and get component would fail on background thread. Though I did expect there to be an error at least.

civic cradle
civic cradle
#

but yeah, that explains it then

grand snow
#

😠 remove Find()

civic cradle
#

i will, i have to restructure it anyway, since I don't want 2 classes in one file

languid spire
#

Cannot use Unity methods on anything but the main thread

civic cradle
#

okay, so to keep thins cleaner then: I simply add my player to a queue or var and make the stuff happen in update() then. That should do the trick.
Basically, onMessage --> call method to add User(name) to a variable and in Update keep track of this var.

That way I can have these things capsuled as well and don't mix them together.

grand snow
#

When i last worked with other threads in unity i had to have a debugger attached all the time to break on exceptions so i could be notified.

#

you can use ConcurrentQueue<> to queue up the recieved messages and parse + use them safely on the main thread (if this is even the cause as you have not confirmed this correctly)

civic cradle
#

Let me clean up the code and verify it. I'll also get rid off find

languid spire
civic cradle
#

Maybe unity is also a bit too much for a game similar to you don't know jack

#

i was initially supposed to be a very very simple gimmick for new-years evening, where people simply open a url in on their phones and get yelled at from some TTS in combination with chatGPT. Then again, can't hurt to at least deepen my understanding of unity when I'm trying to do it this way

grand snow
#

Find() is okay when you start learning but better solutions exist to better reference components, gameobjects and assets

languid spire
civic cradle
#

all right:
i cleaned up a bit, but ended up with warning:

WebSocketServer.cs

// check if it is a connecting player
var payload = Newtonsoft.Json.JsonConvert.DeserializeObject<MessagePayload>(e.Data);
var username = payload.Username;
var type = payload.Type;

GameManager gameManager = new GameManager();
gameManager.playerAdd(username);

GameManager.cs


public class GameManager : MonoBehaviour
{
    [SerializeField]
    TextMeshProUGUI playerlist;

    /* empty start and update methods */ 

    public void playerAdd(String playername)
    {
        playerlist.text = "abab";
    }
}
#

resulting in:

You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script...

#

I also tried making the playerAdd() function static

languid spire
#

So make GameManager a Singleton and add it to an empty gameobject, then you wont need the new()

civic cradle
#

all right

#

interesting. so it does indeed call the corresponding function. it does log my input as well, however, it is still not updating the text-value,
which makes me think that there is something else going on

sterile radish
#

hi, i'm trying to make a random weight system to spawn different platform types for my game which is a doodle jump clone. i was thinking of having a gameobject array of all possible platform types and then spawning a platform from that array based on the rolled weight. however, i also want to take into account the players height (for example, if the player just started playing and they have a low height, i dont want to start summoning all the different types of platforms) how would i implement this?

https://paste.ofcode.org/qJUvU6e9nxMBfiVDD6XPrW

civic cradle
#

maybe something like an array, as you said. Start with 2 plattform-types. upon reaching treshhold 1 (lets say 20m) you push another type into that array. Beginning with the next iteration, it would take a random out of now 3 possible plattforms

naive pawn
civic cradle
#

one last attempt, otherwise I'll let it go:
https://paste.ofcode.org/FUfWfL8XfpsewQ2KMyemrz
So, as suggested, I tried this very basic thing:

In my start()-method, the text is set correctly. It is also re-drawn as expected.
However, it doesn't do anything (except logging) in my addPlayer()-method

grand snow
#

you don't need to access the static reference from a member function but if it doesnt do anything still then put a breakpoint and see what happens (check .text before and after) and make extra sure you arent changing the text state again elsewhere.

#

if VS doesnt work you can try vs code but install the new unity vs code extension + update the vs package in your project

civic cradle
#

it is correct beforehand. it is like it is "failing to achieve to do anything" there

#

the second Log (#43) i also not displayed. No Error, no warning

#

I know that I don't know to access the static ref, but trying go get a clue on this. this very same code DOES work in start()

#

as if there is some kind of return or something, that prevents the code afterwards of being executed.
I can only imagine that it is a problem that I'm calling this method from another script

grand snow
#

if it never logs is probably the other thread problem. if you enable breaking on all CLR exceptions you VS will break and show you when this happens.

civic cradle
#

it logs the first line though

grand snow
#

oh, are any of those things on line 42 null?

civic cradle
#

I can't imagine it, since it is the very same code from start. so Instance.playerlist is bound to the script via [SerializeField].
I'll double check if it is null though

languid spire
grand snow
#

this technically isnt thread safe

languid spire
#

just a test, proof of the problem

civic cradle
#

: o

#

that works

languid spire
#

I thought it might. So you can use the same construction using a thread safe collection like ConcurrentQueue

civic cradle
#

but before I dig into concurrentQueue - why does this work now? Why is this different to my approach?

languid spire
#

becauae playerAdd is being called from another Thread and updating the TMP.text is running stuff not allowed off the Main Thread

civic cradle
#

we checked that TMP is redrawing after a text-change (as seen in start() ) - why doesn't do that in playerAdd()

#

oooooh i see

languid spire
#

Start is run on the Main Thread

civic cradle
#

so what we then do, basically, is to simply set the TMP.text in the main-thread again via update and we simply adjust the memeber-var "text"

languid spire
#

exactly

civic cradle
#

all right, thank you guys so much. I'll look into that concurrentQueue now

naive pawn
languid spire
#

optimization, why do unnecessary work?

grand snow
#

the re assignment each frame would probably re dirty the text (unless they check this internally)

naive pawn
#

i mean i wouldn't think to do that for testing a problem so i thought there was a more specific reason to do it for TMP or somethign 😅

naive pawn
#

fair enough lol

swift crag
#

And if you want to talk to anything else, you need to be very careful about thread-safety

#

(hence using ConcurrentQueue, which properly handles multiple threads trying to interact with it simltaneously)

civic cradle
#

makes total sense

languid spire
civic cradle
#

i was under the assumption that this websocket thing somehow relates to unity

swift crag
grand snow
#

If it was provided by unity or made for unity it would probably not be a problem

#

and setting tmp text surely interacts with some unity api at somepoint that causes an exception (hence it breaking)

swift crag
#

Eventually, yes

civic cradle
#

possibly i simply relied too much on that lib

grand snow
#

and as i pointed out, if not on the main thread it wont log the exception in editor

languid spire
civic cradle
#

in my head, that seemed quite simple, really:
react on a message from a browser (like have a player connect) -> play fancy animation in the game and tell everyone player x joined

grand snow
#

true but why would this suddenly be thread safe? none of unity is except for stuff like the job system

#

My preferred way to solve this issue is using UniTask: (e.g. often mobile ad watch completion events are fired on othre threads)

async UniTask DoOnMainThread(string playerName)
{
    await UniTask.SwitchToMainThread();
    tmpText.text = playerName;
}
languid spire
#

Somewhat of a sledgehammer to crack a nut, no?

grand snow
#

where i work we make extensive use of async code and unitask so it works great
the ad watch functions are awaitable so it fits well.

civic cradle
#

wait, so in that case, instead of having

public void playerAdd() { }

i would have it like this?

async UniTask playerAdd() { }

and I simply let the call from the other script alone? it still calls playerAdd() with the same argument as before?

grand snow
#

yes but dont go using UniTask or async code if you arent familar with it as it has differences to coroutines.
Using a concurrentqueue is a good solution and safe solution to transfer data/work

civic cradle
#

if it wasn't for the fancy stuff I could do with particles, videos or anything similar, i would simply rely on python or so.

languid spire
#

@civic cradle Nice to actually solve a problem posted in a code channel lower than it deserves for a change, thank you

civic cradle
#

lol, i have to thank you 😄

languid spire
#

nah, it was fun

civic cradle
#

well not for me lol

#

that took me like 4h now

languid spire
#

but, next time, you'll know

swift crag
#

well, that'll make sure you remember (:

civic cradle
#

but nice nontheless that it actually works now. at least I learned about this main- and off-thread thing

#

exactly

swift crag
#

If only I could skip straight to the solution every time

#

I'd have my game finished in a month

#

a tool-assisted speedrun

languid spire
#

But then I'd be out of businness

grand snow
#

you guys get paid?

civic cradle
#

the thing is that this stuff demotivated me so much right now. really. having to spent 4h on a task as simple as changing text.
this isn't even something of the stuff I'm more afraid of like networking or distributing data accordingly to every player.
plain, simple text

languid spire
grand snow
#

sold on the asset store? I do mobile games for mine (in unity ofc)

languid spire
#

nah, we license direct to publishers and studios, can't do our business model via the asset store

grand snow
#

sounds cool! I recently saw some horrific code from some thing we bought of the asset store 😐

#

so i have little faith in anything there, thankfully its rare we buy anything with code

languid spire
#

I hate to say it but imo 90% of the code sold on the asset store is horrific

upper prawn
#

How can I save a prefab as a .asset so that I can dynamically load it at runtime? I see there are scripting APIs for saving during runtime, but I want to have them beforehand, and then load them at runtime, almost like a plugin sort of

languid spire
swift crag
#

I see there are scripting APIs for saving during runtime

I'm not sure what you're referring to here

kind skiff
#

Guyss how do I get the previous time? So what i want to achieve here is that I want to get the current time when the button is pressed and then get another time when the button is pressed again then minus the two values to check how much time have passed since the last button press

swift crag
#

look at it later

kind skiff
#

I tried this

                startTime = Time.time;
#

then

#
Time.time - startTime
#

But the amount of time i get keep increasing for some reason

swift crag
#

Show the actual script.

languid spire
#

well thats silly
var dif = Time.time - startTime;

#

but better to use DateTime and TimeSpan classes, that's what they are for

grand snow
#

Time.time seems fine for this as long as you update stuff each time

kind skiff
swift crag
#

notably, if you only set startTime once, it will not behave (:

frail hawk
#

so why was it not working as you wanted

naive pawn
#

probably because they didn't update startTime

upper prawn
swift crag
#

This is an editor method for creating a prefab asset.

swift crag
#

(note that anything inside the UnityEditor namespace does not exist at Runtime)

swift crag
#

you don't load a specific .asset file

swift crag
upper prawn
#

I feel like Resources.Load is the best way to go (without knowing much, just thinking about how I've implemented this in the past lol)
I thought I saw that you can't load FBX files with this though, is that not true?

swift crag
#

That is an unrelated question

#

Resources.Load does not load a file

#

It loads an asset.

#

When you put files into your Assets folder (e.g. an FBX), Unity imports them to produce assets

#

If you put a file into a folder named Resources, Unity will let you load the resulting asset by name

#

The assets are bundled together into large archives that are included with your game. The original files are not included

#

At runtime, your game has no idea how to parse an FBX file

#

Now, there are packages for runtime model importing! But that's a separate thing entirely.

upper prawn
#

Ok I think I'm following. So if I store my prefabs or FBX files in this Resources directory, Unity basically embeds a database of these things.
Then at runtime I could look things up by name. But I -couldn't- modify a text file or add a new model because the directory won't exist at runtime, it'll be embedded in the application

upper prawn
#

Awesome, thanks! I'll eventually want to figure out how to support modding and more things at runtime, but this is definitely good enough to get me going for a long while!

languid spire
uncut depot
#

Hey there! I am trying to do something in unity but I am having a hard time achieving it. I am trying to play an animation when a UI button is clicked(Without any scripts), can someone help me? thanks

languid spire
eternal falconBOT
uncut depot
#

Hey @languid spire , I have no code in the project. What I am trying to do is when the Left UI button is clicked it plays the animation

languid spire
languid spire
west radish
swift crag
#

no, that's fine, assuming you have a material asset named Example

#

(ideally, use Resources.Load<Material>("mat/Example"))

#

My point was just that it's not actually finding a file on your computer with that name

west radish
#

ah, gotcha

swift crag
#

It's looking for an asset based on its path

#

Normally, you can't do that -- you have to serialize a reference to an asset

#

This lets Unity strip assets from the build if they are not referenced

#

anything in Resources is auto-included because Unity has no clue if you're going to load them or not

west radish
#

does Resources have to be placed at Assets/Resources or could I do Assets/myfolder/otherfolder/Resources, not that I ever would

swift crag
#

You can have many Resources folders, and they can be anywhere in the Assets folder

#

check out the documentation for Resources.Load

languid spire
west radish
#

I assumed you could only have 1 folder

swift crag
#

you usually just have one

#

but other packages may include their own Resources folder for their own use

#

Name collisions ahoy

west radish
#

mhmm

languid spire
swift crag
#

I keep my use of Resources to a minimum. I mostly use it to load "catalogs" of configuration assets. I also store small assets that are associated with classes in there

west radish
#

Resources.Load is such a life saver, in the past the one thing that I've always loathed is getting my code to load a file. The naive approach was always to use some awful system.io and to then have to deal with "how do I get the code to understand where the assets folder is located" nonsense

swift crag
#

well, remember, you are not loading a file

#

You are loading an asset.

#

There is no "assets" folder in the built game.

#

That only exists in the editor.

#

You might want to check out the section of the documentation that talks about the asset system

#

it's nice to know wtf is going on in there

west radish
#

I just mean that before I knew Resources.Load existed, to have the code access a texture or anything, meant I had to use the systems io

languid spire
swift crag
#

If you want to load a PNG from the player's computer, that's completely unrelated to loading an asset that you imported back in the editor

#

Both processes eventually give you a Texture2D object

#

But you can't substitute one for the other

west radish
#

oh no in the case of loading a file from the users pc, io would be ideal (like if I had some custom levels stored in some %appdata% directory)

#

but to load a ComputeShader thats located in my project itself, I wouldnt need to deal with any system,IO stuff when I can write TileCompute = (ComputeShader)Resources.Load("compute/TileCompute");

swift crag
#

Yes, and you couldn't do that with a direct file read, full stop

wispy coral
#

do yall know who has good tutorials for everything in unity?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wispy coral
west radish
swift crag
#

That does not exist at runtime.

#

Additionally, just reading that file directly does not give you a ComputeShader. It'd give you...text

west radish
swift crag
#

Again: outside of StreamingAssets (which get copied into your built game), nothing in the Assets folder exists in the built game

#

Those files got imported to produce artifacts, which then get glued together into large asset archives

#

There is no "Example.mat" file in your built game

west radish
#

I recall in the past trying to put stuff into some appdata directory, because I knew that folder would be created when the game runs, and storing stuff in there meant I could get """""easy""""" access to files that could be loaded in the code

swift crag
#

screaming

west radish
#

I know better than doing anything like this now

swift crag
#

There is the persistent data path

#

This is an appropriate place to store things like save files

#

I also dump debug data there

languid spire
#

Also, persistentDataPath is the only path where you can use System.IO access on all Unity platforms

swift crag
#

mobile devices are very strict about that

#

unlike on other platforms, where you can ransomware the entire computer at all times

#

😉

west radish
swift crag
#

hello how do i encrypt computer, i mean save file

languid spire
west radish
#

one dude was asking how they could get the game to download files to the users pc to get the game to read them, when pushed for the reason, he kept skirting around the answer

swift crag
#

i need some "DLC"

unborn urchin
#

when adding sprite renderer to an object and dragging an image into it, then adding box collider 2d, how come changing the size in box collider isn't changing the size of the picture?

#

in the tutorial im watching it does

languid spire
#

I doubt it, the 2 are unrelated

unborn urchin
#

thats what i was thinking i didnt know how that worked in the video

#

16:58 sorry

cosmic quail
unborn urchin
#

i get that and it makes sense, but in the video the image just randomly changes sizes

#

when hes changing the size of box collider not sprite renderer

magic panther
#

I'm making an audio system, but I don't feel like making a bunch of AudioClip variables, so I wanna try to attempt it like this: When a sound needs to be played, I wanna pass in a sound from some kind of directory. I have no idea how I could do that. Like, pass in a AudioDirectory.clipName, it finds the according file by it's path and plays it. What's the best way to go about something like this? Or is this a very bad way to do it, in that case what's the best way for a no variable audio system (No variable as in there's no need for a singleton object with the clips stored in variables or stuff like that)?

languid spire
#

No, you are misinterpreting what you are seeing, all he is doing is changing the collider

magic panther
floral estuary
floral estuary
unborn urchin
floral estuary
# rich adder huh ?

Addressables are still going to make him assign his variables the same way

cosmic quail
magic panther
rich adder
unborn urchin
#

mine goes like this his goes like this

floral estuary
cosmic quail
# unborn urchin 17:05

it doesnt change size for him though. just the box collider. and then he moves the image up

unborn urchin
#

ive never gotten into game design before, ive always just coded. this is all new to me sorry if im slow lmao

cosmic quail
sterile radish
#

hi, im making a doodle jump clone and i have different types of platforms that behave in different ways. i was thinking of creating a seperate script for each type of platform cuz i have only like 3 types of platforms in my game. is that efficient? or is there any way i can optimize this?because all the platforms scripts would look pretty much the same it's just the stuff that's changing in the oncollision method

floral estuary
# rich adder Addressables are literally Resources.Load but better

I get that but Addressables is a whole other system. It's usable in this context but using it does not inherently fix the issue this person is having. I suppose you CAN use addressables from asset path but I think most people use AssetReference or AssetReference<T> at which point you're suggesting replacing Resource.Load with something you consider better, but that doesn't address the issue at hand imo

magic panther
languid spire
languid spire
#

no it's not

unborn urchin
#

oh this is

#

lol

magic panther
floral estuary
unborn urchin
floral estuary
#

Do you want to avoid all Unity objects or just MonoBehaviour/Component types

floral estuary
#

It sounds like what you want is to make a ScriptableObject and have it reference a bunch of AudioClips. Then anything that needs those clips can just reference the one "database" scriptableobject and grab it from there

ivory bobcat
magic panther
# floral estuary What kind of object do you want?

No, look, I need some kind of file that stores a path and codename for each audio file. That way I can use a AudioManager.GetClip(codename) function or something like that which grabs the file, finds a matching codename, Resource.Loads the file from the path, and if it exists, returns it, otherwise throwing an error.
"some kind of file" being my problem

floral estuary
floral estuary
magic panther
#

I think I look like an idiot right now, I'm just really lost, I'm not sure if this is the right way to go about it, because learning from my 6 months of game development, usually with any newly learned feature comes some evil backstabbing twist

floral estuary
#

You don't look like an idiot, I'm speaking a bit advanced cause I'm having trouble gauging your development level don't worry about it! Okay here's my suggestion give me a second to type

magic panther
#

np, brb 3 mins

floral estuary
#

so first we have these things called ScriptableObject. It's a class you can inherit from like MonoBehaviour but it basically just holds data. But it holds it in a way you can have that data sit as an asset in your project files.

#

So before we dig deeper, you're wanting to set up a string-string relationship. You want to give it a string for some codename of a file you want, and you want to get back a string telling you its full path. There's a few ways to make that dictionary, since Unity inexplicably is incapable of serializing one of the most important collection types in 2024 :p

swift crag
#

My suggestion would not involve path names at all.

#

Consider the following

stark rune
floral estuary
# swift crag My suggestion would not involve path names at all.

Mine wouldn't either, but as a newcomer to anything I find it frustrating when I wanted to work on something and people just kept telling me not too XD so I'm gonna lay out how to do this but I suggest you listen to Fen @magic panther I think they seem to be on the same thought wave as me

swift crag
#
[CreateAssetMenu]
public class AudioSet : ScriptableObject {
  [SerializeField] private List<AudioClip> clips;

  public AudioClip GetClip() {
    int index = Random.Range(0, clips.Length);
    return clips[index];
  }
}
cosmic cargo
#

hey every1 i have done some basic projects in unity, Now i want to learn how to create opponents with different moveset and how they use them for a combat (GoW kinda) can sm1 recommend me some resources for the same

swift crag
#

This defines a new kind of asset.

#

You can create it in the Project window, put audio clips into it, and then, crucially....

#
public class Whatever : MonoBehaviour {
  [SerializeField] private AudioSet clickSounds;
  [SerializeField] private AudioSource source;

  public void ClickHappened() {
    AudioClip clip = clickSounds.GetClip();
    source.PlayOneShot(clip);
  }
}
#

No strings!

floral estuary
#

mmmmm I don't like this, they're supposed to reference all audio in their game by an index number? That's not very readable

swift crag
#

You just assign a reference to an AudioSet asset in the inspector (along with an AudioSource component in the sc ene)

floral estuary
#

and if one thing gets switched you could likely just never notice

magic panther
#

I'm back, is there a lot to take in?

swift crag
#

GetClip just picks a random clip from a list

floral estuary
#

right but obviously that's not what they're trying to do

swift crag
#

I don't see why you can't just reference an AudioClip if all you need is a single piece of audio.

#

it will be simpler and much more reliable than typing in a name and hoping you never get it wrong

floral estuary
#

aw don't scathe the guy for wanting centralized audio management it's somewhat understandable. Though probably less helpful in the long run than one would think, but let the dude work on his project haha

swift crag
#

The point of Resources.Load is that you can find assets without having to store a reference.

If you can store a reference, just do that.

wintry quarry
#

Not only that, Resources.Load doesn't even have any memory advantages. It loads the things up front.

swift crag
#

Loading things by name should be a last resort, not your first choice.

floral estuary
#

ANYWHO

swift crag
wintry quarry
ivory bobcat
swift crag
#

You can move the asset around and forget to update the name.

swift crag
magic panther
floral estuary
swift crag
#

😉

ivory bobcat
#

Fen beat me to the punch line

floral estuary
#

mmmmmmmk

elfin knot
#

If you wanna load by string and not have to have the clip loaded in memory at load you could use addressables 😅

floral estuary
#

quite the scathing thing to say, the practical use of that "burn" may vary

swift crag
ivory bobcat
rich adder
#

lmao

magic panther
#

My whole idea is to mask Resource.Load<AudioClip>("path") under something more managable (using resource.load would require me to jump around my code changing the path whenever I move a file elsewhere. I'd prefer changing the path once in some central thingy)

floral estuary
swift crag
floral estuary
#
public AudioClip myClip;
public AudioSource source;

public void Awake() {
  source.PlayOneShot(myClip);
}```
swift crag
#

I have very few string keys in my code

wintry quarry
swift crag
#

Most of them are default values for LocalizedStrings so that they start out with the right table

magic panther
rich adder
#

jesus..

swift crag
#

Start making lists!

floral estuary
#

public List<AudioClip> playerLandingAudios

swift crag
#

If you ever find yourself writing this:

int foo1;
int foo2;
int foo3;

...then you need a list

naive pawn
#

anytime you have symmetric variables, you want a list

floral estuary
#

public List<AudioClip> playerShootAudios

magic panther
#

But won't that mean I need to find them by [n]?

swift crag
#

So what?

#

Pick a random one

#

Presumably you're already doing that, in a much more painful and roundabout manner

elfin knot
#

Dictionary<string, AudioClip> Clips;

sadok

wintry quarry
floral estuary
floral estuary
magic panther
naive pawn
swift crag
elfin knot
swift crag
#

Just serialize a List<AudioClip> for each kind of sound. You can do even do that if there's only one audio clip -- a list of one element is fine.

floral estuary
# elfin knot Need Odin 🫣 😭

Or CustomInspector or a number of other tools, but I haven't been able to explain Serialized Dictionaries without the dreaded "you're going about this all wrong just don't do what you're doing at all" which obviously is a great learning experience XD

ivory bobcat
# elfin knot Need Odin 🫣 😭

There are free and paid third party assets for serializing dictionaries if needed but they ought to just move away from strings overall.

rich adder
floral estuary
#

unfortunately it tends to happen in a room crowded with talented devs

naive pawn
magic panther
#

Alright, so a list of audioClips. Is making a SO that I can access via AudioClips.name straightforward?

swift crag
#

No more names!

naive pawn
#

for safety in that format you'd need a dict of enums to lists of clips, which is.. quite unnecessary, but i mean, if you want it, i guess

swift crag
#

You have a List<AudioClip>. You don't care what those clips are called or how they got put in the list

#

Pick a clip from the list and play it. That is it.

#

The clips could be named "FLORP" or "Dont Play This Oh My God" or "3"

#

You simply do not care

magic panther
swift crag
#

Pick a random number.

floral estuary
#

he shows you how to pull a random clip from a given list

swift crag
#

Write your code so that it simply does not matter how many clips there are

floral estuary
#

random number from 0 to the max index in the list

ivory bobcat
magic panther
#

New C# file, paste this in?

swift crag
#

I am simply explaining how to pick a clip from a list of clips.

elfin knot
#

Yes but I think he wants to be able to play the clips programatically without having to explicitly choose the clip.

private Dictionary<AudioType, AudioRetriver> _audioClips;

public void Play(AudioType type) {
  _audioClips[type].PlayRandomClip();
}

So how can he define the data without some identifier for the type (string, enum, type value, etc)

floral estuary
swift crag
#

too many cooks, yes

ivory bobcat
swift crag
#

let's do a thread. i will explain the simplest option.

magic panther
#

This might be a lot to ask, but a step by step in one message would probably be the best to clear this up

#

yeah

naive pawn
swift crag
#

picking random clips

floral estuary
#

there's the self-appointed alpha in the room "let's make a thread and I'll be the one do it" XD okay I'll leave you to it

ivory bobcat
#

They're reducing clutter, it's a perfectly valid response

swift crag
#

Executive decision 😄

floral estuary
#

My point is when a beginner asks a question, it's a good time to answer their question. Telling them they shouldn't be doing the thing the way they're doing it at all immediately feels bad for learning to me. I would rather answer the question they asked, then suggest that "hey that's probably not the best way though".

#

Like you might think abstract scrob events are the best way to organize a project, but if someone is just trying to spawn their enemy I don't think we should be talking about that :p you can answer the question then lightly suggest a different approach than the one they now understand

naive pawn
floral estuary
naive pawn
#

this even happens when the cleanup is in the same message, rarely, but it does happen

floral estuary
#

I don't think that has to do with what I'm saying, yes internet people can be lazy but I don't see how that pertains

#

I don't think you're ever gonna push a copy-paster into being a real coder by way of teaching them best practices

naive pawn
#

they do come back and necessitate cleanup afterwards when it's been expanded on

floral estuary
#

in that situation that person has chosen their path :p

naive pawn
#

so in my experience, telling them that it's a bad path upfront tends to be more productive long-term

ivory bobcat
#

Imo, it doesn't matter how it's presented. The matter of importance is with enabling the individual to complete their task in the simplest yet correct way. I try hard not to support ill use tools or practices that'll have others needing to fix said bandaids in future tasks.

naive pawn
#

im not against actually answering their question, but sometimes that's not the most important part of actually telling them what they need to know, xyproblem and everything

floral estuary
ivory bobcat
naive pawn
#

but excess technical debt is a something worth fighting for imo, especially when it's a core concept

#

literally something being done for them

#

if they don't know about it, it's gonna be a lot more painful than it should

magic panther
#

But in a "Not how it's usually preferred to be done" rather than a "It's objectively a horrible way to do it" (unless it actually is)

naive pawn
#

that pain without knowing there's an out seems to be more draining/burnout inducing

floral estuary
#

I mean clearly everyone is against my side of this debate here, but I've been a coder trying to learn something, came up with a small learning project, and been told "don't do any of that here's this simple thing or 3rd party thing that does it all for you cause why are you doing that" at which point I do nothing because the whole learning experience I designed is apparently just a button click, when there were still valuable and relevant things I could have learned from that experience

#

I just think the best response to a beginner asking a question is usually to first answer the question

swift crag
#

you do not know what you do not know

#

"unknown unknowns", perhaps

naive pawn
#

of course there are valuable things to learn in every path, good or bad
but you have to weigh:

  • how valuable is it to their overall learning, as a beginner?
  • how valuable is it to their immediate task?
  • how valuable is it to their long-term task? (ie, the game)
  • how much time/focus is it going to take away from the stuff more relevant to the above 3?
    stuff about performance or optimization tends to not be ideal for beginners just learning how to do stuff
    sometimes you don't need to learn it; sometimes you can't learn it yet without the necessary experience to understand it
floral estuary
#

But you also have to consider how likely this person is to learn about serialized dictionaries in a later scenario. Not SUPER likely I'd bet. Will serialized dictionaries be helpful? almost certainly. How likely are they to hear that they shouldn't reference things by string? It's certain. Look how the room swarmed around it.

This person could have learned how to string,string reference things, one of the most lacking/broken oft-needed features in Unity, as well as that they don't need to use strings for AudioClips.

Instead, they just learned the more obvious thing because people solved their problem instead of answering their question. I'm not saying it's not important to learn or note not to reference things by string, but that other information would have also been invaluable, and I feel like I was like "okay hang on let me type a full explanation", and everyone was like "no I can type a quick explanation of a whole different approach much faster than you can do that" :p which is frustrating tbh

naive pawn
#

ok im confused, dicts were only recently mentioned, weren't they?

floral estuary
#

One might think, I haven't been able to say much of a word about them XD

#

but no I mentioned them early on

naive pawn
#

ah, i mustve missed that while backreading

floral estuary
#

all good, again it devolved into a discussion on best practices which is part of the frustration

naive pawn
#

i mean, that's quite a natural progression from several variables, so i dont' see how that's not super likely

floral estuary
#

I feel like the core of what I'm saying is being glazed over

swift crag
#

Oftentimes, the original question is not the correct one.

naive pawn
#

i think the divide here (i mean, between your stance and the rest of us) is kinda over a subtle difference: useful overall vs useful now
i don't think any of us think string references aren't important or anything, but it's less important to their development as a beginner, since direct references are more typically used
i don't think any of us would object to an explanation of string references, but more about presenting that explanation as an answer to the problem (vs an answer to the question)

swift crag
#

Finding that "true question" is challenging.

#

And I think doing so is a vitally important part of pedagogy

#

(ooh, five dollar word)

naive pawn
#

if they don't know normal references, and are then taught string references, then, well they'd probably just keep using string references
that's gonna be a pain both for them and future helpers

#

but of course, quick discussion throws all that nuance out

floral estuary
#

If a person asks a question and we tell them best practices instead, they didn't learn the thing they wanted. If a person asks a question and we tell them best practices, and then someone else says no that's not the best way, and then we all argue for an hour, they learned nothing and they probably leave.

I've left modding communities as a whole (cough minecraft) because I wanted a specific piece of information and I could NEVER get that information I wanted to learn without "WELL WHAT ARE YOU TRYING TO DO" with 800 different opinions on how I should go about it instead of learning what I wanted to learn. It's honestly infuriating sometimes. Beginners are often not trying to accomplish something, they're usually just trying to learn.

wispy coral
#

dose anyone know where to report problems with the unity learn courses?

ivory bobcat
#

From what I've seen, there were two underlying concerns. The first being a means to prevent needing to rewrite code in the case that sources are modified (placed elsewhere). The second is with the means of accessing the data. The first is a given that the individual should use a manager to remove management responsibility from individual scripts. The second was where folks would suggest using an alternative to strings (the actual clips themselves to prevent errors) - they would be working with some other identifier instead (indices with fens suggestion).

floral estuary
swift crag
#

we disagree with your point

naive pawn
floral estuary
naive pawn
#

im not sure what the core point is
if it's this

If a person asks a question and we tell them best practices instead, they didn't learn the thing they wanted.
i do disagree, yeah
especially in the context of beginners, where "asking the right question" is not a developed skill yet

rich adder
wispy coral
floral estuary
#

I mean what's the line on this

#

there's always easier ways to go about things

#

obviously the line is somewhere before "use unreal engine, it has that built in"

#

but where do we land on suggesting a beginner who's trying to learn to code just use a third party asset?

naive pawn
#

industry standard, probably

floral estuary
#

kind of an ambiguous term, though, seems like it would lead to a room of people yelling over each other about the best way to go about things

naive pawn
#

if they know enough to not want that and learn what that does for themselves, then kinda sounds like they're not a beginner anymore

floral estuary
#

I guess a main thing is if you answer their question, we're all answering the same question. If you try to answer their intent, we're all answering what we think their intent is and it's loud.

swift crag
#

If we only ever answered the original question, without doing any digging, we'd be doing a disservice.

naive pawn
#

if they're a beginner and they want to learn to code, in general, and there's a widely-used third-party asset that makes life easier, well, they have bigger fish to fry than remaking that asset

#

IDEs and LSPs are third-party assets

swift crag
#

We'd be reduced to an autocomplete engine.

#

I disagree very strongly, on a philosophical basis, with this idea

ivory bobcat
#

Either be responsible and create a thread to attempt writing-for-them-code or guiding them through the process (hand in hand). Or provide information as correctly as possible, knowing that they'll struggle but hopefully pickup better practices.

naive pawn
#

writing-for-them-code
uh, spoonfeeding?

#

we have a word for that, and it's discouraged

ivory bobcat
naive pawn
#

that just deprives them of the oppurtunity to learn

floral estuary
swift crag
#

These are identical responses.

floral estuary
#

they are absolutely not

swift crag
#

the first one is just wrapped in bubble wrap

#

along with an unnecessary detour to something that's a bad idea

floral estuary
#

those are logically and socially completely different

#

okay dude I'm done

ivory bobcat
naive pawn
swift crag
#

I misread the first option. I see.

#

I would not immediately provide an implementation I consider to be a bad idea.

floral estuary
naive pawn
#

i mean i wasn't here for the initial convo so i can't comment on that

wispy coral
#

I have 0 prior experience on how to code and if someone offers me the better way of how to make, i dont know, a fps player controller script i will go for the better way of doing it

frosty hound
#

How can someone offer a better way if they haven't seen your original way?

warm maple
#

So I'm not really sure if these types of questions can be answered here, or are the right place to ask, but I wonder how certain functions like sin/cos/tan work in a gamedev perspective? For example if I wish to create a circle that keeps repeating itself, with how do we keep the particle going? Do we typically use a while loop for that to make it infinite?

swift crag
#

So, each time the method gets called, you're one frame ahead from last time

#

Time.time has gone up by a little. Other objects have moved around.

floral estuary
wintry quarry
# warm maple So I'm not really sure if these types of questions can be answered here, or are ...

how certain functions like sin/cos/tan work in a gamedev perspective

They work the same way they work everywhere else in the world. Sine is: angles in, a value between -1 and 1 out

For example if I wish to create a circle that keeps repeating itself, with how do we keep the particle going
THis is really a question about "how does the game loop work, when does my code execute" etc, than any thing to do with math functions

#

but "circle that keeps repeating itself" is pretty vague

floral estuary
#

To be honest most people in Unity wouldn't use sin though. They'd probably have the thing rotate in Update() and just have it always moving in its forward direction.

warm maple
wintry quarry
#

just updating the object's position in Update, based on the result of sin/cos(time)

#

also there are multiple functions at play here

floral estuary
#

I didn't think it was vague. We have an Update() method in unity that is always going off, so we don't necessarily need a loop

wintry quarry
#

one determining the height of the object, and one determining its position on the x/z horizontal plane

#

Anyway yeah this is really just a "how does Update work" question

#

the trigonometry is a red herring

swift crag
#

Right. There are quite a few ways to get that movement.

wintry quarry
warm maple
swift crag
#

I'd go with what Chloe suggested. I actually do very little trig in my code...

#

Unity provides many useful methods for performing movement and rotation

wintry quarry
warm maple
#

Kind of how we could make a function f(x), and for each x, it would have a different position

gilded canyon
#

has hatebin closed?

wintry quarry
#

(this doesn't handle the up and down, just the circle)

swift crag
#

If you can explicitly calculate the position based on the time, then it'll be great

naive pawn
#

well first decide how you want to make it move
you could make it modify the existing position, or directly set its current position
the former would be just rotating and then stepping forward
the latter would be using trig

swift crag
#

This makes sure you don't get little errors that build up over time

#

Closed-form functions are great

warm maple
rich adder
gilded canyon
gilded canyon
#

ive set a condition if hit is null

#

with else

rich adder
gilded canyon
#

i see lemem try smth

#

yup fixed

#

i just didnt clock in that it would try to access somethin that doesnt exist

rich adder
gilded canyon
#

will do

thin birch
#

Hi, how can I use a TMP object in the game world and not in the UI?

naive pawn
#

put it in a canvas that's set to world space

slender nymph
#

or use the TextMeshPro object that is explicitly in world space already

verbal dome
#

PIck GameObject > 3D Object > Text Mesh Pro from the menu

thin birch
verbal dome
#

I'd guess it works fine in 2D, try it

slender nymph
#

i imagine it probably doesn't play perfectly with the 2d sorting, but that's the only thing that wouldn't work about it in 2d considering 2d is still 3d. the only major difference between 2d and 3d are the physics engines used

thin birch
#

gotcha ty

gleaming plaza
#

idk what I'm doing wrong

slender nymph
#

seems like you may have your own class called GameObject for some reason

ivory bobcat
#

UnityEngine.GameObject laser;
but preferably don't use the name GameObject

slender nymph
#

look through your own code and find out?

#

or better yet, right click the GameObject type in the laser declaration and go to the implementation

ivory bobcat
#

Unless VSC is just misconfigured and throwing improper suggestions. I'd check the console errors from the Unity Editor UnityChanThink

polar acorn
#

Don't make scripts with the same name as unity classes

gleaming plaza
#

one of my scripts had a class called GameObject idk why the heck it was called that

gleaming plaza
#

the script is called Laser, idk why the the class wasn't called that

thin birch
#

yea renaming a script keeps the class name as it was before suespicious

rich adder
#

Yeah renaming the file won't affect class

gleaming plaza
#

I don't remember ever creating a script called that, but I probably did by accident

burnt vapor
#

Unity automatically renames the files because if it did not, renaming would break the script since Unity requires both to match

slender nymph
#

unity doesn't automatically rename the class, and it's up to the IDE's refactor tools to rename the file when renaming a type. also as of 2022.2 the file name and class name are not required to match

dark cape
#

Does anyone know how to get rid of the grayed out code suggestions in visual studio?

naive pawn
steep rose
#

I thought that was intellicode

slender nymph
#

that's intellicode, not copilot

dark cape
#

I think I found the option

wispy coral
dark cape
#

but I also thought that 3 other times

#

I think this gets rid of it

naive pawn
slender nymph
#

dunno, i don't use copilot. but that is 100% the default behavior of intellisense

steep rose
#

co pilot is like gpt and just gives you code I believe (just a guess), intellicode just guesses what you want

wispy coral
#

if i disable intellicode it will just not give me more suggestions for code?

slender nymph
#

you'll still have intellisense which is separate

zenith cypress
#

intellicode is the in-line LLM suggestions. intellisense is your autocompletion stuff.

wispy coral
#

alrighty

oak cloak
#

every time i bake my Lighting it crash

slender nymph
mighty compass
#

anyone using c++ here in unity? how do you do it

naive pawn
#

uhhh why do you want to do that

mighty compass
#

lower level language, has its advantages

slender nymph
ivory bobcat
#

What specifically are you targeting from c++?

mighty compass
#

networking

#

client/server interactions

ivory bobcat
#

Doesn't seem exclusive to c++. If you've already got ready made binaries, you could probably import the dll.

mighty compass
#

kk

grand snow
#

ofc you need to compile for each platform you desire (though android/ios can be compiled for you by unity if the src files are included, not sure about others)

covert flower
#

not 100 percent sure if this is classed as beginner but i followed the documentation i was using to the letter and idk how to fix the error

frosty hound
#

Why do you have = at the end there?

ivory bobcat
#

A value cannot be assigned another value. The thing on the left side of the assignment operator needs to be a variable to be assigned the value on the right side of the assignment operator.

#
name = "Bob";//valid
"Bob" = "Steve";//invalid
GetName() = "Jones";//invalid```
grand snow
covert flower
#

ty guys the video stupid mistake lmao

mighty compass
#

how can I check if a Ray intercepts with an object?

#

nvm i found the RayCast class

cosmic charm
paper sable
#

hey guys, im watching a video about handling slope movement, i've followed all of the steps but my character automatically jumps off the slope when i enter it for some reason, i dont think i've done anything wrong, so i dont really know why this is happening. does anyone know why this may happen? this is the code that handles slope movement:

    private void HandleMovement()
    {
        moveDirection = orientation.forward * moveInput.y + orientation.right * moveInput.x;

        if (OnSlope())
        {
            rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 20f, ForceMode.Force);
            print(GetSlopeMoveDirection());
        }

        if (grounded) rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        else rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
    }

    private bool OnSlope()
    {
        if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerObject.localScale.y + 0.3f))
        {
            float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
            return angle < maxSlopeAngle && angle != 0;
        }
        return false;
    }

    private Vector3 GetSlopeMoveDirection()
    {
        return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
    }
cosmic charm
# cosmic charm I don't know why but sometimes the character stops moving even when i'm pressing...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CentaurMoveState : CentaurGroundedState
{
    public CentaurMoveState(Centaur _centaur, CentaurStateMachine _stateMachine, string _animBoolName) : base(_centaur, _stateMachine, _animBoolName)
  {
  }

    public override void Enter()
    {
        base.Enter();
    }

    public override void Update()
    {
        base.Update();

        centaur.SetVelocity(centaur.moveSpeed * xInput, centaur.rb.velocity.y);

        if (xInput == 0 || centaur.IsWallDetected())
            stateMachine.ChangeState(centaur.idleState);
    }

    public override void Exit()
    {
        base.Exit();
    }
}

this is my move state, some how the xInput is getting updated to 0, and idk how

#

or the mvoeSpeed

north kiln
#

!collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

kindred cedar
#

am i able to ask for help on a script in here>

green flame
#

Hello! I don't know what I have forget in my code someone can help me ?

I have this script:

#

And I created a scriptable object in the assets folder like this:

#

But when I log it in like this in my first script:

#

I log "Null" 😦

ivory bobcat
#

It should have a game manager component with a game data field.

green flame
#

Yes

#

Here is

ivory bobcat
#

So it's None right now aka null

#

Make it not None or rather, where do you assign it a value?

green flame
#

Gamedatas should have default value instead of this :

ivory bobcat
green flame
ivory bobcat
#

It's a reference type so it should not have a default value.

#

Use your scriptable object to create a scriptable object instance.

#

You should be able to create a last game data scriptable instance asset

#

It would be under the menu Scriptable Objects as you've set

#

After you create that instance, reference that instance by dragging and dropping it into the field that has None.

#

These SO instances would be like component objects but not in the scene and without needing an object to be attached to - unlike regular components.

#

Basically asset components

#

I've got to run, good luck.

green flame
#

Ty i'll look at this !

ivory bobcat
# green flame Ty i'll look at this !

Random youtube video that had the creation of a scriptable object instance https://youtu.be/0IrWYG4JdHo?t=104
Yours would be at the path you specified - at the top of the list normally in your "Scriptable Objects, ..." submenu and would be named "LastGameDatas".

Learn the basics of implementing Scriptable Objects in 3 minutes! This does not go over every detail of the script, it is meant as a quick resource to get started with Scriptable Objects.
---LINKS ---

Unity 3D game engine: https://www.unity.com/

#unity3d #unity3dtutorial #tutorial

▶ Play video
green flame
#

The workflow is not very user friendly but now I know :3

ivory bobcat
#

Think of the original SO script that you've typed as a template for creating many instances as assets. The SO script is an asset as well but just the template for creating many others. Useful in the case that you've got a lot of objects in the scene that need their own unique SO instance.

tight latch
#

so Im making a 2d game as practice and i don't know how to make my line i draw collide with my player so it doesnt just fall through(I don't really know which collider to use i think)

brisk oasis
#

After a lot of hard work, I finally figured it out. Thank you for your advice!

#

It is for my third game only but I like to challenge myself

proper needle
#

how do i call an objects own tag in unity?

#

if i wanted to put the same script on a bunch of different objects

sterile radish
#

hi, im making a doodle jump clone with different platform types with different behaviours. i want to make seperate scripts for each type of platform but i dont want to copy a big collision code chunk thats the same for every platform into each platform script. is there a more efficient way to do this?

steep rose
brisk oasis
#

Of course

proper needle
#

how do i call an objects own tag in unity?
if i wanted to put the same script on a bunch of different objects

north kiln
#

what does call mean

tulip nimbus
#
 public GameObject prefab;
 public Vector3 origin;

 private void OnTriggerEnter(Collider other)
 {
     for (int i = 0; i < 10; i++)
     {
         StartCoroutine(wait1());
     }

     Debug.Log("Triggered!");
     

 }

 IEnumerator wait1() 
 {
     yield return new WaitForSeconds(1f);
     Instantiate(prefab, origin, Quaternion.identity);
     

 }

What can be done here? I want to instantiate a prefab 10 times every second. However this seems to fire all at the same time

north kiln
#

you're running 10 identical coroutines at the exact same time

#

Either add the loop inside the coroutine, or pass a different delay/wait into the coroutines you start.

polar acorn
tulip nimbus
polar acorn
tulip nimbus
#

this is just to test scripting since id like to make a gun that shoots a salve later on that only needs one button press, but shoots rounds delayed

polar acorn
#

You said you wanted to spawn something 10 times, every second

tulip nimbus
#

my bad!

#

very poor wording but i meant spawn a prefab once, 10 times, every second

signal mango
#

So you want ten spawns, spread out over a second

#

Not ten spawned immediately each second

tulip nimbus
#

yup! each spawn with a duration of 1s

signal mango
#

That seems to be what your code above does, it will create ten "spawner" coroutines that each wait one second before spawning

#

They will of course end up spawning at the same time since they all started at the same time, and all wait one second

#

Do you want some kind of randomness added to the timer or something?

teal viper
tulip nimbus
signal mango
#

Oh I think I get what you wanted now, you want ten spawns where each one waits one second after the previous spawn

tulip nimbus
#

ya you were all kind of right, i just had to put it in the for loop

signal mango
#

In that case yes, putting the loop into the coroutine itself would work:

private void OnTriggerEnter(Collider other)
{
    StartCoroutine(DelaySpawn(10, 1));
}

private IEnumerator DelaySpawn(int count, float delay)
{
    for (int i = 0; i < count; i++)
    {
        yield return new WaitForSeconds(delay);
        Instantiate(prefab, origin, Quaternion.identity);
    }
}
sterile radish
#

why doesn't my cracking platform detect that the player is colliding with it? my player has a box collider 2d and a rigidbody 2d. and my cracking platform has an edge collider with a platform effector. the edge collider is set to trigger.

https://hastebin.com/share/usetutokow.csharp

sterile radish
stuck rampart
#

Was working fine just a few mintutes ago, not sure what I touched: "UnassignedReferenceException: The variable combineParents of MeshCombiner has not been assigned. You probably need to assign the combineParents variable of the MeshCombiner script in the inspector." Please help im new to unity and not good at programming in general. im using the kart microgame scripts if that helps

#

i tried to make a pit-limiter kinda thing in my racing game but it didnt work so i deleted it and now this, it was seperate so i dont know what happened

slender nymph
#

You probably need to assign the combineParents variable of the MeshCombiner script in the inspector

wispy coral
#

how do i reference a variable that's in my script but i changed its value in another script

stuck rampart
slender nymph
#

search your scene using t:MeshCombiner as the search term

stuck rampart
#

@slender nymph i found it, but where do i assign combineParents now?

#

sorry if this is a really dumb question 🙏

verbal dome
#

Is combineParents a list or array?

#

How could it be null 🤔 Unity should initialize serialized lists/arrays automatically

#

(Not a question to you YaoMing, just wondering)

verbal dome
#

Clear your console and enter playmode again

#

See if the error still shows up

stuck rampart
verbal dome
#

Open this and show what is inside

slender nymph
#

and make sure you're doing the search at runtime when the error actually appears

stuck rampart
#

its 6 and has 6 emptys

verbal dome
#

Oh and check for instances of meshcombiner in playmode

stuck rampart
#

wait

stuck rampart
slender nymph
#

i am aware. but you searched the scene after you left play mode

verbal dome
#

You can hit pause and then search

stuck rampart
#

it did the error pause thing

#

automatically

verbal dome
#

You can toggle that off in the console

#

But thats fine

stuck rampart
#

what would happen if i set the value to 0 and didnt use it?

#

is that even possible 💀

#

im not sure what i had combined

verbal dome
#

We dont know what the meshcombiner component does but sure

#

Currently it has 6 empty elements anyway

stuck rampart
#

wow it worked

#

will this cause any problems later on? this part of the game is from the unity kart thing so idk

mighty compass
#

Ive got this basic class that is assigned to each building object that I place, Im trying to make the doors toggleable (open/close), if im making am ultiplayer game, where should I have the door logic, where should it check if a player has tried to open it

verbal dome
#

No comments on multiplayer, but it is common to have your class implement an interface like IInteractable, which could have a Use method for example

#

Your character can raycast or do some other physics query to find the object it is aiming at

#

Then you'd try to get the IInteractable interface with TryGetComponent

#

If you find it, call Use on it

#

I'm sure this is a well covered topic if you look online

teal viper
eternal falconBOT
mighty compass
red harbor
#

Guys i have a question about setting up cam with cinemachine , can i ask it here

stuck rampart
round scaffold
#

Hi, im making a 3rd person movement where the player moves in the direction of the inputs oriented by the direction the camera is moving, (gta movement for reference),

im trying to make the player move via rb.AddForce (since im used to using that for movment) in the same speed regardless of the direction the camera is facing,
I need help with the math that applies the speed in the correct direction, the current bug is
when i look in certain directions the speed would go up to 200-300, and then be normal in others
https://paste.ofcode.org/xgQGBkSAft7pEV7HghPP2P
the code block is just a function being called in fixedUpdate please help me its been hours :((

#

im fairly new to 3d sorry if this is something simple lol

verbal dome
#
 float currentVelocity = rigidBody.linearVelocity.z;```
You are only using the Z axis here 🤔
#

Perhaps you want linearVelocity.magnitude?

#

FYI, linearVelocity is in world space, not relative to the rigidbody

round scaffold
#

i could kiss u , consentually

#

i had converted the formula to use floats so i can multiply it by the direction

#

compeltely forgot about it

#

it works thank u

magic panther
#

How do you guys recommand I do my configuration files? So far I've used XML, but recently heard that's not a good way to go about it

teal viper
magic panther
teal viper
magic panther
#

It works, I'm just making sure if there's something I should avoid here

teal viper
#

Ideally, I'd make the field private and add a property. Or add an auto property with an attribute.

magic panther
#
using UnityEngine;

[CreateAssetMenu(fileName = "GoalConfig", menuName = "Configurations/GoalConfig", order = 1)]
public class GoalConfig : ScriptableObject {
    [SerializeField, Tooltip("How fast the goal follows after the cursor")]
    private float movementSpeed;

    public float MovementSpeed {
        get => movementSpeed;
        set => movementSpeed = value;
    }
}

Like this?

teal viper
#

Yeah. Is it supposed to be modifiable from outside this class?

#

If not, then delete the setter.

magic panther
#

Yeah, just delete the set => movementSpeed = value line?

teal viper
#

Or even replace the field as well with

[field: SerializeField]
public float MovementSpeed { get; }
acoustic sequoia
#

Hey everyone, quick question. i have two scripts. on eof them derives from another. the base class is to hide all the mess that will be duplicated across many of the same gameobjects..
how do i make each one of them have a unique event tied to it?

here are the scripts first the base and then the unique script..

{
  *** removed all irrelevant code

  public Action<int> debugEvent;

  private void OnEnable()
  {
    debugEvent += OnDebugEvent;
  }
  private void OnDisable()
  {
    debugEvent -= OnDebugEvent;
  }

  public abstract void OnDebugEvent(int value);
}```

unique class
```public class DebugSliderValueEvent : CustomDebugSlider
{
  public override void OnDebugEvent(int value)
  {
    // do something unique
  }

}```
teal viper
wintry quarry
acoustic sequoia
north kiln
#

Unless there's something I've missed, Unity can't deserialize over readonly fields

acoustic sequoia
wintry quarry
#

You'd be using composition instead of inheritance, which is usually more flexible and extensible

acoustic sequoia
wintry quarry
#

Why do you need inheritance? There's nothing in your code to be inherited

#

You will still have the CustomDebugSlider component on your GameObject. Inheritance buys you nothing.

acoustic sequoia
#

or sorry wait.. that's not right

wintry quarry
#

Put the unique code on a separate script and assign it in the UnityEvent inspector

#

The rest stays here

acoustic sequoia
#

i want to do this..

UnityEvent.Invoke(); <--- this includes the inherrited code```
wintry quarry
#

Again, I don't see how inheritance improves that though

teal viper
wintry quarry
#

And call it

burnt vapor
teal viper
#

Hmmm... I guess I did't have such properties without a setter. I do have some with a private setter indeed.

        [field: SerializeField]
        public Inventory Inventory { get; private set; }
acoustic sequoia
# wintry quarry Again, I don't see how inheritance improves that though

so hold up, i know i'm not understanding exactly.. but let me tell you exactly what i want to do and then tell me what i should do..

forget all the code above.

  1. I have a debugManager that will handle all the unique methods.
  2. i have 12 Custom Sliders that will all have a unique function assigned to them using unityEvents in the inspector from the debugManager.
  3. all of the sliders, when the unityevent is invoked, i need to run the unique function first and then the inherrited function.

so for all sliders they will have two functions:
1 that is unique amongst all other sliders
and 1 that is shared amongst all other sliders.

wintry quarry
wintry quarry
#

But it's unclear what these "inherited" functions are. To me, it probably makes more sense to just add a second Unity event rather than writing 12 subclasses. But it depends what you're actually doing

teal viper
#

Kinda hard to give an advice without knowing the actual context

acoustic sequoia
# wintry quarry But it's unclear what these "inherited" functions are. To me, it probably makes ...

so here is the main goal.

imagine i have a player with a level and a speed.

i want to be able to play the game normaly and upgrade my speed and my level whenever those functions are triggered.

(makes sense)

now for the part i'm trying to figure out.

i want to link in a debuging system that allows me to update the players level and speed through that menu at runtime.
so the debug UI needs to update the game when i want it to, and also the game needs to update the debug menu when it needs to.

so when i'm playing, i have an easier time testing out things.

#

so basically, i'm trying to create a two-way system that is for testing purposes only. so that i can easily "plug-in" my debug system without added a ton of littered code throughout myproject. when i'm done.. unplug and it works perfectly fine. no ties to anything.

acoustic sequoia
burnt vapor
#

So your debug manager has the same stats, but rather configurable instead of being read only?

#

It sounds easier to just make the stats page configurable when debugging

acoustic sequoia
# burnt vapor So your debug manager has the same stats, but rather configurable instead of bei...

so yeah that's easy. and that's what i want to do. i'm trying to link that info to a UI system that is for debugging only. by creating prefabs dragging and dropping the prefab into the menu. then drag and drop one function to it and it works. for any stat that i create in the future.

this isn't a "lets do this everytime i create a new project kinda thing. i want to do this once, package it up and be able to drop it into any other project i have and litterally do two drag and drops per stat i want to display.

teal viper
acoustic sequoia
teal viper
acoustic sequoia
teal viper
#

The way I'd do it, is either have an editor script or in game ui that bind to a certain character and displays and modifies it's stats.

teal viper
#

Break the feature down into components and tasks and try to implement it. When you actually have something working, you can ask for actual advice on how to improve or refactor it.

copper crest
#

Its saying the variable is not assigned even though it IS assigned in the inspector

teal viper
copper crest
#

it dosent removes it real time

teal viper
copper crest
teal viper
copper crest
#

and now it dodsent work

#

it worked then i saved it

#

and now it dosent work

#

what the sigma

teal viper
#

You need to debug properly...

#

There's likely something resetting the reference.

paper sable
#

hey guys, im watching a video about handling slope movement, i've followed all of the steps but my character automatically jumps off the slope when i enter it for some reason, i dont think i've done anything wrong, so i dont really know why this is happening. does anyone know why this may happen? this is the code that handles slope movement:

    private void HandleMovement()
    {
        moveDirection = orientation.forward * moveInput.y + orientation.right * moveInput.x;

        if (OnSlope())
        {
            rb.AddForce(GetSlopeMoveDirection() * moveSpeed * 20f, ForceMode.Force);
            print(GetSlopeMoveDirection());
        }

        if (grounded) rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        else rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
    }

    private bool OnSlope()
    {
        if (Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerObject.localScale.y + 0.3f))
        {
            float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
            return angle < maxSlopeAngle && angle != 0;
        }
        return false;
    }

    private Vector3 GetSlopeMoveDirection()
    {
        return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
    }
teal viper
acoustic sequoia
teal viper
#

With update, you'll make one or the other manage the values. And dirty flags or timestamps can be used to determine who's value is up to date.

acoustic sequoia
paper sable
teal viper
teal viper
teal viper
#

Just the movement and slope normal are barely enough info.

pallid kite
#

Hey, I'm currently having an issue where my prefab that has a worldspace overlay of a text input field not taking any input even when I click it. This doesn't seem to be too common of an issue, but I've been stuck on it for the past couple hours on how to fix it. Can someone help me possibly debug this issue?

teal viper
pallid kite
#

Sorry for the delay, tried debugging a bit more

#

Admittedly, I'm a bit confused on what a good screenshot would be for showing you my runtime

teal viper
pallid kite
teal viper
#

This is not an instance of the prefab at runtime.

pallid kite
#

I'm sorry I'm still a bit confused, do you want me to run and then screenshot?

#

Just to confirm we're not allowed to screenshare too? I was thinking that could help to debug

teal viper
teal viper
pallid kite
#

Okay, going to create that really quickly

paper sable
teal viper
pallid kite
#

Ah that makes sense then. Here's a screenshot of what I think you're asking of me... How do I get the jar to still show within the prefab screen, I keep losing it

teal viper
pallid kite
#

Okay, getting that right now

#

I hope this helps?

thin birch
#

Hi! apparently the final for loop gives me immediately the "Object reference not set to an instance of an object" error... I provided the objects in the scene and cannot seem to understand why this is happening...

    public GameObject Sun;
    public GameObject Bg;

    private Vector3[] _startPos;
    private float[] _widths;

    void Awake()
    {
        
    }
    
    void Start()
    {
        for (int i = 0; i < Clouds.Length; i++)
        {
            _startPos[i] = Clouds[i].transform.position;
            _widths[i] = Clouds[i].GetComponent<SpriteRenderer>().bounds.size.x;
        }
    }
short hazel
#

Multiple things could be null in here

thin birch
#

the exact line is the first line of the for loop

#

sorry

short hazel
#

Okay so Clouds was null

thin birch
short hazel
#

So Clouds isn't null

#

First line of the for loop is for (...)

#

Right?

thin birch
#

_startPos...

short hazel
#

Ah I see, it's _startPos

thin birch
#

yes

short hazel
#

Yeah, it's private

#

You need to instantiate the array yourself

thin birch
#

I see, thank you

dreamy tide
#

@short hazel brother

short hazel
#

What?

#

Pings and refueses to elaborate, great lol

snow warren
thin birch
burnt vapor
#

Same goes for checking cloud instances

#

Even if they are private it doesn't hurt. Debug.Assert is stripped from builds so it won't hurt performance

thin birch
#

ended up solving by declaring the array sizes

teal viper
# pallid kite

If you look at the hierarchy carefully, you'll see that the canvas with the input field is deactivated:

minor radish
#

What's wrong with this ?

rough lynx
minor radish
#

Thank you but the mistake is still here

#

Anywone ?

queen adder
#

. between transform and rotation.

burnt vapor
eternal falconBOT
burnt vapor
#

Pick the link that represents how you downloaded Visual Studio and follow the steps ☝️

burnt vapor
valid violet
#

@minor radish use Instantiate(pipe,transform.position,Quaternion.identity);

burnt vapor
gilded canyon
burnt vapor
#

And I ask again you don't help, period. If you decide to give the answer anyway most people just tend to continue their code rather than chore and fix their editor so this doesn't happen again.

gilded canyon
#

im pretty sure the game wont event run withour ide being configured

burnt vapor
#

It will

gilded canyon
#

i could be wrong though

valid violet
#

how did they make editor not configured on instalation?

burnt vapor
#

The editor is merely an analyzer, and Unity will compile the code if compilation is required on playing the game

burnt vapor
burnt vapor
#

Pick the one best suited. I assume it's either VS installed through the hub or manually.

green flame
#

Hello! Is there a way to "reset" an existing ScriptableObject by it's default value ? I tried 2/3 things but 0 success ^^

#

(from another scene btw ^^)

minor radish
burnt vapor
#

Specifically with manual installation, you must make sure the workload is installed and the external editor is set to VS.

finite dove
#

oh i just saw the comma

minor radish
finite dove
burnt vapor
#

Please configure your editor instead of fixing the issue. Your editor will point out the issue once configured

frail wind
#

guy i got trouble with player or spike collision because the player just go through the spike without any single collision occur. (unless i jump). i also sent the screenshot of the player code, the spike code, and both of the inspector in unity.

wintry quarry
wintry quarry
wintry quarry
#

"inside your visual studio installation directory" as it says

minor radish
frail wind
#

(also rate my coding skill along the way lol)

wintry quarry
wintry quarry
frail wind
wintry quarry
finite dove
minor radish
burnt vapor
#

Things like this are things your editor helps with, not other users

minor radish
minor radish
#

Nothing guide me yet

burnt vapor
#

Visual Studio is already the external editor according to this screenshot

#

So the next step is to install or update the Visual Studio Editor package

frail wind
#

does [transform.position += (Vector3.left * anyNumber) * Time.deltaTime;] actually not moving the object but Rather teleporting the object?

frail hawk
#

yep, it changes the position, if you want proper physics you would have to use some rigidbody movement instead

cosmic dagger
frail hawk
#

Addforce / velocity / moveposition (not really accurate)

frail wind