#💻┃code-beginner
1 messages · Page 401 of 1
ohhh
Click it and set it literally anything else
You bet good luck
your a lifesaver
fr he is
its always something so simple that im missing stg
No worries I been doing this 15 years and sometimes I still forget to assign things in the inspector
always nice to have someone to help ❤️
RPC trouble
anyone know how to fix this?
doesn't look like a coding question
#🔎┃find-a-channel
😦
how should i start learing code
is it by learning c# alone and then make games using it or the other way ??
I have a native unity app running in the background of my quest and this app will launch the browser onto this device and run in the background, and now this app is not listening to the user speech in background, and is not playing audio, how can I solve this
so I have this code written down to respawn my character when it is destroyed but even when it is destroyed it dosent respawn can I get some help with this thanks
also its followed by this error
If by "quest" you mean the Oculus/Meta VR device, that seems like a question which you should maybe direct to the #🥽┃virtual-reality channel. If that is not what you meant, I think you should probably elaborate upon what you mean by "native Unity app" and "running in the background of my quest," as well as which devices you are talking about, and how you are listening for user speech to begin with.
Is this code on the player you are destroying?
no i switched it to an empty object with a box collider
Well
i see it now
You check if character is null
and then use it
If its null you cant instantiate it
oh ok than how would i fix that problem
The way I would do it is to have something in the players OnDestroy()
for example in the playerScript in OnDestroy you start this coroutine in Respawn.
And then you reference the PlayerPrefab instead of the actual player and spawn it after x sec
Also has the advantage that you arent checking wether the player is null every frame
The above would otherwise also start a new coroutine every frame and spawn alot of new players
Every frame for 2 seconds till the first player spawns a new coroutine would start
tysm for the help
Depending on your game, actually destroying the player could lead to problems though. Depending on how coupled everything is
It could potentially be easier to just hide the actual graphical aspect and disable controls or something
But that depends on your situation
On a tangent, I'm really curious about what was responsible for the error here... Was it the coroutine call, or was it the Instantiate(Charchter)? Surely the former, as after two seconds Unity has certainly actually destroyed/GC'd the GO... Unless the flagged-for-destroy value was captured in the coroutine argument? 🤔
hmmmm ok ill keep that in mind thx
Instantiate(Charchter) is throwing the error
because this line will only ever be called if character == null
Therefore its guaranteed to throw an error because you cant instantiate(null)
Maybe show us the error
what
It's been destroyed but you're still trying to access it.
I'm just thinking that if the GO is Destroy()d in the same frame prior to this script's Update(), then it's not... actually destroyed yet. Just flagged for destruction at the end of the frame, no? It has an overloaded equality operation for null, but it's not actually null yet, yes? So like...
Ah I'll go test
Oh not sure about that myself actually
Thats why I would prevent all that and just do it in OnDestroy() or invoke some Death event
Destroy happends at the end, yes
Make sure to reference the prefab and not the destroyed object
Oh 100%! Best to handle it all in a more robust manner :)
I just got overly curious about where specifically the error was coming from
so i change character to player
FYI, DestroyImmediate destroys the object immediatley and Destroy destroys it at the end of the frame. I suggest you don't rely on this behavior though and try to stick to Destroy
Thank you! But now what if you call a function with that pre-real-destroy value - does the weird intermediary value get captured in the stack frame?
Let me know how the test works out)
Oh definitely! I'm just... I dunno. Trying to grasp the weird theoretical edges. I can go test to investigate 👍
C# is not my native language 😁
This is more Unity and its weird quirks and features 🙃
I doubt they like it themselves but after years of development these things will exist
Absolutely! I... just sometimes have a weird preoccupation with the minute details of implementations. The details are mostly useless in practice, but I can't help but be a little captivated - at least when they're in my realm of understanding.
I think.... part of my fascination might be borne of time spent with the Hackmud community - a Unity game, where obscure knowledge of the weird edges of it's JS runtime/environment could allow you steal other players' riches.
How can I make a model disable after 2 seconds of raycast casted from player’s camera hit the model?
Coroutine
Thank you so much!
for future reference, if someone tells you something you dont understand, Google it
Its useful if you want to do stuff across frames, like waiting some time to do x, then another wait and do y
Very basic explanation but yeah
Ok thanks!
tips on making learning code less boring
how would i reference a void OnMouseButton() in another script for example to damage and enemy
to start with that is a Method not a void. Secondly it would need to be public
sorry i just started with coding so i dont remeber the proper names for each things and thanks
You shouldn't need to be calling this method.
wdym
You shouldn't need to be calling this Unity callback function - it's managed by Unity.
Make something fun
But if you find code boring why learn it in the first place
ADHD makes everything boring yk
I guess the first step is to go to a doctor to get diagnosed and see what you can do about that
i am diagnosed but its smth you gotta deal with
or take the medication which i dont have accesses to rn
Yeah I dont have much experience with it but figured there is some medication that might help
But if access to it is not possible thats unfortunate
Guys I fell stuck and I don't know what to do I started learning weeks ago but I don't know the program to study and see progress
How you guys learn
What the steps u know
Pick something relatively easy you want to achieve and do it
Step by step, cut it into the smallest pieces and do one after the other
have you looked at !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'm currently following Brackeys tutorials
not a good plan
Dont just follow them like that
No ill check it
Do your own project and then look for tutorials for each step you get stuck on
Yes I fell stuck and I don't fully understand I mean the code works tho hhh
I felt it tbh
But how to get ideas for project
you dont need to
Something simple and easy
you should make the mobile games from the ads
its fun to make
fairly quick to do
yeah that could also be a good plan
or classics like tetris/ pong/ snake and work up from that
i made a skibidi toilet fangame for fun and also learned a lot from that
Run through the obstacle course and bring the adventurous Giant to a fabulous color ride!
i dont understand why this video has 780k views but its a fun project
I haven't quite fully sussed this out but I need to sleep. My observations thus far are fairly sprawling and probably not entirely accurate. I think I need to play with it all another hour or so get a full grip on things. But this is what I observed:
Instantiate() with an argument of the real value null produces a distinct exception:
ArgumentException: The Object you want to instantiate is null.
After you Destroy() a GO, within that frame it's value and equality will evaluate as equivalent to null, but it's still a GameObject type, and you can apparently operate upon it within that frame and within that call stack without issue or repercussion (yet to test - destruction from a separate script... perhaps the flagging which is responsible for the exception occurs between script message invocations)... If you Destroy() a GO then immediately Instantiate() it, Unity will happily clone the destroyed object into the scene hierarchy without complaint.
On the next and all subsequent frames, it's still an actual GameObject which evaluates as null, but now attempting to Instantiate() it or otherwise interact with it as a GameObject will throw the MissingReferenceException exception...
So I'm still not certain where the code in question was generating the error, and I haven't yet tested the argument closure... But I suspect it is the Instantiate(Charchter), as it would reference the... post-destruction GO after the frame in which it's destroyed at that point.
But that'll have to wait for tomorrow 🫡
Thanks yall I'll do that
this is very interesting. its probably because the GC hasnt acted upon the object
Interesting
when you Destroy an object, it cuts off all references in the project but hasnt destroyed the object.
Thanks!
not until the GC acts again, prob at the end of the frame
i cant open unity after reinstalling my windows. i did install Visual C++ Redistributable tho and games that needed it are running just fine
which Unity version because 100 is a very old VC++ version
Oh definitely! Like I'm sure this is all documented somewhere, and like 80 thousand people have done what I'm doing now... but 🤷
What I find most interesting is that bit which you point out - that it seems like Unity is still happy to treat the thing as a fully functioning GO until the end of the frame in which it's Destroy()ed, but it's not until the next frame that it seemingly starts throwing exceptions for member accessors (unless that change occurs in my yet untested scenario of the subsequent Unity message)...
yea its pretty dangerous if someone doesnt know what they're doing
but also interesting
i wonder if this is platform dependent and if it differs between .net and IL2CPP since they treat cases like this differently
ive had to deal with discrepencies between the two platforms a lot before
in fact I also had discrepencies between the editor and the game before
i had my unity editor installed in a non windows drive, so i just located it rather than reinstall. can it be the reason
you need the Visual Studio 2010 (VC++ 10.0) downloadable from here
https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170
yeah? Not 2010
ooooh
dayum. i thought later versions support older ones
thanks
hey guys!.
why does unity crash after running this line(55) once?
https://hastebin.skyra.pw/izegiburin.csharp
nothing is null btw
its not crashing just because you add deltaTime to t
It's probably in an infinite loop
It has a yield though 🤔
I suppose disintigrationTime has a value as well actually
wait ill send a video
Are you messing with timeScale or anything?
and if you comment out that while loop.. does it still crash?
you have been on this discord long enough to know to put Debug.Log statements into your code
unity crashes, how do you want me to read the log output
How do you know that it crashes there? Are you stepping through the code?
Log files
It gets written to disk
yea commenting it out didn't fix it...
how do i find the infinate loop?
so your crash is elsewhere
An infinite loop would cause the editor to freeze, not crash.
Though depending on your os it might get shut down after a while
It's not the infinite loop, I just didn't read your code properly
now comment out the mat.SetFloat(...
Well, the log should probably have some info on the crash.
you'd hope
There aren't that many things that could crash an editor. The most common one is a GPU crash/hang. And that should be producing errors correctly
this code used to work before! idk why this is happening
Probaby unrelated but this is not how if works
Well, who said that it's this code that's causing it?
the code is kinda old
from my old project
ill change it
its not an issue tho
ill go check the base class, maybe something there is causing it
check the logs first
What? Why? How?
Are you just making random assumptions?
exactly
How did you come to a conclusion that this code or it's base class is relevant?
I'd also like to know Who and When, just for completeness' sake
missing the most important one, When?
a vid has been provided, with step through to the crash
Ok, that explains it. I don't think it was mentioned anywhere in the text though. Or I'm blind.
not explicitly, but in his first msg he's got a screenshot with the breakpoints visible
That doesn't provide any proof that the crash is caused by the code though. You press continue, so it yields and probably continues to the next frame. There's probably a hell lot of a code running between you pressing continue and the crash.
how do you recomend i find the cause then?
First things first, is that log directly after a crash?
Or did you reopen the editor before copying it?
commenting this out fixed the crash. this is whats causing it.
btw its not the while loop, since commenting that out didnt fix the crash
It's not .. that's just a coroutine call.. the cause will be in the coroutine being called
ik
I suggest you use breakpoints and iterate the coroutine to figure out when it seemingly crashes.
thats what im saying.
One thing I'd check is wether you're not passing NANs anywhere. It seems like a possibility in that code.
i did use break points
use MORE
first thing I'd do is make sure you're not starting multiple coroutines
im not
prove it
That being said, it's likely something you're doing to the GPU, so it crashes after the coroutine yields and the GPU processes the issue.
so changing the material parameter?
Please store the result of Mathf.Lerp(startValue, targetValue, t / disintegrationTime) (line 54), and check its value before you call mat.SetFloat
My guess is that this is the issue, maybe
Possibly
Check the value that you pass in
on the first frame that the while loop runs(which is also the only frame that it runs) it is 0
and it is supposed to be 0 since it is slowly supposed to go up
Can you show us?
The value in the debugger
why does a null reference appear when when I call this method from another script
And it a crashing right after that?
Show the error..
yield return null runs, then it hangs for a few seconds and crashes
So it hangs
That would be a freeze.
playerDamage is probably null
which bit of code is EnemyAi.cs ?
second img
hmmm ok
the NRE is in EnemyAI.cs -> on line 138 ... as @languid spire says, it'll be playerDamage
please use some common sense here. You've posted 2 snippets neither of which show the class nor the line numbers
sorry man
i'm using heightValue = Mathf.PerlinNoise(perlinX, perlinZ) * perlinHeightMultiplier; for perlin noise but everytime i enter playmode i get the same output. how can i randomize the seed it is working from?
its so annoying having to open a project so many times just for it to crash again. it takes so fucking long!
then dont write code that causes crashes
narrow it down by commenting out less..
tried using int seed = Random.Range(0, 100000); Random.InitState(seed); but it seems like the seed remains the same
i guess ill try to introduce a random scroll through the noise instead
ahh, i guess that is how it's supposed to be used
this is a snippet of my script, and everything works perfectly well, besides the fact that nothing is getting Destroyed. Any idea on how to fix this?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Please put some Debugging in your code
Use this
Debug.Log($"Destroying hole: {hole.gameObject.name}", hole.gameObject);
It will output the game object getting destroyed and if it's still around you can click the log and the GO will be pinged in the hierarchy
then why does the code you posted not reflect this?
yes because you told me to add one
It seems to me the Destroy() functions are just not executing
how do I fix this
I was boutta say I have this on hole.gameObject but fragments are on top of holes getting destroyed 💀
added .gameObject to all destroys, all is working now
i found the reason!
you see, on the line where i set the shared materials for my renderers, it was possible for the renderers to be a VFX renderer, which literally crash the game if you try to set anything on them. i ended up filtering them out from my renderers list.
That in no way explains why the crash was on a for loop of colliders setting the layer
because it wasnt? it was on a loop for setting the shared material
jeez calm down, how was i supposed to know? ive been debugging ever since this last message to get here
oh nooo
thats just a break point
i meant it crashes when my code looks like this and dosnt crash when i comment out the materials part
So setting sharedMaterials on a Visual Effect causes a crash?
yes
Hi,
How can I access VFXRenderer class from my code? It seems that it isn't available due its protection level. I want to be able to iterate over...
i dont even know why we are allowed to do that, that should be handled by the visual effect component
I asked this earlier and deleted cause I thought I fixed it but apparently not.
I am trying to do a simple data save to json and I keep getting UnauthorizedAccessException. Could it be because I am calling it from the OnDestroy function of an EditorWindow class?
This is the code:
path = "/Assignment_03/Data/BoardData.json";
string directory = Application.dataPath + path;
System.IO.File.WriteAllText(directory, jsonObject);
dataPath is read only. Typically you'd save data to persistentDataPath
Same issue
and use Path.Join to build the directory
Path.Combine
Combine is for some reason only returnig the path string
show how you use it
string directory = System.IO.Path.Combine(Application.persistentDataPath, path);
Debug.Log(directory); //prints "/Assignment_03/Data/BoardData.json"
I get the following error: Assets\Scripts\Quiz.cs(88,15): error CS1061: 'Timer' does not contain a definition for 'CancelTimer' and no accessible extension method 'CancelTimer' accepting a first argument of type 'Timer' could be found (are you missing a using directive or an assembly reference?). I have a reference to a timer object in my quiz script that calls the public function "CancelTimer" from the timer object, I have no errors in the code but the error from above pops up in unity.
string directory = System.IO.Path.Combine(Application.persistentDataPath,"Assignment_03","Data","BoardData.json");
Ah, alright. Thanks!
it's saying the Timer class does not have a method called CancelTimer or an extension method (of the same name) that usesTimer for the first parameter. if you don't see errors, make sure your !ide is configured . . .
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I guess that was a bug or smth, i just pressed "attach to unity" and the error dissapeard, usually i just pressed ctrs+s to save
its most likely because you didnt save the file, attach to unity has nothing to do with that problem
you need to save all your code files so stuff like that doesnt happen
i did save multiple times using ctrs+s
but like you need to save all the files
oh ok. thanks
e.g. I can use TechTalkManager in ActivateOnEnter in my code, visual studio says its ok but because I havent saved TechTalkManager yet unity will yell at me
because of the *
For some reason this decided to work
thats fine just continue
it wont launch
but its because you have a different version of unity
i been waiting for the past hour
no it wont EVEN LOAD ANYTHING
it just says this i click continue 10 mins go by nothing
yea end the thing in task manager and try launching it again
okay
ok i saw something it was the unity's logo and it had a red alert next to it
for a split sec
let me try to screenshot it at the time
there it is
omg
that ! also appears when you run unity games
you can only task manager end it
or restart your pc
can you screenshot of the contents of the project folder you are trying to open
I mean the folder using File Explorer
this?
OK. Delete the Library and Temp folders and try to open the project again
need a restart or not?
no
ok
ok now it's on the loading screen
yipee
ok its done loading do i need to wait?
wait? Is the Editor not open?
nope
screenshot your task bar
no, windows task bar
that is NOT the task bar
press ctrl shift esc
no, not that either. May I suggest you spend some time to learn how to use your computer
i aint american
once you end the task go delete the library fiiles too
and try again
how did you even get a project to corrupt like this where is it from
I just downloaded unity and it just said this
this issue isn't code related, should have been asked in #💻┃unity-talk
and threaded
ok
in the standard rp, whats the difference between using a shader on the camera versus applying a shader to all objects? im not really sure how shaders work
i wanted to make a rolling world shader like animal crossing, the shader that I have only applies it to objects though
you don't put shaders on the camera, are you getting confused with post processing?
kinda yea
whats the difference between post processing and applying a shader to all objects
idk how I can apply my shader to all my assets reliably
i did see setreplacementshader and was thinking if I should switch to standard rp(my project is currently on URP)
Hey, can you give me some high level architectural tips? (I suffer from analysis paralysis, and would like someone to just give me some pointers to get me going). I'm struggling to add a serialized inventory, so I can load a save game and have an item in hand if I last saved with it in hand. (I have items on my levels that I can pickup (which assigns them to an "inHand" var on the pickup behaviour for example). So when I load my state and reset the player, do I just set all of my state? or call the code for pickup (so "simulating" picking up the item again?) Also My item is loaded as part of a level, when I load a gamestate on a different level, I need to also somehow load that one item to put it in my character's hand)
im not sure how your inventory works, but if we take minecraft for example every slot is assigned a number. and the inHand variable would be the slot number
you could use your pickup code when loading in items but if theres any items with "on pickup" passives that could cause issues. again we dont know what your pickup code has so we cant give an answer.
overall theres not enough information here to advise you on this.
URP is ur best bet to use all kinds of shaders
imagine I have nothing, I learn as I go, so I'm willing to scrap any solution I made that's not really "how things are done". So currently, an item is just a model with a script on the level, and when the character picks it up, that same prefab model is moved and parented to the character's hand. which made sense, but now when I'm getting to the inventory / serialization part I see it would probably make more sense to have some "db" (or scripted object) of items where an item type would have a separate prefab for something that's spawned on the level, and another representation for being in hand (like in an fps / or minecraft the onscreen in hand models are totally different from their in world representations)
Pretty sure you can use custom render passes for this in URP
ive spent a lot of time trying to make a custom render pass but it somehow doesnt work out
It was pretty easy in HDRP but URP seems a bit more complex
its not too bad but there are a couple of steps
Hello, im making a custom level editor in my game and i have some questions. Currently i can edit position, rotation and scale values of objects when i click on them but i want to add custom parameters for specific types of objects .For example when i click on a vehicle it should show a speed value that can be editable, an explosive object should display explosion force and damage. Whats the best way of doing this without making spaghetti code?
the last time I made an editor for it, it was spaghetti code. you can make a serialisable class and loop through the variables depending on the available variables
can you explain a bit more? should i create a class that has every single property an object can have
how can i get this code to work in the game (i have a main menu scene and it works in that but not the level scene)
i'd probably use a base class w/ ur standard parameters.. and maybe a dictionary that u can override for custom properties.. and then derive from that class for all ur different types
public abstract class EditableObject
{
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
public Vector3 Scale { get; set; }
public abstract Dictionary<string, object> GetCustomParameters();
public abstract void SetCustomParameter(string key, object value);
}``` something like this perhaps?
```cs
public class Vehicle : EditableObject```
```cs
public class Explosive : EditableObject```
I had a Block class, containing a field for another class. you can drag and drop scripts into that field which will change the fields that appear in game
like this?
class BuildObject
{
public Vector3 position;
...
}
class Explosive : BuildObject
{
public float range
}
yea
you can attach this script to any gameobject in the level scene
oh ok ty
like drag and drop it in
public override void SetCustomParameter(string key, object value)
{
if (key == "ExplosionForce") ExplosionForce = (float)value;
if (key == "Damage") Damage = (float)value;
}```
🎊
yeah
what does the object keyword mean
can it take any type of value?
pretty much
yep but youll need to cast it
theres probably a better way.. but im just learning how to use inheritance.. so im trying to up my game
correct:
object myObject = 69; <-- Assigning an int
int myInt = (int)myObject; <-- Casting back to int
so should i put this code in every single build object?
i would Not copy and paste any of my code.. i can't help u expand on it lol
just giving u an idea of what u can try
pseudo code but something like this can be done
class Shape;
class Circle : Shape;
class Square : Shape;
Circle shape = new();
switch(shape) {
case Circle _circle:
...
case Square _square:
...
}
this checks what type the shape is, then you can use it accordingly
so if its a Circle, you can use _circle
if its a Square, use _square
ya, its still gonna be a chunky system if u have multiple things u want to be able to change
also see:
if(shape is Circle _circle) {
...
}```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class EditableObject
{
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
public Vector3 Scale { get; set; }
public abstract Dictionary<string, object> GetCustomParameters();
public abstract void SetCustomParameter(string key, object value);
}
I want to use this code, is there a way to add it in objects and edit it in the editor
that works, then youll also need to loop through the values of this object to construct the values
Note that using is often indicates that you have a design problem
this is an abstract class so you cant use it by itself
yes i will do it in prefab scripts
indicating that you should be adding a virtual method to the parent class and moving the logic in there
It does makes sense for "bag of data" classes, I suppose
What does "add it in objects" mean?
assign to prefabs
you'd need to derive from it.. you'd create a Monobehaviour public abstract class EditableObject : MonoBehaviour
and derive from thatpublic class Vehicle : EditableObject and put that on the gameobject
I had an Objective system with multiple objective types(Dialogue, Location, Interact) and some objects need to check the current objective type
maybe someone else like ^ this can help better.. b/c i haven't implemented anything like this before
im just spitballing
can i use it without making other classes? for example i will add the script into the plane and add "speed" variable
the speed variable will be edited in build mode
and when the game runs the plane script checks if it has a variable
does anyone know any extentions to make coding easier in vs code?
and then changes its own variable
u could yes.. if it was a basic Monobehaviour
heres a few i use
found this online but not very good: typeof(Class).GetProperties();
ignore the PlatformIO
thanks sm
thereafter you can loop through the properties of the class
so let's say you want to loop through Explosive: foreach(var property in typeof(Explosive).GetProperties())
theres definitely better ways to do it
always is lol
what do you think about this
class EditableObject : MonoBehaviour
{
List of properties
}
struct Property{
public string name;
public int value;
}
i like structs
the objects own scripts will check it
but now you're stuck to int
ya, he could use it for anything he wanted if hes working only w/ int values
can i make something like interface but in array fashion
what does this mean
so i can [i] for my custom type to get something
is there a way to make it any type of value
object
oh i forgot lol
but youll have to get its type later anyway which loops back to the casting problem brought up earlier
it works for now though
why is it a big problem
you mean like MyClass : Monobehaviour, IInterfaces[i] ?
cuz thats weird.. lol i'd have to look into that myself
huh no idea i just want non array to act as array
where i can [i] to get custom thing
from my custom class
whats the purpose?
getting data from class
public class thing {
public string this[int key] {
//... return a string
}
}
note that you have to use this, the name of the key and the name of the class can be anything
isn't this just a dictionary at that point?
arrayless array yes that what i wanted
yes but you can swap out the input type
actually yea its a dict
you can return any property though
ahh cool okay
its like a gettersetter for dict
actually i can use string for every property
makes sense
youll still need to cast it at the end of the day
loops back to the original problem
why
you store everything as strings, lets say you have an Explosive class with the property of range. range is an int so you need to cast from string to int. also how would you restrict input to only allow int to be entered
Why
why you complain about everything
im also curious
you want to make a class that allows you to define properties on the fly like in js?
Why are you doing absolutely batshit things and never explaining the reason why the tools that already exist are inadequate
thats the only thing I can draw from this
Arrays exist. Use them.
because by the years you sitting here you know my options are limited
you want to use c# so change your mindset to be able to use c#
What possible situation can you be in where you don't have access to arrays
c# doesnt have "arrayless arrays" or whatever youre bringing up
ya, most things said are actually in good faith..
(and yet you do have the ability to define your own classes)
do provide a code example
this is either some completely insane VRChat thing or someone trying to reverse-engineer a game
or someone that came from knockoff programming language that tries to re-invent the wheel
could be an x y problem
It's not VR chat. I've done VR chat and half the stuff they're trying to do to workaround basic C# features are just not allowed in VR chat while the thing they're trying to circumnavigate are
Like, what gives you access to creating custom classes but can't have arrays? What let's you make enum flags but can't use the << operator?
❓ ❓ ❓ ❓
Beginner chat never fails to amaze me
we sitll need an example of this
even if its not from any programming language just type it out
we will see what we can do
i got answer here so i already dont ask for more
If you're going to come here and say "I can't do the obvious solution to my problem" then you're 100% going to need to explain why otherwise the problem has been solved
Can you please tell me why you need this, this is horrible
make a god-damn array, so help me god
ill expand on this: ```public class BetterDict
{
public Dictionary<string, string> _data = new Dictionary<string, string>();
public string this[string key]
{
get
{
if (!_data.ContainsKey(key))
{
_data[key] = string.Empty;
}
return _data[key];
}
set
{
_data[key] = value;
}
}
public float GetFloat(string key)
{
if (this[key] == "")
{
this[key] = "0";
return 0;
}
if (float.TryParse(this[key], out float swag))
{
return swag;
}
else
{
this[key] = "0";
return 0;
}
}
}
this dict behaves like the one in js where it returns an empty string if theres nothing there
i think i will only have a float input
i shouldve pasted this but yea
i could change it later if i want to add other values
It's been, what, a month? And you still haven't explained why you can't just use a goddamn list
this is a part of my rickety savesystem where it serialises a dictionary to use for the savefile
I know this is an example but you realize this is a pretty poor way of storing numeric data, right?
yep
Like, just store it as an object if you are doing this
im just lazy
Alright
quick question: i have a one-time event listener class. is it worth to have a separate field for a single callback or easier to just assign the single callback to the collection and remove the private System.Action _callback; field?
https://hatebin.com/qzjhjlgjpd
thanks for helping @eager spindle @rocky canyon
no problem wish i could help more. but ur treading outside my comfort zone.. good luck 🍀
i dont exactly understand what this does but yea youll need seperate actions, as one action cannot store different amounts of Templates
even the docs define it like this
i presume this is only meant to be used for zero-argument functions that return nothing
I would simplify it by just having _callbacks
Iterating over a one-element list is going to be marginally more expensive
and I'd rather not have to fuss over different behavior for one vs. many callbacks
why is a list needed, you can add many callbacks to 1 Action
it makes garbage
it's a one-time event listener. you'd call it like myEvent.OneTimeEvent( () => Debug.Log("Blah."));. it removes the listener after being called . . .
theres different types of action here some of them have no args some of them have more
we're all very aware of this, but that's out of scope here
depending on what point you want the args baked in, you can just bake it in via a lambda with no args
you can't meaningfully invoke anything other than a System.Action if you're responding to an event that passes no arguments
This is important if you can add or remove callbacks in response to the event being fired
can only really menually handle args if you know them up front or can bake them into a new delegate
since adding elements to or removing elements from a list will break the enumerator
that's what i was thinking. originally, i used callback for a single action, then figured some people would want mutlitple actions to fire only once for an event, so i added a collection constructor . . .
If you are wanting a listener to only fire a method once on an event, why not just unsubscribe from the event on the listener side when it's called?
action += anotherAction;
This produces an entirely new action that has nothing to do with the old one, so it can be safely done in the middle of the action being invoked
Yeah the listener can unsub from the event in the callback method i dont get writing this big wrapper
yeah if i want a invoke once, just unsub on invoke
this requires more work if you want to use an anonymous function
i wonder if an anonymous function can still unsubscribe itself
wrap it in a named function, that unsubs its self
yeah, it's a one-time event . . .
you can define a named function inside a function
Interesting point but its less work than making this whole class XD
making the class requires you to do the work once
rather than having to copy-paste logic everywhere
and yes, this is impossible
Also to handle args you will need a bunch of generic variants for each amount of args
nope since theres no reference to it. maybe if the Action works like an array and you get the index of the lambda
stupid method though
still easy to work around that, you can create a named function within the same scope as the lambda would be
I was thinking I could be tricky and have it capture the local variable from outside of the anonymous function
Yes, and now you've written a named function. It is no longer an anonymous function.
I don't understand why everyone is clamoring to come up with a workaround. I think this is perfectly reasonable
does that matter, its still within a constrained scope and not polluiting anything
like if you want to unsub ofcourse it needs a way to indentify just it
@shell sorrel yeah, this was the original extension method i had . . .
// Both params are closures
public static UnityEvent OneTimeEvent(this UnityEvent unityEvent, Action callback)
{
// Delegate allocation
unityEvent.AddListener(Invoke);
return unityEvent;
void Invoke()
{
// Delegate allocation
unityEvent.RemoveListener(Invoke);
callback.Invoke();
}
}
it works fine, but both params become closures and adding/removing the named function creates a new delegate instance every time. i wanted to try and avoid this. so it's a separate (wrapper) class . . .
I do something similar with an event that's meant to be re-subscribed to every time it's fired
in that case, though, the event just gets set to null after being invoked
why is this?
because I had a situation where multiple places in my code wanted to hear about the next time a specific thing happens
Im really curious about the use case now
I forget where I did this, actually. I'll have to go dig it up
(this indicates how non-remarkable the idea is 😛 )
It's identical to a List<System.Action> that gets cleared after the invocation (assuming you don't try to add/remove callbacks in the middle of the invocation)
Another place I use something similar is a "debug drawer" class
I want to be able to draw gizmos from anywhere in my code
not just OnDrawGizmos or OnDrawGizmosSelected
but you obviously can't draw gizmos outside of those messages
so I have a singleton that you stuff actions into, which then get executed at the right moment
the list gets cleared every frame
I have a mechanic in mind, but I don't know exactly how I can run it.
It would be something like time travel, when I press the button, the scenario changes to 2, when I press it again, it goes back to scenario 1.
Is there any way to do this without loading, just using a transition?
I'd have to create another scene for this, or I can make it so that such objects don't render until I press the button, and after I press it again, other objects render and others stop? (I don't know if this should be in this chat or in the game design chat srry)
is a 2d project
Oh make rendering layers
Swap to a camera that has those layers or change the layers on your camera in code
Oh, how can I change the layer that the cameras see?
Thanks for that
It worked exactly as I was thinking, thanks!

i just found it interesting lol
why cant i do this?
what is GameState
well, did you define an operator ==?
If that's a struct, I don't think you get equality out of the box
it is a struct, i wasnt expecting it not to work. how can i define something like that
I would go ahead and implement IEquatable<GameState>
Then implement operator == and operator !=
shebb is writing a multiplayer game and needs to be able to check if the clients are in sync
(or, more generally, check if two simulations of the game are in sync)
this is what rider recommended after implementing the interface. will this work fine?
I don't think GetHashCode works like that for a List<Vector3>
structs are immutable, you're comparing the value of the struct.
lets say you have ```struct ObjStruct {
int x, y, z;
}
class ObjClass {
int x, y, z;
}
assuming you use an operator overide, comparing ObjStruct against an ObjStruct checks if the values x, y and z are the same. if you have two different structs with the same values, this will return true,
comparing ObjClass checks if they're the same object. if you have two different objects with the same values, this will return false.
Isn't that just testing if you have the same references
yeah, the default equality test for reference types is to compare the references themselves
what about this
added the operators as rider suggested
lets say you have
ObjStruct first = new();
ObjStruct second = first;
seccond is a copy of first. doing ```
second.x = 1
will not change `first`.
but if you do the same thing with`ObjClass`, then both `first` and `second` will change because you are modifying the same object
im not sure .equals works but give it a spin
I would give your state an explicit ComputeHash method
do you need it to be a struct?
then have Equals compare ComputeHash() and other.ComputeHash()
(this way, ComputeHash can return an int or a long or whatever the heck you want it to)
GetHashCode can call ComputeHash and then turn it into an int, if needed
yeah, its easier that way surely?
when I first learned about the difference in how struct vs object is treated in c++ vs c# i was appalled
I don't see a huge case for using a struct here
it's not like all of its members are value types
It's got two List<Vector3>s
i mean i can change it, but wont that make the operators useless because its checking references or whatever?
The default equality check for reference types is to compare references
You can override this.
okay. how does this look for a computehash method btw
public Hash128 ComputeHash()
{
Hash128 newHash = new Hash128();
newHash.Append(playerPositions);
newHash.Append(playerVelocities);
return newHash;
}
what do i add to the code to make it whenever the light flickers the bulb goes black?
because lights get baked at the start, disabling lights wont work. you can change light intensity
It looks like Hash128 has an overload for hasing arrays/lists/nativearrays
how would i put that into the code
So that would work.
this thing
you should look up the docs on Light
or you can right click Light and go to definition
Sounds like you need to adjust the bulb's material properties.
Do you have a model of the lightbulb?
do i add a variable for the mat properties?
Changing light intensity would also do nothing if the light was baked
yeah its just a sphere
Grim is asking about changing the visual look of a model, it sounds like
Add a field that can store a Renderer.
Drag the MeshRenderer for the light into it
You can now do bulbRenderer.material.color = Color.black, or whatever you want
do i just paste that into the code?
Renderer.material is the first material used by the Renderer, and Material.color is the main color of the Material.
well not literally: it doesn't have a semicolon at the end
but you'll do something like that
okay ill try
note that when you access material, Unity creates a new copy of the material for that specific renderer
otherwise you'd be modifying the original material object (which might be used by many different renderers)
the mat is only used for the bulb
what exactly do i add i dont know much about coding
your code already has several fields in it
[SerializeField] Renderer bulbRenderer;
this will hold a Renderer
oh ok
Hi, how can I move the centre with the blue circle?
is this correct?
change the pivot in the sprite editor
the emission is what i need to turn black
This will set the color once, in Start
You probably want to do that in Flashing instead
in that case, you'll need to figure out what the name of the emission property is
here?
In the top right corner of the material's inspector, there's a "..." menu that lets you select the shader
You can then figure out the names of all of the properties.
It doesn't work, I want to do it for all the sprites in one, there are a lot i don't want to spend hours to do that
Think about when that line of code will run
ok
u can change it in code then
When do you set the color in this code?
Compare that to when you enable and disable the light.
I think i must do that but that bad, thank you for answer me
here?
Right. You change the color at the same time that you enable or disable the light.
Now you're going to need to set the emission color property, instead of just .color
you'll use SetColor for this
e.g. material.SetColor("SomeColorProperty", Color.white);
You should do two things:
- Pick the correct color, based on whether the light is enabled or disabled
- Set the emission to that color
This would be a smart place to use a conditional operator
Color emission = testLight.enabled ? Color.white : Color.black;
If the light is enabled, you get white. If the light is disabled, you get black.
where do i put this in the code
well, where do you need the color?
in flashing right?
might need a conditional as well..
material.color = Color.black;
else
material.color = Color.white;```
after u toggle the light ofc
the plan is to use emission to set the color on the next line :p
aok
sorry just seen u mention this already
ternary.. so simple i dont notice it half the time 😄
its proper name is the "conditional operator"
it is a ternary, but that's a bit like calling + the binary operator 😁
is this correct? do i have to type whats in the grey too? i have an extention on
ill remember that 👍 thanks
oh man, Intellicode actually did a good job there
may be AI 😉
bulbRenderer.material.SetColor will set a color property on the material
that's the Intellicode doohickey
or Codeium
too many things
codeium yea
i think i have both lmao
It's setting a Color property named "_EmissionColor"
i love codeium, u give it some variables.. and a decent script name and it damn near writes it for you
I would check that this is indeed a valid property for your shader. You can do that like this
If you see an _EmissionColor property in the list, you're good to go.
i see it
so do i type the grey stuff?
u can press tab and it will fill it in for u
thanks sm i was wondering how to get it to fill it out lol
@swift crag and @rocky canyon you guys are amazing tysm for the help it actually made sense lol
its been a looong time but... do we still need to cache this.transform or unity got smart enough to not do a GetComponent each time?
no need to cache a transform.. imo unless u just want to
I've never cached it
i used to.. b/c i thought it was cool t.GetComponent<>
does this.transform still do GetComponent<Transform>? 🤔
I'd be surprised if it ever has
id be disappointed if it did
Although, I suppose I shouldn't be .. after all there was Camera.Main
really quick how did you get the text in that grey box?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the bottom part ^
same as CS, but with a single `
the back ticks are usually next to ur 1 key
on both sides..
how to get children reference in unity toolkit?
you have to tell it where to start and end
like this
i figured that out but it says this content is blocked by this server from mods
its with scripting tho
ahh, probably b/c u didn't type enough characters
it'll block smaller messages b/c it thinks its spam
ohh ok lmao i just typed "a"
ya thats spam 😛
you can ask code questions in there. and look at the pinned msgs for useful info that may already have the answer
yayy
aye!
and to doo big blocks u use three on both sides
public class CachingExample : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>(); // Cache the Rigidbody component
}
void Update()
{
rb.AddForce(Vector3.up); // Use the cached component
}
}```
can i add you? you're a good teacher
nah, sorry but im here everyday 👍
m_NPCTextDialogue = uIDocument.rootVisualElement.Q<VisualElement>("NPCDialogue").Q<VisualElement>().Q<Label>();
can someone help me why this code doesnt work?
i tried to get a label reference here
i also have a YT channel if u wanna check that out
ok if i need help can i @ you?
sure i dont mind
ok ty
whats your channel?
same as my name
ok
its also in my profile
i subbed!!
damn thats a long line
any errors in ur console?
yeah i tried to get the children for every component
if its not working i'd debug each part of it until u make it thru the end
and see if u get any null reference errors
ahah! magic 🪄
yea it said something like that
sometimes if its been open a while it'll get lazy
i have to tab in and out sometimes to force it to recompile my code changes
a restart normally speeds it back up
Ctrl + R will refresh the editor
just learned that myself 🙂
thanks for the info dude
@rocky canyon how would i add a sound to the lamp whenever it flicks on?
add an audiosource to it.. put a clip into it.. and when u flick it on and off you can
audioSourceReference.Play();```
ok
or you can reference an audio clip in the script and leave the audio source slot blank.. and then use audioSourceReference.PlayOneShot(audioClipReference);
is this correct?
looks good to me... as long as ur reference is assigned 👍

