#archived-code-general
1 messages · Page 156 of 1
How to start with visuals? What are shaders, lightning, textures, material maps and so on? I need a deep dive tutorial. The question is in #✨┃vfx-and-particles
If the UVs are set correctly, then it should stretch the image properly. You can easily check if it's the problem with the mesh by using a material that works correctly on some basic meshes like Quad or Cube. If the material behaves differently, then the problem lies on the mesh side.
What do you mean by "seems to stick to one grey unless I adjust the scale"? Does it turn to a different shade of gray when you generate the noise differently?
Correct, if you generate a new noise, the grey will shift to a different colour/shade, suggesting that it is reading the noise map, just not applying the texture properly
Could you Debug.Log uv of each vertice?
Hello. I'm creating a gameobject from scratch (in code) and assigning a spriterenderer component to it. I want to load an individual sprite from an atlas with multiple sprites directly from my assets folder. I've come as far as doing renderer.sprite = Resources.Load<Sprite>("Assets/Texture2D/buildings.png"); but I have no clue on how to load a sprite from an atlas.
First things first, that's not how the path works in Resources.Load! It should not have an extension, and will search in all Resources folders it finds
oh thanks
so thats one future problem solved, but how do i go about getting individual sprites from an atlas?
What kind of atlas? One made in Unity or a single image with all your spitres on it?
For the first case i think you can do that in editor and in code but the other case its purely UVs
UVs seem all good. Applying the noise texture to a cube works just fine, just doesn't apply to the plane correctly which leads me to believe the issue is centralised within my MapDisplay script, but for the life of me can't figure out where
Could you send me the whole code so I could test it out?
how do i add this to my project https://github.com/aarthificial/darkwood-vision-effect/tree/master
When I try to debug in Unity 2021.3.3f1 with Visual Studio, the first time it attaches correctly, but the next times I get a "No connection could be made because the target machine actively refused it" error
this started happening today
I actually just managed to get it working by using a different method to map the UVs
Now time to properly generate the maps to get terrain 
Nice. 👍
How do I make my game to remember user?
how do I make is so that users already has their account loaded without need to connect to database by typing name or email?
like a Login?
wrote in previous message
you normally store a session token
just this?
if you're using unity authentication then it already stores token iirc
no, I am using SQlite database
so why did you send unity authentication docs
you have to make your own session cookies then
I have googled session token
as you have written
well yeah it's a common practice in already established systems
session cookies? in unity or sqlite?
otherwise you have to make your own token system
welcome to authentication hell..
it's very annoying
that's why third party solutions exists
I just want user to register in my game, then when they quit game and open it, they are already loaded
?
like Unity Authentication etc.
yeah you would store that info inside playerprefs or something
do I combine it with sql?
nah
I have to store user in database
or do I just do both?
playerprefs & sql?
the token for the user.. not the user itself
that's how unity does it
You store user in DB. You store their token (logged in authenticated info)
in playerprefs
and when they load the game I should get that info somehow??
when they load the game one more time *
yeah you just check if playerprefs has that token stored
that means they have logged in already
but you need to put a refresh token ideally and timelimit
how do I know which token I should check?
because its only for login, so ideally a logintoken
🤔
did you lookup what a token is?
yeah, but how does unity know that I am logged?
yeah
when you login user you store their token in playerprefs..
oh, wait, I have forgot that playerprefs is unique for every user...
if playerprefs has token, that means they logged in
my bad
yeah, I forgot that it's not database for all users
yes playerprefs is typically in the local pc registry
thats why its bad for permanent saves
I see, is it reliable to store it in PlayerPrefs?
ofc every SDK i've seen so far with unity does it
unity themselves does it, read the docs
I see
ok, it seems pretty easy to implement
So I got some issues with this funny stickman game absicly what im trying to do is have the stickman grab a weapon and have the weapon rotate the same way as the lower arm while still being affected by physics. I tried achieving this by making rigidbody2d Kinematic than making a FixedJoint2D and setting isKinematic to false right after. It works fine but after a few seconds of playing around with the sword it suddenly glitches out and starts flying across the screen. here is code: https://paste.myst.rs/ti3avdp4
a powerful website for storing and sharing text and code snippets. completely free and open source.
Does anyone have experience with Gradle? Im having some issues with it and I have zero knowledge on how to fix it. I recently updated from Unity 2020.*.* to Unity 2022.3.5f1 and along with that it cause my outdated version of gradle to stop working. So I downloaded the most recent version of gradle and it still doesnt work. Would someone be able to help me? Ill include console logs and everything
104,610 people
how do you know?
nice, thanks
is there a way to do something like this? Basically making a max distance that a camera could zoom to, the camera is on an angle so it seems much more tricky than if it was not angles at all
You can multiply the localPosition by a scalar, i.e. 2.5 / localPosition.magnitude
That'll achieve the same effect
This is basically how I am moving it
not sure exactly what you mean when you say scalar
Scalar meaning a single number which scales the length of the vector
So someVector * 0.5f would produce a vector that is half as long
I don't understand the application
For this line
Assigning the magnitude to 2.5 would be equivalent to normalizing the vector then multiplying it by 2.5
(Normalizing the vector makes its length ((the magnitude)) 1)
You can use Vector3.ClampMagnitude() for that, if you don't want the magnitude to go past a certain value
vec = Vector3.ClampMagnitude(vec, 2.5f)
I was thinking of using a min/max clamp but I'mw not sure where to set it
hello
How do i call user's profile picture?
avatar ?
question to people who are confident in their English
Avatar, Character Icon, Player Picture
Profile picture works universally for the picture, avatar can apply to your character in a game
is avatar used mostly?
I see, that's called profile picture then.
Avatar is a mostly incorrect word for it but people do use it
"pfp"
Character Widget and Player Icon are ones I hear often at work
hello one more time, is @gray mural a nickname and unique one an username?
I need it for my db
You can change it and on Discord it probably can have duplicates as well
Unique user id would look like 1025482839954821222
Your DB should have a primary key, which is an integer on 32 or 64 bits or longer
but is unique one called an username?
For DB it typically called "User ID"
yeah, I have one, id
is _idbb_ an username?
or user id?
Username
name that is unique I think
Your user ID is 1025482839954821222
how do you know it?
You need to turn on option yeah
I see
356398888036335617
but both id and username are unique?
Discord ensures there are no duplicate names, but usernames and IDs have different functions
also email is unique 🤔
Does anyone have a good tutorial on setting up a mobile joystick ui
You can add a UNIQUE constraint on your DB column if you need to have unique usernames
yes, I have done it already
thank you both
No interested in downloading an asset , I'd like to build it myself
I should just implement player account scene and have to know how to call things correctly, not uniqueName and name
And probably an index, clustered if available, on that username column, so searching for a name is fast!
I don't get it
Database index, speeds up fetching of rows by one of its columns by either physically sorting the values on disk (clustered index), or using some hash table (regular index)
I see
If you do a lot of searches by username WHERE username = 'something', then you probably want an index on username
how do I add index on username ?
Depends on which database management system you're using. It might not be available on all of them
SQLite
Hm, it's a file so probably not available.
Googling "sqlite add index" should yield some results
this?
Oh that's available, but there's no clustered index as it's using a special column rowid to physically order the row
But yes, you can use indices on sqlite
I see, thank you
I have a NullReferenceException problem when trying to get the parent gameobject of a gameobject my player is looking at
"Object reference not set to an instance of an object"
on this line:
heldObjectsOriginalParent = lookObject.transform.parent.gameObject;
Either lookObject is null, or it doesn't have a parent
anyone know how to paint trees on unitys built in terrain using code ?
i did a null check (if (lookObject != null))
Just now, or before you got the error?
just now. this is my code rn:
if (lookObject != null && lookObject.transform.parent.gameObject != null) heldObjectsOriginalParent = lookObject.transform.parent.gameObject;
neither the object or its parents can be null
lookObject.transform.parent can still throw doing the .gameobject afterwards
Yeah your if statement is flawed on that second condition
your check should be lookObject.transform.parent != null
oh, that works! ty!
How should I go around doing this
public void TryFindValidInstance(AnyMonoBehaviour gameObjectType)
{
if (FindObjectOfType<AnyMonoBehaviour>())
{
return AnyMonoBehaviour;
}
}
Yeah but to make it so there aren't 10 billion ugly if statements and I can do some other stuff if there isn't an instance I wanted to turn it into a function
You pass in a MonoBehaviour class for example a GameManager script
And it'll try to find an instance with FindObjectOfType and return it
If there isn't one then do other stuff
Do you mean like TryGetComponent style?
Yeah
Try to avoid Find functions tho, prefer DI solution, but singleton if inevitable.
Look into out keyword
float fillPercent = XP / maxXP;
Debug.Log(fillPercent);
i only get zeros. its an xp system and i am making a bar. if the xp is 10 and max is 100 it should output 0.1. but its giving zero.
nm
nvm
i needed to add (float)
Is there any way to get a summary of all profiling results in the unity profiler rather than inspecting frame-by-frame? I want to see across all recorded frames, which of my script methods took up the most cpu time.
Ideally also across all threads
Hey there, not sure if this is the right place to ask this but I'm looking for someone who could help me out with a script (I am willing to pay for it). DM me for more info about the project in case you are interested, cheers
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
aw i see, thanks
Does Physics.IgnoreCollision overrides the layer collision matrix?
Okay, ill give some background first. So for awhile i have been trying to start work on a cloud shader and i have been having problems figuring out how i can implement 4D Worley noise in a comprehensive way, either in a shader script or in a regular C# script. I have attempted to search for answers both on unity forums and other various threads/forums. The whole point of this part is that i want to be able to animate the clouds growing using 3d noise and i figured that using 4D noise will make the animation better. If there is any documentation or threads on this subject that i could use that would be great!
Anyone familiar with unity and VR game development? I got this problem where I want to make use of natural walking and go through a portal, but it dosent seem to work unless I use the joystick to my VR headset, but when I physically go through the portal the portal dosent work
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
So, how do I rename an already-established tag in the editor?
Select any game object, then in the top left of the inspector, you should be able to "add tag" which will let you edit any tag or layer - this will bring you to "Edit > Project Settings > Tags and Layers", as another way to access the same information
Can someone take a look at my method here? https://paste.ofcode.org/DPqkLfm69k4NZp627nZHk It is moving an object off and on screen, while rotating it so it looks at the camera. When the object is on screen, it rotates from another part of the script, so when it moves back off screen it has to take into account the starting rotation of the object so it doesn't snap the rotation to a new value. However that part of it is not working. In my script, I am taking the look rotation and rotating it by the starting rotation to try to prevent this using quaternion multiplication. Can anyone see where I am going wrong?
AFAIK it shouldnt, it would just ignore the collision between 2 specific colliders or objects on different layers, and will reset if the scene changes, game closes/reopens or any other condition that changes the state of those objects
By overrides, I mean: does it overrides it temporarly while there are active collisions being ignored?
I'm in that menu but all I can do with tags is delete them, unless I'm missing something
If your "static" point has objects between it and your AI, pathfinding can make sense, the goal of pathfinding is to find the shortest path to get to some location while avoiding stuff preventing you from going in a straight line to it, if you dont have that problem, then I think MoveTowards/Lerp sounds fine, though im not an expert with AI
If theres an active collision and then you ignore the layers, the next frame it should apply, if its a layer ignore and not a ignore between 2 colliders, so I believe until you change the scene state or call ignoreCollisions and pass true for the last param, it should continue to ignore any objects on those layers, even newly spawned ones, but it wont persist in the Editor after exiting play mode, just that session
does anyone know a good shader course
I did something wrong then, bc Unity is not working as expected
Oh, maybe something changed and its only for layers now, its been a while since I had to edit a tag, you could delete and remake it then, otherwise an alternative that comes to mind would be to edit the actual asset file for Tags & Layers, located in YourProjectRootFolder/ProjectSettings/TagManager.asset, you can open that with a text file, if you get non-human letters when you open it, you may have to go to "Edit > Project Settings > Editor", and make sure under "Asset Serialization", the mode is set to "Force Text", though I think thats a few steps for 1 tag change, and id caution making changes outside Unity this way (alternatively I think you can do it through editor scripting but also seems like an overkill approach to just recreating the tag), maybe theres another way im not thinking of atm
Odd, what is happening for you? And what is your setup?
I will update my repo with the code and send the link. It is hard to explain without letting u test it
But basically, I have X objects in the scene
I have some conditions that enables/disables object/object collision
Every object is at the same layer
So there is only this condition check that makes them collidible or not for each other
Based on some flags
These objects have CharacterControllers only
You could maybe record a video in addition to showing the code your using to manage the collision toggle, checking the docs there is
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
Which ignores collision only between 2 specific objects, and
https://docs.unity3d.com/ScriptReference/Physics.IgnoreLayerCollision.html
Which ignores collision between layers that object are on
Im using the first one, but no lucky. Maybe it doesnt work for Character Controllers?
Also, I have no Rigidbodies, if that matters
Im not sure if there is any specific cases with CharacterControllers, I dont think they count as colliders though I could be wrong (I believe they handle physics, so I imagine they have a internal collider), if they do count as colliders, then they should work the same as any other collider 🤔
They inherit collider class
{
Debug.Log("Print");
InsertLine("Input Anything...");
Debug.Log("Read");
yield return StartCoroutine(Read());
Debug.Log("Cls");
Clear();
Debug.Log("Print _in");
InsertLine(_in);
}```
``` private IEnumerator Read()
{
while (!isInputReady)
{
yield return null;
}
isInputReady = false;
}
Adding a console. Attempting to wait for the Read coroutine inside of the Main coroutine, which is being started by executing StartCoroutine(Main());, however the Main coroutine just executes all the way through without waiting for Read to finish Executing.
What is the proper way to wait for a coroutine in another?
This is the correct way
What makes you think it's not waiting
It immediately executes before isInputReady is made true.
How do you know? You need to add more logs
Including logging the value of isInputReady
And logs inside the other coroutine
Maybe it's already true
So it only waits a single frame
Ah boom, I'm a dumbass
Was setting isInputReady in my print line method and not my get input method
Runs fine now. Thanks for knocking some sense into me
Unrelated to your error, though if all your Read coroutine does is use a while loop to wait, why not use a WaitUntil yield instead of a while loop? The results should be virtually the same but you wouldnt have to have a coroutine that just yields null then
can I double-derive something
like maybe make an object derive from Damager but also Interactable
or I could just make two scripts
thats probably easier
You can only derive from one base class but you can implement any number of interfaces
You can inherit from as many interfaces as you want, but only 1 base class, so yes if "Damager" is a class, you can use that and IInteractbale, and IDamagable, etc - if Interactable and Damager are both classes, you could only inherit from one at a time
Better option though is to just split those things into separate components, imo
Ah, very cool. Wasn't aware of this.
yeah
and I dont understand interfaces, so ill just make two comps
i'm using nav mash to make a car follow a destination like this
Any idea to make the car get a path like this instead?
If it's a moderation issue, then DM or use #531949462411804679 . Otherwise, don't tag usergroups or people not in conversation with you.
Well it's not
I'm making a vr game you see.
And I accidentally deleted the main camera
And when I load the apk it's just the old grey void and sky
Do you know how to fix this?
Then the second half of #archived-code-general message
Good luck 🤞
Make your own a* pathing
You probably want to move Manhattan distance only
Somehow not to cut corners though
If you want to use navmesh is still possible if you put the points carefully on the mesh
Can anyone tell me why line 17 is giving NRE?
after completing my bro's code c# course do you recommend going towards scripting in unity?
I'm learning c#
in order to script for vid
just starting
I'd follow the beginners course in unity, its very informative and paced out well. On top of that it can teach you some useful features
Because variable is null
Why are you making super suspicious implicit operators
Why are they super suspicious?
As a matter of fact they are the least suspicious implicit operators I have lmao
I dont know why it says its null
I didnt even know a bool could be null
actually not true
Only if marked nullable values can
You are saying writing a code like ScriptableBoolean something = true; is not suspicious? 🤷
I'd also recommend the #💻┃code-beginner channel and check out their pins for guides and intro tutorials . . .
It isn’t the bool that’s null
This is correct
I mean that doesn't actually happen, so no not really.
You defined implicit operators so to allow writing that code
Respectfully, I get your point of view, but Its basically just implicitly casting a bool to a scriptable bool which is just a bool property
It'd be less sus if scriptable objects werent built different
Which will secretly create new SO instance and won't work consistent with operators like ==, sure
I suppose thats a bigger issue, I didnt think about that
I doubt that will matter at my games scale though
Ill try to fix that
This isn't a bool property its an SO which is a class that is created when you Implicitly assign a bool to it . . .
Well is there any other way to return a static SO
Why are you using SO in the first place
is that roads and intersection?
what are you doing?
Because its a lot easier for my buddy to not have to mess with code and still link useful information
using navmesh for traffic is not how its usually approached
i think nobody approaches this task using navmesh
What they usually use to simulate traffic?
point graph, at the very least
maybe with quad/cubic/bezier depending on how steering is handled
CS simulates traffic using point graph and steering behavior afaik
if you dont want to code pathfinding over point graph yourself the A* pathfinding project supports point graphs
all you need is to construct the graph with your own road pieces
or however you are making roads
theres a lot there, you can do multilevel graph, that only has major intersections, that one is used to compute the big path
then the main graph with all nodes you only compute path to the next target of the long path
the most straighforward optimization for massive cities
Game dev is a constant learning process. There's no one course that will teach you everything you will ever need. And you sure as heck won't retain everything in your first go
So there's no complete, but a good base perhaps
tx!
Guys, is there a better way to setup a C# property (without a backing field, get and set are functions taking data from transform) in the inspector ?
For example: i have a camera that orbit my planet, i want to setup the properties: coordinates + zoom and change the transform accordingly.
I have a working code, i want to show/edit in inspector.
The only two ways are building a inspector from EditorGUILayout or setting a backing field.
Any better way ?
Look into the SerializeReference and see if that works for you
I think the syntax is something like field:SerializeReference.
It's an attribute
Doesnt seen to work in this case, its to serialize a object reference.
In my case Coordinate (struct) is a result from the actual transform. I wanted to expose it in the editor without having to rebuild its fields manually through EditorGUILayout. But thanks
is the OnValidate() monobehaviour callback the thing youre looking for?
yes, i can use it to set a backing field to read/write from and reapply on validate
Thats the way you would do ?
if i understand your problem correctly, then yes. i would do something like OnValidate(){ transform.position = coordinate }
or vice versa, whatever you need it to do
and to pick the value the first time, when i load the editor, would you copy the transform -> coordinate, from a awake or start ? Or validate is also called on startup ?
OnValidate() is called whenever any value in the inspector changes. it's only called in the editor
because on validate being called after changes, its ok to pass the inspector changes to the backing field "_coordinate" and posterior changes will have the actual value. But on startup it would be default. Which function would you use to acquire the value ?
(start, awake)
if the value is marked as "public" or [SerializeField] then the value stays
General design question: Is there reason to use one pattern over the other with the following coroutine calls:
private IEnumerator DoInWhile ()
{
while (_Condition)
{
yield return new WaitForSeconds(0.2f);
}
_Done = true;
yield break;
}
vs
private IEnumerator DoRecursive ()
{
if (!_Condition)
{
_Done = true;
yield break;
}
yield return new WaitForSeconds(0.2f);
StartCoroutine(DoRecursive());
}
hey, so i made a character in blender and added bones so it rigs all good. the character looks like this image above, the bones are shown as well, i added some animations and dropped it into unity and they work fine.
now on the unity side, i want character customization to be able to add clothes to it, armor, etc., but i'm not sure how to approach that. in the second image, i parent that white underwear to the armature's pelvis bone in the unity hierachy and that works fine i mean, until the character starts walking beause the whole underwear object just rotates back and forth instead of each individual "sleeve" moving and the base staying
would i add "bones" to the underwear for the "sleeves" then attach those bones to the rig's thighs in unity or something
okay, reading a forum thread a bit, i can make bones for the "sleeves" then rotate them along with its parent?
second one is less efficient; starting a new coroutine generates a bit of garbage. You should also cache the WaitForSeconds if you're looking to maximize efficiency
Maybe ask in #🔀┃art-asset-workflow
Or one of the art channels
im getting NullReferenceException: Object reference not set to an instance of an object
Actor.ChangeAnimationState (System.String newState) error at line 64.
im new to csharp so i have no idea what to do
this code is in my first person combat script and it should work fine
That means you're using something that's null. In that line, it's probably animator
but i have it defined up there
So make sure it has a value
You defined it yes
But did you tell it which animator is it referring to
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
theres an animator attached to the gameobject that the script is attatched to
You still need to assign the animator component to the variable
Go through one of the beginner projects or watch the get component video in beginner scripting
Watch the video
k
i fixed it
animator = GetComponent<Animator>();
i put this in my Awake() function
Can you provide a breif snippet of what that caching looks like?
how can i make a pixel perfect camera effect for some objects only
store the WaitForSeconds instance and reuse it instead of creating a new one every time
also, you'd just yield return null to wait the next frame instea of a small arbitrary number . . .
I'm using an animator event that calls a function with an enum input, but every time its run the program gives me a NullReferenceException. I'm not sure why. Any ideas?
Show the !code ?
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
And show the error
public void StartAttack(TypesOfAttacks name)
{
isAttacking = true;
animator.SetBool("attacking", true);
if (name == TypesOfAttacks.attack1)
{
hbcontroller.damage = attack1damage; //NullReferenceException
}
}
Heres the function in question
hbcontroller is null
I thought that too, but in my awake i'm making hbcontroller an object
void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
hbcontroller = GetComponentInChildren<HitboxController>();
}
this is in the parent file that im inheriting from, the child file has no awake function
Show where in the hierarchy of this object there's this HitboxController component
You need to pass in the parameter to look for inactive objects
Look at the documentation for GetComponent in children
oh, alright thanks!
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(name);
while (!asyncLoad.isDone)
{
yield return null;
}
}```Trying to get a coroutine to check for if a scene is done loading. It doesn't seem to be working.
no wait, it is. So why is this breaking for me (ignore this tangent but note that I will probably have questions later)
How are you calling it
Via a UnityEvent. While the scene is loading, the event GO is set as a child of a DontDestroyOnLoad so it doesn't disappear while loading. (it get flushed when the event chain is done)
You're going to clarify what you mean by breaking
Need to see code. Are you at least using StartCoroutine
yes
I think I've locked onto the issue now, but it's something entirely different that requires more explanation on how my code specifically works.
And possibly looking at my project directly.
I'll save this question for tomorrow at this rate, it's bigger than I expected and it's also midnight here.
Hey all, I'm working with the new input system and trying to learn it myself and I'd like to use the Unity Events aspect of it. I have the Player Input component on the player object and I added the input actions reference to the component. I also added the reference to my player controller script to the specific event i'm looking to invoke (Move), but when I go to look for the function I wrote:
public void OnMove(InputAction.CallbackContext context)
I cannot find it. I realize I didn't provide too much info, but is there a common mistake that causes this?
first of all, you have a typo
"CallbackContrext "
it's CallbackContext
I didn’t paste it from my code, so it wasn’t an issue, but thanks for pointing that out haha
give your full code
Anyone have an idea why this list might not be serialized in the inspector?
public List<AnimalDNA> animals = new List<AnimalDNA>();
public class AnimalDNA
{
public ScriptableObject DNA;
public int num_to_initialise_on_start;
}
I have no errors, it's definitely the correct script, neither the script nor class are abstract. I originally had a struct but some answers online for similar questions suggested a class instead, to no avail. Much appreciated
your welcome
If I want to make some methods that are accessible by a script when needed, do I do this with a namespace?
Huh? You ideally make them private/protected/internal depending on your situation
No..? What does it have to do with a namespace?
I thought one of the points in having a namespace was that you could access it's methods and variables from another script
It's about separating your code.
For instance Microsoft have their "core" classes in System, but if you want IO classes you have System.IO, or if you want networking you have System.Net.
These aren't "hidden", they're just not included in your script unless you "use" them or have them in a global using.
For instance in a game project you may have
MyProject.Actors
MyProject.Actors.Player
MyProject.Actors.Mobs
Can I make a class that extends the monobehaviour or my games main namespace and then just call it in a script that I want it in?
You can technically "hide" classes that are default in .NET by doing something like:
I.E
namespace System.IO
{
public class File { }
}
As, then when you include System.IO you'll be including your own class, not the default .NET (I did try something similar to this recently, however this code is untested to be exact - it's also not foolproof to someone using reflection).
Yes.
The namespace is largely irrelevant
Will it be unique to the thing that called it automatically? So if many objects use it, their data won't get messed up
like if the method was to return a value based off of an input
So this is the difference between static, and non-static. Unless you specifically state the class is static, you'll require an instance of a Behaviour. So they'll not conflict.
An instance is unique.
Is this the method for calling an instance? SelectionManager.Instance.Function(); would get that function/method with input data relevant to only the invoker? And if it was called again at the same time by something else, there would be no conflict?
Yes, that seems fine, BUT not if SelectionManager were to be a monobehaviour. That wouldn't work.
Yes
If SelectionManager is a MonoBehaviour in this case you need to adapt to the code to:
a) create a GameObject and AddComponent<SelectionManager>()
b) Find a SelectionManager component
c) On Awake/OnEnable of SelectionManager you can set SelectionManager = this
Otherwise your get is going to cause issues here.
So basically making a temp game object to store data for an instance adn then get's deleted when it's not needed anymore
By default the temp GO will exist until the scene is changed.
If you need it past that you'll need to tell unity not to delete it.
Hey guys any idea if I can set the build index of a scene at runtime?
I want to be able to create a Scene using something like Scene newScene = SceneManager.CreateScene(sceneName); then set that scenes build index so I can load into that scene
Probably more practical to load using the name then
I don't think you can change the index
do u know what this error is ?
I dont think I can load into a scene without it being in the build index right?
is the script set as private?
idk
where you have
public class SceneMove : MonoBehaviour
does that public up there say private instead?
as an example
thats odd
this is the problem
is what you are referencing private?
You mean build settings?
You cannot add new scenes into build settings at runtime
Yes like when you put your scenes into the box in build settings and it assigns them a number. I want to create a scene in the game and have it load into that scene
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
what do u mean ?
Read the bot message
seems to me like onFoot is private
try changing the onFoot var from private to public in the code
ok that error went
all good?
Why does it now say OnFoot when it was onFoot earlier
I don't see a reason why it would behave differently but if i do someEvent?.Invoke(data) from another thread and i'm subscribed to someEvent in the main thread of Unity, will that cause issues? I have a way to not be bothered by that limitation but it requires me to add Unity to my library but i kinda want it to be just LiteNetLib and nothing else
idk
my script
nvm thanks a lots for helping
the code works
Thanks a lot for your time
no problem man
Unless you're calling unity API in the subscribed method, it should be fine.
The method would run on the other thread, so you can't use unity API in it.
You don't need to modify your library though. You can make it the responsibility of whoever subscribes to the event. Make sure it's clear that it runs on a thread though.
so I am making a Home Assistant of GPT-3.5, but my current way of doing it is not optimal, here is the current setup:
First I wait for a noise
then when I detect a noise I start recording
after recording for 5 seconds I stop
That recording then gets turned into text by a speech to text (Whisper)
then I see if that text includes the name of the home assistant
if it does I send the text to GPT-3.5 and wait for the response
when I get the response I use a TTS service to say I
When the TTS is done saying it, I start recording again for 5s
then I go through the same again but if GPT-3.5 detects an end of the conversation it will send the command [End conversation] and then I don't start recording again after the TTS is done.
Here is a list of the Issues is have with this setup:
- I have to first make a noise, then I have to say the name and then I can ask the question. This is too many steps.
- I can only talk for 5s so I sometimes have to talk fast. This is a general issue no matter how long the recording is. I want to get rid of the set recording length.
- If I ask a small question I still have to wait the entire 5s to get a response.
- I want to change it so GPT-3.5 does not have to detect an end of the conversation to end the conversation. As it is unreliable.
Here are the limitations I have:
- I can only either record a file or detect the loudness of the microphone
- The speech to text can only get a recorded clip no streaming
Here is also the code: https://gdl.space/oyavubeqoz.cs
I know a bit messy both the code and the explanation but I tried my best. In the code just focus on Update function on line 122.
And all of that sounds like it has nothing to do with Unity
Start by finding a streaming Speech-To-Text service.
It is made in unity with a lot of unity's tools, although i am aware it is not the optimal place to do such thing, it is the only thing i know : )
Okay, Ill have a look at it, thanks
try making a console app version first
no idea how, currently it does work, I'm just not happy with the setup
well I suggest you learn how, making a working prototype as a console app will be a lot simpler than doing it in Unity. Once it is working to your satisfaction you can then think about porting the code to Unity
none of what you describe is Unity specific
I am aware, but that would require me to learn Python as far as I know, and i don't really have the time. The question was mostly to see if there was any thing i missed, or something simple that could be improved, but you are right, I'll come back the project when i have more time and do it properly like you said, in a console app : D
python? Why? you can make a console app in .Net C# exactly the same as Unity
Is there any way to check the FPS of an Android Application through the Editor's Profiler ? I can see other metrics like memory etc but can't figure out where the FPS is shown when connecting the profiler to the development build running on the Android device.
You gotta look at the CPU Profiler Section. There is the amount of ms that it takes to do 1 frame.
However, the FPS will not be representative of what you have in release mode.
As a development build add a substantial amount of work.
oh, i never knew, thanks, ill have a look at it : D
@steady moat okay okay, then I guess I will use the dev options on the device to see the actual FPS, thank you very much for your remark !
Is it possible to setup authentication system around just email ID and password using unity gaming services?
anyone know why my bullet drops like this? https://youtu.be/P5v9K3lScxE
im not sure how to phrase this, but
is it possible to set up something so you could say
"Set this to false provided nothing else is trying to set it to true"
or is that not a thing
var myValue = something || somethingElse; ?
i think the issue im trying to solve is that I have multiple things that prevent sleep, but after it is set to true, I need to set it to false once all the conditions to set it to true are no longer valid, and they are spread across multiple scripts, and multiple gameObjects, so I cant have a big if check
Just reevaluate your condition ?
You can also use a semaphore approach.
private void LockSleep(){
sleepLock++;
}
private void UnlockSleep(){
sleepLock--;
}
private void CanSleep(){
return sleepLock == 0;
}
Agreed, I'd use an event to update it. Send an event to add and subtract from sleep and update the counter. When it reaches 0, sleepy time!
private List<System.Func<bool>> conditions = new List<System.Func<bool>>();
private void Subscribe(System.Func<bool> condition){
conditons.Add(condition);
}
private void Unsubscribe(System.Func<bool> condition){
conditons.Remove(condition);
}
private void CanSleep(){
return !conditions.Any(x => x.Invoke());
}
thats a good idea
managing going up and down might be a hassle
the list might be more optimal for me
Ill do that
are objects actually destroyed when I load a new level? will it trigger OnDestroy
depends on how you load the new scene, i heard that additive will not destroy objects in old scene
would it make sense to instantiate a scriptable object at start and assigning it to a reference of the SO class inside monobehaviour?
public interface IPlayerComponent
{
public Player player { get; set; }
public virtual void doAwake<T>(Player player, ref T playerComponent) where T : ScriptableObject
{
this.player = player;
playerComponent = UnityEngine.Object.Instantiate(playerComponent);
}
[CreateAssetMenu(fileName = "Move", menuName = "ScriptableObjects/Player/Components/Move")]
public class Move : ScriptableObject, IPlayerComponent
{
public Player player { get; set; }
public float BaseSpeed = 5f;
}```
```cs
public class Player : MonoBehaviour
{
public Move move;
void Awake()
{
((IPlayerComponent)move).doAwake(this, ref move);
}
}```
While coding saving and loading, I've come to a problem. Currently my code uses a lot of coroutines like
private IEnumerator BeginStun(float time)
{
isStunned = true;
InputControl.Instance.SetControlState(ECState.Character_NoMove);
meshAnimator.SetBool("Stunned", true);
yield return new WaitForSeconds(time);
isStunned = false;
yield return new WaitForSeconds(1);
if (!isStunned)
{
InputControl.Instance.SetControlState(ECState.Character);
meshAnimator.SetBool("Stunned", false);
}
}
Can I save and restore their state? Because RN when I load a save, they just get eradicated, which breaks stuff if one of those was active when player saved (in case of BeginStun, for instance - in that save the player will never come out of stunned state, because isstunned set to "true" but coroutine that was about to set it back to "false" got lost)
ughhh this is spaghettiiiiii
even I recognize it isnt going well
Well, you'll need to serialize all variables of that specific state then and redo the coroutine when you deserialize the data
Depends if you want to write to the SO or not. People argue that they should only be used for immutable data, but if this design method makes sense for you then go for it.
I've heard SO being much lighter than MonoBehaviour
Well, yes, I already serialize the variables, but I can't exactly just simply restart the coroutine on the loading end, can I?
they serve different purposes, so you can't really compare them directly
Right, there's less overhead but you do lose the scene presence of a mono, and you cannot directly run coroutines on them. Not the biggest of deal since you can always just use a manager on the scene for that.
I'd imagine you'd just restart the stun process for the coroutine, but this time with lessen duration from which the time you serialized it.
Do not use coroutine. Simple as that. Instead use a good old Update loop with a correctly implemented StateMachine.
yeah that's the answer for sure. You need finer grained control of your state machine than you can get with a coroutine here, so it's time to jump off the coroutine train and build your own state machine whose state can be serialized and restored.
Coroutines are essentially just quick and easy state machines
You usually do not want to instantiate ScriptableObject as their life cycle is most of the time not exactly what you want. If player is destroyed, the Move ScriptableObject will have to be explicitly destroy as well otherwise you gonna have memory leak. If it was a component, it would not have this issue.
Also, in your case, I doubt that the Move will want to be a ScriptableObject.
It is share by what ?
But using Update for anything that doesn't need to be updated every frame is a sin, no?
I'm instantiating a clone of the existing reference from the editor
"do not use coroutine use Update" can work for some cases of course... Up until you'd need to replace two coroutines running alongside one another. °~°
I guess I wanted to put SO into more use for game logic so that I might have less MonoBehaviour scripts
In case of a state machine you gonna almost is guarantee to have to update every frame. You can always add a wrapper around your state machine if you do not want to update it everyframe.
but it seems like it's not worth going through all the trouble
Update one after an other
Coroutine are not even async. There is nothing that prevent you from doing:
UpdateA();
UpdateB();
yeah I see thanks
if you need delays, you can use Time.Deltatime timers or Invoke()
I was thinking of changing my Buff/Debuff coroutine scripts into a general container to update through on each entity instead of just firing and forgetting.
It comes down to waitforseconds() vs checking the time each update, but I would assume the operation time is similar.
I'd rather check the time than use WaitForSeconds as it's less accurate . . .
Oh, yeah that's a good point
Updating the buffs through each entity is better as you can pause, stop, or cancel the process if needed. Personally, I'd run each entities Update through a global updater to control all buffs (though that's not particularly needed) . . .
You need a single source of truth for your game, stuff like this youd want to store as perhaps
GameState.Player.Debuffs[Debuffs.Stun].RemainingTimeMs
something like that
Right now, im trying to make a gun gameObject recoil backwards, away from whatever enemy its shooting at. Ive done all the coding, just not the recoil part. Any ideas on how I would accomplish this?
Is is possible that this code gets compiled in a build only from a Windows os?
I can build locally but it fails on a remote pipeline that runs on Linux
WebGLInput.captureAllKeyboardInput = false;
#endif ```
that will only be compiled for a webgl build
and indeed the target platform is webgl build
also is it normal that If I try to run that code from the editor I get an error?
I read that WebGLInput is specific to WebGL app
So, can you elaborate please? I've started implementing my own analog (not exactly just dumping shit into Update, I'll use a separate class for this), and I'm currently trying to wrap my head around how to make writing these things convenient, instead of making a shit-looking strings of if (elapsedTime > 0.5f && elapsedTime =< 0.5f+Time.DeltaTime())
Look into StateMachine
var delta = Time.DeltaTime();
var trimmed = elapsedTime - 0.5f;
if (trimmed > 0 && trimmed <= delta) ....
though not sure what you are trying to do there ngl
but when you see 0.5f twice in your conditional thats usually a sign you can simplify it out, like a math equation
Hey I need help, my boost is propelling me in the direction the player is facing, not the forward direction of the boost. Here is the script:https://gdl.space/ogigokehip.cpp and that is the boost model, which as you can see I want to boost the player in that direction the boost is facing. (the script is on the PLAYER not boost!!)
To come up with an analog of yield return new WaitForSeconds(0.5f); without needing to splice the code into a bunch of ifs or functions.
see what I wrote here:
#archived-code-general message
Why don't you just add some variable direction on a script, on the booster, which the player would read from when they come into contact with?
Ideally, you should just rotate the booster into the desired forward direction
theoretically you dont even need the variable right? assuming every booster has the same "original" direction with respect to its rotation, you can just get a vector based on what direction its rotated no?
^
So i replace the transform.position with vector3.(the direction i want).position?
I live in 2d land though so quaternions are something I havent learned the methods on, but you want the X/Z vector on that plane for what way its "facing", there's a method for that IIRC
This doesn't help, it doesn't matter where I get the remaining time, I still need to find a way to tell unity to skip part of the function on each subsequent Update so that it wouldn't repeat the start of my "poor man's coroutine" each time.
I get this error when I tried to build from a Linux container
if (remainingTime > 0)
but I want it so even if I rotate the boost it will work, or else every time I have to find the direction
every update you just subtract off Time.DeltaTime from your existing buffs/debuffs, then do a pass for if any of them have dipped below 0 and invoke code for em
prolly then want Strategy Pattern to handle various debuffs and what they do given that info
prolly something like
public interface IBuffStrategy
{
int DebuffId { get; }
void Process(DebuffContext context);
}
Can you show the code that boosts the player?
Yeah, right, so if I have function
void DoAFlip()
{
if (remainingTime < 1)
DoJump();
if (remainingTime < 0.5)
TurnAround();
if (remainingTime =< 0)
Land();
}
by the time it's time to call Land(); it will still be calling DoJump and Turn Around on each frame. Unless I give it very tight "if" conditions... Which might cause it to skip Jump() or TurnAround() completely if the player's framerate is shit......
Ok, use other.transform.forward instead of boost.transform.forward
Ok thanks, I will try it
Usually you'd make it face the forward direction (world z) when importing the model, but you could also do something like childing the object to an empty game object and rotate it locally.
then maybe like
public class PoisonDebuffStrategy
{
private GameState GameState { get; }
public PoisonDebuffStrategy(GameState gameState) {
GameState = gameState;
}
public int DebuffId => DebuffIds.Poison;
public void process(DebuffContext context)
{
GameState.Player.Debuffs[DebuffId].RemainingTimeMs -= context.DeltaTime;
var actualTime = context.DeltaTime;
if (GameState.Player.Debuffs[DebuffId].RemainingTimeMs < 0)
actualTime += GameState.Player.Debuffs[DebuffId].RemainingTimeMs;
GameState.Player.Life -= actualTime * this.damagePerSecond;
}
}
He wants one object to get an added force based on the forward of another object but was using the forward of a prefab reference (or something) instead.
oh yeah, probably dont want to do that haha
It does the exactly same thing and has the exactly same problem.
you should likely be Lerp/Slerp'ing their position based on time
It's just an abstract example =_=
or just use the physics engine and then have their animation be purely based off the couple vectors you have to work with (velocity and is collided with ground)
whats "the same problem"?
your serialization issue with starting the game and saving it? no that should be solved with what I posted largely
the problem of "how do I run each part of the function exactly once, ensuring I won't skip it if player's framerate is shit, and with a code that's human-readable, and without multiplying a shitload of bools"
I did forger their prolly should be a > 0 check at the start, and short circuit out of the debuff no longer has duration left
timescale projection, using delta time to figure out all the things that outta have happened based on time transpired
you're gonna need to do math, basically, to figure out where they were, and based on time transpired from the last frame, where they now outta be
"be" in the sense of total game state of all relevant stuff. Position, velocity, animation, life, all that jazz
luckily unity has handy methods like Lerp and Slerp to help facilitate this, animation curves, etc
in the case of the code you wrote above for example, it looks fine to me. I would just make sure that the logic of Land() overwrites the logic of TurnAround
such that if both of them fire off in the exact same frame, Land()'s mutatations "trump" TurnArounds and it takes precedence
You need to implement Land, DoJump and TurnAround as state... Each one of them are responsible to when they stop.
A really simple implementation would be:
void Update()
{
State next = current.Update();
if(next != current) {
current = next;
current.Enter();
}
}
I have a script that holds a couple variables. I want those variables to be readonly but accessible by every other script, except for one which I want to be able to modify the variables. How can this be implemented?
plain c# or mono?
use a property accessor with a public getter and private setter
and if its a list, use Readonly list property backed by a normal list as a field
actually Im curious @leaden ice do you know of any kind of readonly list in C# that provides real time access to a "bound" normal list? like where any mutations to the original list will be reflected by the readonly one?
without having to do re-allocations
better to just share the original list reference as an IReadOnlyList
How do I make a private setter that another script can access?
you can't
wait does List implement IReadOnlyList?
that's the point of it being private
yep
... well... okay lol
that was easy
10 years and I honest to god was today years old when I learned that List implement IReadOnlyList
And why shouldn't it? It's just a subset of the List functionality!
@steep saddle
Private: Only this class can access it
Protected: This class and its inheritants can access it
Internal: Same Namespace can access it
Public: Everyone/Everything
Okay, so just so I'm understanding... I have my structContainer script with public getters, and I have my structSetter script (which does more than just set the struct, but it is part of its functionality). How does structSetter set it?
it doesn't. Why do you want a separate type to do the setting?
What's the use case here
is your goal "one time setability" where you can set it once, but once set it is immutable?
if so, thats what the constructor is for
I have a bunch of microcontrollers connected to buttons, toggles, rfid readers, lights, etc. I have a Port handler script that does the work of decoding/processing the Serial packets. I want to have corresponding game objects for each of my toggles and buttons and whatnot, whose state can then be read by other scripts. But the "setting" of the toggle object's state should only be done by my port handler script
ah okay, no problem, you want to use Interfaces and Classes
Internal is by assembly*
you can have the get functionality exposed on the Interface, but the Class has the setter also exposed.
Your service can have the class version of your objects, but its methods all return the interface
public interface IFooEntity
{
string Bar { get; } // <- note the lack of a set here
}
public class FooEntity : IFooEntity
{
public string Bar { get; set; } // <- Note how the set is public here
}
public class FooService
{
private FooEntity MyFoo { get; } // <- We have the class, not the interface ref
// v--- note how this returns the interface, not the class version
public IFooEntity SetFooText(string text)
{
MyFoo.Bar = text;
return MyFoo
}
}
Note that when handed a copy of IFooEntity they can only read from it, the setter is not exposed
Interfaces, as their name sort of entails, are primarily useable in this way, by acting as a "mask" that can cover up and specify what functionality is exposed vs not
Okay, thank you. Trying to process it all
In the specific example I listed, I would pass the IFooEntity to anything meant to only read Bar (what does the "I" imply, by the way?)
Do I have it right?
you typically, in C#, name all your interfaces starting with an I
Interface. Naming convention in C# is that interfaces start with I
exactly yup
I always get this wrong lol, because so often the two sort of go hand in hand for multi-project solutions XD
Is there a sort of code review channel here :>
I typically post it in a pastebin/hatebin link, but yeah Ive gotten a couple code reviews here before
Okay so, this is the script I would put on a given toggle object? I don't quite understand what is happening with the get; and set; up top, nor do I know what I'm returning the toggle entity in setState? Also, is set state meant to be an interface or is toggle? Currently I'm getting an error by trying to return toggle.
public interface IToggleEntity
{
bool state { get; }
}
public class ToggleEntity
{
public bool state { get; set; }
}
public class ToggleSwitch : MonoBehaviour
{
private ToggleEntity toggle { get; }
public IToggleEntity setState(bool newState)
{
toggle.state = newState;
return toggle;
}
bool state = false;
}
Can also just expose the ToggleEntity with a property so you dont need to return it from the method, and you dont need to track state since your ToggleEntity has it already
I can play midi inputs but not outputs and read midi. anyone capable to help me with that? I've done research but can't find a solution till now or someone who understands how to do it
have installed DryWetMIDI and NAudio
OnSceneLoaded doesn't seem to be running when the scene has loaded. Or can it not run from DontDestroyOnLoad()?
But I mean, your ToggleSwitch can implement the interface directly, you can inherit from 1 class but you can implement infinite interfaces, you can 100% just do
public class ToggleSwitch : MonoBehavior, IToggleEntity
if you like, it super depends on how your other code gets the toggle switch
show code
I'd kind of like the other accessing scripts to have a public toggle switch (or, toggle switch interface) which I can designate in the inspector
from an object that gets set to DontDestroyOnLoad:
where did you sub to the event
define "sub"
that 100% works, you can use an interface as your field and drag and drop it on
[SerializeField]
IToggleSwitch toggleSwitch;
Will still work fine if your MonoBehavior implements IToggleSwitch, can drag and drop it on
subscribe
This method isn't referenced anywhere, did you forget to subscribe to the SceneManager.sceneLoaded event?
oh wait isn't it SceneManager.activeSceneChanged?
If however, you want your IToggleSwitch to be implemented by a POCO, I dont think those can be serialized fields
... probably. I'm new to this particular method so I don't know what I'm doing yet.
private void OnEnable()
{
DontDestroyOnLoad(gameObject);
SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
}
private void SceneManager_activeSceneChanged(Scene arg0, Scene arg1)
{
//do stuff
}```
Think that depends on timing, if you want to know as soon as a scene change happens (before the scene is loaded), or after the next scene is loaded
POCO?
There's a subtle difference between the two I guess, yours will likely get invoked on a scene that's already loaded additively
ahh right..
Plain Ole Class Object
yeah forgot there's a few events in there
in your example code you wrote there, ToggleEntity is a POCO for example
activeSceneChanged can be invoked just by calling https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html without loading or unloading any scenes
that takes two scenes ... does it matter what the scenes are?
it returns those values from the event through the parameters
so you get a(current scene & next scene)
not sure this the method you want tho
sceneLoaded could prob work fine, but did you actually subscribe to the event. Show the whole script @river sentinel
ended up going with this and the Debug.Log fired off properly
put a -= on OnDisable
it's good practice to cleanup
avoid some weird leaky
ah, thank you for that
one more question, not for fixing a problem or anything but just for my understanding: A missing GO is treated as just null, correct?
depends what you mean by "treated as just null"
if a script tries to reference it it'll act like it is null, right?
obj == null will return true
and dereferencing its fields will give MissingReferenceException
but it's not a true null
or check "if null then this" will return as it beign null
^
okay good
I'm working on a tennis game and I'm trying to add some fun movement. I like where I'm going with it so far, but it's still scuffed.
private bool canMove = true;
[SerializeField]
float smooth = 5.0f;
[SerializeField]
float tiltAngle = 20.0f;
private void Update() {
if (canMove == true) {
//get input from GameInput.cs
Vector2 inputVector = gameInput.GetMovementVectorNormalized();
//input to movement
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += moveDir * moveSpeed * Time.deltaTime;
//goofy movement physics
float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;
Quaternion target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
//rotation interpolation
float rotateSpeed = 12f;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
}
}```
You can try to add some cool movement to the camera if you want to have something more dynamic. I don't understand the question you have here.
If you want to have fun with camera mouvement, I recommend looking at this here : https://youtu.be/mr5xkf6zSzk
In this 2015 GDC tutorial, SMU Guildhall's Squirrel Eiserloh takes a dive into the world of 1D nonlinear transformations to help game programmers make better games.
Register for GDC: http://ubm.io/2gk5KTU
Join the GDC mailing list: http://www.gdconf.com/subscribe
Follow GDC on Twitter: https://twitter.com/Official_GDC
GDC talks cover a ran...
I think thats a good idea for later. I want to prevent the player from clipping in the ground when you turn around 180
yes, thank you
Ho I didn't see that.
is it a bad idea to use a rigidbody for a 2d character controller?
do you want to use physics? if so you use the 2d rigidbody yeh
if I were you i would not use direct transforms. use a rigidbody or character controller
If you want, you can try to check the angle in the LateUpdate function to correct the angles if they are going too far.
LateUpdate() happens after Update()
i was thinking about that, but I dont know very much about unitys physics. I want to try and refactor it down the line.
good time to learn then 😛
exactly 😅
sounds great. ill start working on that now
should I use GetComponent<Transform> and a Vector3 to track the rotation?
never
.transform exists
no need to ever use GetComponent<Transform>
oh yeah, this just amounted to "I forget a check to move onto the next event in my queue". Easy fix after all.
Hey I have a problem, my boost is pushing me in the forward direction of the player, not the boost's forward, here is a video that shows what i mean: also here is the script that is on the PLAYER, not boost, the boost has no scripts. https://gdl.space/ludejidunu.cpp
pass in the forwards of the booster then
Who has the script O.o
the player
thats what i did with other.transform
Hey guys, where would i go for netcode for gameobjects help
Got it
Instead of
other.transform.forward * boostForce + Vector3.up * boostUpwardsForce;
You can do :
transform.forward * boostForce + Vector3.up * boostUpwardsForce;
i had that
is the pivot correct ?
doesnt change
Ah there’s teo, okok
it doesnt change anything
wht do you mean?
the blue arrow for the booster
does it point where arrow is ?
yes the axis are correct
Is the correct force being applied ? I feel like your movement script might just override your change.
how are you moving the player
player movement script
wait
if you are it overrides all forces
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
maybe your velocity limiter
is coming into effect
if (flatVel.magnitude > moveSpeed && grounded)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
How?
cause it would resort to .velocity
which would override it
that's if that even hits that statement
but how
does that have anything to do with the direction ?
like the force is being applied fine
did you debug.log SpeedControl
the ifstatement i meant inside of it
nope doesnt appear when I go through the boost
this was it
I didnt get any message
what happens if you only walk through speed boost without jump
wait..
Boost is on player right ?
The script is on the player yes
like I said the boost model has no script, just a trigger collider
thats why i used other.transform
also is this in local space or world coords
switch it to local and show me which script has Tag Boost / collider
yeah this is true if it's different direction each time (if you verified this without jump) then something else is wrong
the axis in local
Blender export, it seems
other.transform.up
yes
you could try this sure
I would fix the pivot personally
You should configure the exporter to use Z as forwards, and Y as up
Noted,ty
Im gonna try wait
okay it works
its just
really
really weak
let me turn it up
ok this is weird
I turned it up
by *10
and its the same
just a really weak push
but atleast correct direction
im gonna do *100
are you chaning it inside inspector or code?
code
ok I changed it in the inspector and I got yeeted to heaven so it works, thanks
Hello everyone, I can do whatever I want as software in unity, but I write unhealthy code. For example, I always use bool or something. How can I advance myself?
In general, looking into programming patterns and S.O.L.I.D might help, though it depends on the specific problems your running into, could you provide some sample code that youd like to find a better way of approaching?
What's wrong with bools?
i am looking for my sample code. I will throw.
I'm using it in an update or something. in terms of performance.
its canon event bro I underestimated hardware and still do idk but bool aint nothing 
are you referring to constantly polling bools in Update to be alerted when another object does something? if that is the case, look into events. but your question is rather vague and there isn't really a single definitive answer to it other than study design principles and get better at logic
Sounds like a complete non issue unless you've actually profiled your game
The whole bunch of GetComponent() and FindGameObjectWithTag() calls is what would hurt the performance the most here, not booleans
Especially when it's done ~50 times a second
I'm trying to learn the principle of working with different classes. I can't. looking for advice
Yes. for example
what do you mean?
position is needed.
Is there more than one ship?
No worries
yeah, I haven't read the conversation before and thought that was your full question
So you cache the ship, and just get the position when you need it
no
what principle?
you mean you don't know why you shouldn't just paste everything in one script?
or why you should make multiple classes in one script?
working with different class
Exactly
in more detail, please
So, is it possible to make a UnityEvent that has a Vector or multiple arguments? So far, those functions seem to be unavailable in the inspector.
for example
Well, there's the SOLID principle, which you can google. But I'm not sure that's exactly what you're asking for
yeah, you probably need it
trying to get one that moves a player to certain coordinates with a Vector3, but I can't put that function in the UnityEvent.
yes
just make sure not to inherit classes from MonoBahaviour in one script
I look. Thank you
you can make classes with quite a similar meaning in one script
if you load data from json, you probably will have data class in the same script
it's possible, ofc
how can I do it ? Is there any documentation I can look at?
to do what?
json you mean?
I don't think you need it now
MovePlayer(v3) and RotatePlayer(quat) are the notable ones here.
I have just gave you an example that first came to my mind @fiery wagon
So where should I start?
with json?
see some tutorials
google => json with unity
"loading data from json unity"
"saving data to json unity"
ok i will look. Thank you for your attention.
I think they inherit from Event
: Event<Vector3>
: Event<Quaternion>
Please course-correct me here.
that's what you need, as I have said
you should inherit from event
you create your class that inherits from Event of type Vector3 first
then serialize it in another class
subscribe it
and Invoke when needed
pretty easy 🙂
am I able to set the coordinates in the inspector this way?
this shouldn't be necessary unless using a really old version of unity
2022.1.23f1
I am pretty sure that the documentation that I have sent is 2022.3
yeah but the docs haven't been updated. inheriting from the UnityEvent class hasn't been necessary since before 2020.1
I think no
do you have another idea?
that's important here so I don't need to do a wild workaround
oh, try it
with [Serializable]
should work
I have never tested it
and see this post
still don't see it
you have to make a field of type UnityEvent<Vector3>
inheriting from UnityEvent<Vector3> to create your own serializable class is not necessary
I see, if it works then nice
why should it even be in EventCollections class?
I see, nice then
it does because as of 2020.1 unity can serialize fields of generic types
because my events need to be in a different class due to how the interactables in my game work. And no, no source code is being changed, I'm nowhere close to that proficient with Unity.
EventCOllections is built-in class
not yours
you should try to find it in your class
it's EventCollection, not EventCollections
yes, it doesn't matter
you will just find your method there
read the documenation I have sent how to do it
and don't forget that you don't have to create your custom event class
as boxfriend has previously mentioned
What's the correct way to remove a listener added with a lambda like this?
unityevent.AddListener(() => { // Whatever
});
Or will it automatically disappear as it exits the scope of the parent method?
store the lambda in a delegate variable and pass that to AddListener or subscribe using a method
i feel like i’ve done something like that before, where the lambda stays in scope
but I’m not sure if I used a delegate
then you can remove the listener using the delegate variable or the method
Makes sense. Thank you.
I have a bit of a graph theory coding problem.
I have a directed graph that may contain cycles and logic at specific nodes to turn them on/off with electricity. During runtime, certain nodes will light up and pass electricity to any node it can reach. The issue is that some bits of logic might run into conflicts when I have cycles, and I’m not sure how to resolve them.
how do i get "rb.velocity = (moveDir.z * transform.forward + moveDir.x * transform.right).normalized * runForce;" to ignore the y velocity and leave it unchanged?
float yVel = rb.velocity.y;
Vector3 newVel = (moveDir.z * transform.forward + moveDir.x * transform.right).normalized * runForce;
newVel.y = yVel;
rb.velocity = newVel;```
something along these lines
is there a way to do it in the single line of code?
sure but it would be significantly uglier and less performant than this
can you send it anyways
a what
my dude you're not giving me homework lmao
you're good though, thanks for the help anyways
I have a question about the math in an algorithm I found. Is this the place to ask that question?
Hello, I'm new to Unity so sorry if this is a stupid question, but I just can't figure it out or find anything relevant.
I have a unit prefab that work perfectly fine until I put 2 of them in the scene, if I do, then when I hit play they all disappear except for 1.
Does anyone know how to fix this?
The object returns when you stop it, it disappears from the hierarchy as well.
Sounds like a problem with your code
can't say anything more than that without seeing the code, naturally
hi ,
i'm unable to open cginc files on visual basics all the sudden
when I open any file it opens limetext instead, how do i fix this ?
What kind of problem in the code could cause something like this?
presumably your code is destroying the object.
at an inappropriate time
i tried unloading and reloading the project in VS 2 times , didnt work , restarting unity didnt help either
I'll check it out, thanks for the help, if I can't solve it then I guess I'll post the question again with the code.
My GameManagerGlobal script is added to "DoNotDestroyOnLoad" on Awake:
private void Awake()
{
// If there is an instance, and it's not me, delete myself.
if (Instance != null && Instance != this)
{
Destroy(this);
Destroy(gameObject);
return;
}
Instance = this;
-> DontDestroyOnLoad(gameObject);
gameState.Reset();
GetComponent<PlayerInput>().enabled = true;
GetComponent<InputControl>().enabled = true;
if (gameState.currentLevel == "")
gameState.currentLevel = SceneManager.GetActiveScene().name;
SavePreferences("Default_Game_Settings");
LoadPreferences();
}
, but I still get
MissingReferenceException: The object of type 'GameManagerGlobal' has been destroyed but you are still trying to access it.
when I change levels. What I might be doing wrong?
you sure that's the correct line for the error?
nope, I get it when I try to launch invoke
if (scene.name != "MainMenu")
{
//wait a frame or two to ensure everything loaded and set itself up
Invoke(nameof(LoadingTimeout),0.1f);
}
In my post-load-level bit of code.
Show the actual full stack trace for the error
basically I'm confused why you highlighted this line:
DontDestroyOnLoad(gameObject);
If that's not where the error is
MissingReferenceException: The object of type 'GameManagerGlobal' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.Invoke (System.String methodName, System.Single time) (at <4a31731933e0419ca5a995305014ad37>:0)
GameManagerGlobal.OnSceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at Assets/Cliffworld/Scripts/CoreGame/System/GameManagerGlobal.cs:160)
UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded (UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode) (at <4a31731933e0419ca5a995305014ad37>:0)
Line 160 is the Invoke line.
can you show where you are subscribing to the onSceneLoaded thing?
I highlighted it to show that it should be added to the DoNotDestroyOnLoad list, and it does show up there (though as a "clone")
"as a clone" means that you are creating it via Instantiate
Here's the whole set of functions involved in the level change, JIK:
public void ChangeLevel(string levelName, string spawnPoint = "none", bool loadSave = false)
{
-> SceneManager.sceneLoaded += OnSceneLoaded;
playerState = player.GetData();
if (!loadSave)
SaveSceneData();
nextLevelName = levelName;
levelSpawnPoint = spawnPoint;
levelChangeIsSaveLoad = loadSave;
DevLog.Log("Loading scene '" + levelName + "'...");
//TODO: change level fade-out
inGameplay = false;
InputControl.Instance.SetControlState(ECState.Character_NoMove);
Invoke(nameof(BeginChangingLevel),2f);
}
public void BeginChangingLevel()
{
SceneManager.LoadScene(nextLevelName);
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
DevLog.Log("Loaded scene "+scene.name);
if (scene.name != "MainMenu")
{
//wait a frame or two to ensure everything loaded and set itself up
Invoke(nameof(LoadingTimeout),0.1f);
}
levelSpawnPoint = "none";
gameState.currentLevel = scene.name;
}
private void LoadingTimeout()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
FinishChangingLevel();
inGameplay = true;
}```
SceneManager.sceneLoaded += OnSceneLoaded; seems like you're never unsubscribing this
SceneManager.sceneLoaded += OnSceneLoaded; should go in Awake and SceneManager.sceneLoaded -= OnSceneLoaded; should go in OnDestroy
Remove SceneManager.sceneLoaded += OnSceneLoaded; from the ChangeLevel function
Will it fix the error? I made it this way because otherwise OnLevelLoad fires when it shouldn't.
yes it will fix the error
the other option is to leave it as it is but add SceneManager.sceneLoaded -= OnSceneLoaded; inside OnSceneLoaded
Okay, thanks, I'll think of other way to stop OnSceneLoad from firing.
try this @thin hollow
I replaced unsubscribing and subscribing with a bool check, and it seems like it worked! Thanks!
guys
one of cginc files doesnt open on visualStudio because of this error An error occurred in 'Assembly-CSharp' while attempting to open 'filename.cginc
what should I do ?
it was working before, but I think my pc had unplaned shutdown and this happened
ok I have noticed that the code have turned into 00000000000000000000 somthing like that
is it reversable ?? , i have an older version of the file , should i go back to it or is it fixable ?
I think the file is busted , that looks scary but it actually works , it does what it supposed to do , its just not in form of code anymore.
ayo what is this for
oh its for shader basically, but looks like it's corrupted without a way to fix it, i've no idea why it gone to this for an unexpected shutdown, if i remember correctly my pc was on sleep mode , yet the file got corrupted nonetheless, im bking everything up now.
If random range is maxExclusive shouldnt I be doing this? bc sometimes is out of range
is it really maxEclusive? because i dont think so even if its said when hovering random range
don’t add the + 1. .Count is already 1 higher than the highest accessible index
I thought Random.Range is max inclusive?
I swear the parameter name on the function is literally maxInclusive
for floats
the int overload has maxExclusive
Will anyone like to he,o with my game
hey so for some reason my "looking around" script only works by looking up and down< i cant look left or right, im pretty sure ive done everything right tho
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ViewingScript : MonoBehaviour
{
[Header("Mouse Settings")]
public float mouseSensitivity = 1;
private Vector2 _currentRotation;
private void Update()
{
DetermineRotation();
}
private void DetermineRotation()
{
Vector2 mouseAxis = new(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
mouseAxis *= mouseSensitivity;
_currentRotation += mouseAxis;
_currentRotation.y = Mathf.Clamp(_currentRotation.y, -90, 90);
transform.root.localRotation = Quaternion.AngleAxis(_currentRotation.x, Vector3.up);
transform.parent.localRotation = Quaternion.AngleAxis(-_currentRotation.y, Vector3.right);
}
}
You are most likely overriding the rotation you have set previously.
Try this instead
[SerializeField] private float speedH = 2.0f;
[SerializeField] private float speedV = 2.0f;
private float yaw = 0.0f;
private float pitch = 0.0f;
void Update () {
yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
}
I feel like that makes sense, otherwise it would be something so incredibly close to the upper bound it would be rounded to it in many cases anyways. Right?
possibly…, random numbers are a big mystery to me
Same. I only recently ran into the issue where using random would always do the same numbers without a variable seed (i used time.time)
Is that the preview in unity editor? Did you try to open it in a proper ide/text editor?
yeah i tried to open it in visualStudio, it immediately opens it in Sublime text which was pretty weird, and what is even weirder is that it doesn't have the code anymore, just 00000000 as i mentioned above with a screenshot, i didnt even notice any 1 its all just 0s and surprisingly, the shader was working on the unity editor .... i have no idea what was that .
all other similar files even with the same formate opens normally with the code written on it and perfectly working as well
Can you share the file?
i had my own backup file from yesterday and I have just finished redoing all the code.
unfortunately nope
Okay
sorry, i signed a Non-Discluser.
i will just try to understand how is it still working where all what is written on it is a bunch of zeros , i havent seen a single 1
more on that later.
that might be the best encryption method LOL
CanSomeone help me I forgot how to make my character move in the forward direction
private void FixedUpdate()
{
if (playerRigibody != null)
{
playerRigibody.velocity = new Vector3(inputVector.x, 0, inputVector.y) * speed;
}
}
I think I use vector3.forward right?
or transform.TransformDirection
how could I only have a parameter if a bool is enabled?
so If I use Vector3.forward would that be applied in the fixed update movement or in update getting input vectors? or either way?
A parameter to a method? Or what?
either way. but transform.TransformDirection is cleaner tbh
a parameter to a constructor
for a scriptable object
basically, if something is craftable I want it to have a requirements parameter
Hmmmmm, i do not know. I know you can have multiple constructors.... but...
I thought about doing the craftable ? reqs : null or something
on the line you have selected is fine, or immediately above that line
bro what
pass in your input multiplied by speed to TransformDirection, not Vecto3.forward. and use the returned value to assign to velocity
transform.TransformDirection(Vector3.forward) would just return the same thing as transform.forward
Is it possible to GetComponent in EditMode?
I know it doesn't work, but is there a work around?
Sounds like you wanna have CraftableThing inherit from NormalThing and add this as a Constructor param