oh wait.. that will only play the sound in Start() the first frame...
you'll want to put it in ur Coroutine.. like u did the material change
ohh yeah i see
or whenever u trigger the light (however you do that)
the light is always on
ahh okay.. sooo when it flickers u should call that
this?
yup
ok lemme test it
the reason I use Stop() before i Play.. is that it keeps audio clips from overlapping
sometimes they can sound weird
and make sure ur audiosource isn't set to Looping
ok lol no wonder it sounds weird
still sounds a little weird ill screen record hold on
and.. it might be obvious.. but dont put the audiosource on the object ur turning on and off
b/c once u turn it off the audio source will go off too
wait do i put it on the lamp, light, or bulb
anything that doesn't get turned off
even an empty gameobject.. just depends on how u wanna do it
i put the audio source on an empty gameobject and it still sounds weird
i dont even think you can hear it hold on
nope no audio
ignore the radio
this is what the properties are
@rocky canyon you there?
ya, hold up
alr
had to test it myself..
works fine here..
IEnumerator FlickerLightAndAudio()
{
while (true)
{
flickeringLight.enabled = !flickeringLight.enabled;
if (audioSource.isPlaying)
audioSource.Stop();
else
audioSource.Play();
yield return new WaitForSeconds(1f);
}
}```
Why are all the scripts directly in Assets?
maybe try the if/ else statment to see if that helps
i am hold on
dont judge.. its my Discord Helper Project 😄
it gets overrun
This just scared me
why isnt it stacking items?
Skript?
indeed 😉
he's k00l 😄
Still I'm not sure why there are 3 scenes in Assets if there's the "Scenes" folder
haven't gotten around to organizing it again... i do it like once a few weeks
for some reason += is not adding any quantity to the item amount
trust me.. the internal folders are very organized
is the _itemsInveXXXX collections of struct or class?
Collections of struct
You know you don't have to use any additional software to change the asset's location or create it in the suitable folder from the start, right..?
im aware.. and i structure my projects as i please..
can u concern urself w/ something else?
Sure.
thank you
@rocky canyon its working but its only playing when its off. and i only want it to play when its on
wait
just use an extra conditional
i think i know whats wrong
to array() copies all the "values" (whole struct or pointer if it is class) from your collection (no idea what it is) and you are modify the copied value in the return array (ie access the struct in the returned array), but the original struct in the collections wont be modified
quite hard to explain it in plain text
i was not correct
so maybe I should make it a class?
im a little confused what exactly do i write?
what is your collection?
you should not call toarray every iteration
it is a list of ItemAmounts which is an struct that contains the ItemType and the amount of it
@rocky canyon i want the buzzing to play when the light is on / white
then you can modify the struct in list by copy->change its field->assign it back
your_struct the_struct=list[i];
the_struct.field=value;
list[i]=the_struct;
something like if(testLight.enabled){ flickerSound.Stop(); flickerSound.Play();} should work
ok ill try
mybe it is better just to create a class right?
orr if its a buzzing loop that ur using
if(testLight.enabled){
flickerSound.Play();
}else{
flickerSound.Stop();
}```
if light is on -> Play() if light is off -> Stop()
probably if the struct is "large" (Microsoft says large==greater than 16 bytes)
this worked!! tysm
no problem! i didn't know it was a buzzing noise or i'd mentioned that earlier
i thought it was like a click on/off sound
oh sorry
i should change the name of the sound to buzzing sound
mmhmm.. always name ur stuff appropriately.. it helps u find stuff quickly..
and u dont want people like Sashok randomly complaining about ur project folder
yeah i just named it flickering light cause thats what it was called originally when i use it as a buzzing sound
lmao
i changed the sound do you think this is better?
record MP4s
keep it on topic too, this is a code chan
for general questions like whats better this or that.. use #archived-game-design
ok ty
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class PipeSpawnScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
public float destroyRate = 4;
private float timer = 0;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
} else
{
spawnPipe();
timer = 0;
}
}
void spawnPipe()
{
Instantiate(pipe, transform.position, transform.rotation);
Destroy(pipe, destroyRate);
}
}
any reason for this to not destroy the pipes? im making a flappy bird game, trying to use the Destroy function to destroy the pipes after a certain time delay, but im just getting an error instead.
looks like ur trying to destroy the prefab
and not the Instance (copy) that u spawned
did you follow the steps in the tutorial? i recognize those pipes
i was trying to move ahead a little, i find it easier to learn when i figure things out my self
how would you do that?
follow the tutorial and it'll tell ya ;p
you need to cache them when u create them
go back and rewatch what you missed itll help
Instantiate returns a copy of an Object
the copy is the "instance" in this case
var copy = Instantiate(prefab);
Destroy(copy, 3f);
how I get myself not confused
public GameObject pipe; // bad name
public GameObject pipePrefab; // goodname
using UnityEngine;
public class Pipes : MonoBehaviour
{
public float speed = 5f;
private float leftEdge;
private void Start()
{
leftEdge = Camera.main.ScreenToWorldPoint(Vector3.zero).x - 1f;
}
private void Update()
{
transform.position += Vector3.left * speed * Time.deltaTime;
if (transform.position.x < leftEdge) {
Destroy(gameObject);
}
}
}```
camelCase public variables 😦
public variables 😢
my script but its from another tut so idk if itll work
true lol I'm so used to SerializeField
use three of the backticks on both sides for big code blocks
Are there any good videos on how to write good / production quality code in unity? i've been working on a game for about two weeks and it going decently well, but I am noticing that my code is messy and I would like to bring any further code I make cleaner.
Like this
add the cs so it's colour coded
These concepts of "clean" "messy" and "quality" are highly subjective... most of it comes with time and experience. One thing you shouldn't be afraid of is deleting and rewriting code often to improve it.
not working
u have to skip a line
yeah well I think im at the point where I can make stuff work, just not nicely
yeah right if it works, as long its not an unmaintainable mess
because you put the cs on its own line, you didn't copy what I did
like dont get me wrong, some of my code is good and I proud of it, but other parts look 💀
put a line break after the cs
and make sure theres no spaces after it
there is, the problem is he put a line break before the cs after the 3 `
he figured it out
fixed
Most of my code works, but there's like a 2% chance I decide to eventually release it on steam and I would like to have code that doesn't work on just my machine lol
thanks for the pdf :)
i found it comes with experience more than anything.. once u have to start refactoring b/c u can't keep track of whats happening.. thats when u start to learn what works for you and how to write things neater
yeah true. Run a bunch of tests prior with itch and stuff
yes use itch its free to upload a game lmao
i have never tested my code on another machine... i bet 20% of it doesnt work
I test my game mostly on my macbook. I also run it on my Steam Deck (and even sometimes on my PC!)
My player objects are stored in a List of a class called ItemAmount(objects hat contain the item data and its quantity). Is it better that every time my Inventory updates(receives an object/releases an object) I build it from scratch by using the items and quantities in the List or just updating the objects that were changed
you probably write solid af code tho 😛
i've discovered some really weird platform-specific issues
all of my IMGUI text was just...gone on my steam deck
the font didn't work
notice any performaance issues?
I haven´t tryed it yet
but I am not sure if I should "refresh" the UI from scratch or simply add little by little
I develop on linux for a client who uses windows. fun stuff
🫡
sounds lovely lol
most of my platform-dependent code is for stuff like opening a file browser
why not run a windows virtual machine? @dense plume
and for correctly displaying the command icon instead of the windows logo on macos
Unity handles almost everything for you.
- can't stand windows 2. don't need to, unity builds out to windows and it works fine
It's actually concerning if you have something that only works on one platform
i'd be super suprised if my projects didnt work on other platforms..
but work perfectly nah.. most likely not
What I am doing is reseting all the slots in the inventory every time it is updated and then showing the "abstract" inventory
doesn't sound out of the ordinary
its just I thought reseting the inventory every time it is updated sounds awful in terms of efficiency
Is it common to do so?
wdym "reset the inventory"
all the UI slots loose their information and it is changed attending to what the "abstract" inventory has
gotcha
sounds good?
My first go at "UI slots" would probably be a dictionary tbh, each slot being the key with inventory items as values
sounds like it, depends what "abstract" inventory means in your context too
like a logic representation of the UI ?
A list of a class called ItemAmount which stores the type of object and its quantity
weird name but seems fine
okay, thanks
Class? without methods you might consider a struct
the thing is I cant change the quantity of the object in the struct in a foreach
Ahh so this is like, "Arrows" as an item, with some mutable quantity, like a consumable
Yes
I agree with navarone that this class would probably be more readable as just "InventoryItem" or somesuch, but hey if you understand it, that's good
So you're storing these ItemAmount classes in some list for the UI to display?
Thats it
And the representation is carried out by this "Slots"
Dictionaries are dope, wish Unity could out the box serialize them. But alas we need to do magic tricks with struct 😛
Sounds like you'll also need a "UISlot" class to handle interaction and reference the UI elements
thats what I do. Mine usually goes
-InventoryManager
-UISlotsManager
-UISlot
