#archived-code-general
1 messages ยท Page 165 of 1
i just got it of the documintion https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Not sure if this is the best channel for this, but it does include code so I will post it here. I have a simple player controller in a 2.5d demo game. When using the "Windows, Mac, Linux" build preset, everything works fine. However, when switching over to the WebGL build preset, the player continues moving for a second or two after the key is released. Does anyone know what could be causing this? I have attached the code, a video of the issue, and a screenshot of the components attached to the Player GameObject. Thank you for any help that you can provide.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
public float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
controller.Move(move * Time.deltaTime * playerSpeed);
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
Never mind, figured it out. I think that the character controller physics are designed to have it gradually slow down, however normalizg the movement vector caused the magnitude to always be 1 (even when it should have been lower to slow down). Adding a simple if statement that only normalized the input if the original magnitude of the vector is greater than or equal to one seems to have solved the problem.
Hey guys, just looking for some help with an implementation here.
So I've got inventory items that all implement an interface IEquippableItem, which has methods like OnFireKeyStart, OnFireKeyEnd, OnReloadKeyPressed, etc.
My problem is saving. Because the inventory system stores a variable of IEquippableItem for its selected item, I can't serialize and save it. What I've done is create a Dictionary<string, IEquippableItem, then save the string with a dumb search method to find the string from its value, and load the item based on its string value.
I don't think this is the optimal solution, and it definitely isn't considering I want to be able to save item data too. Any suggestions?
I was considering adding an OnSave method which returns a string of all the data that gets serialized, but I'm curious if there are any other ideas.
(By "item data" I mean data for individual implementations of IEquippableItem, for example a firearm implementation might want to save its current ammo and other stats, while a medkit might want to save use count)
I would just make some separate class/struct which gets saved and holds all possible information you want. That class can just hold the string (which im guessing is ID), ammo amount, stats, etc.
then when you want to load, grab the ID and lookup which equippable it is, plug in all the stats
For each item?
Not all the items would have the same data that needs to be saved, surely it'd end up with a ton of null variables?
i wouldnt save every single item, you can represent all of them in like an SO. In terms of the null variables, are you really gonna have that much difference between them? A few variables that get ignored really arent an issue
Yeah, there's a massive difference in data types because each item is very different
So what I was thinking of doing is adding an OnSave method to IEquippableItem, which returns a string to serialize
Then in the constructor it grabs the string data from save file and parses it
you might have an easier time just creating a struct/class for different types of objects then, because at least then you'll be able to easily deserialize it. Serializing is easy, you can literally just write an anonymous type
new { x = something, y = somethingElse }
call JsonConvert.SerializeObject on it, and WriteAllText it (assuming you're using json).
the annoying part is just getting the data out without having an exact data structure for it
Alright, I'll try it out. Thanks for the help
qq: is there best practices for how to handle Steam failing to init from Facepunch.Steamworks? Would it be acceptable just to quit the app as bare bones drm?
https://partner.steamgames.com/doc/sdk/api#initialization_and_shutdown
theres some info here like SteamAPI_RestartAppIfNecessary. Honestly facepunch's documentation is so lacking I dont even know what you use in there, if you find something let me know because i need it too ๐
ah facepunch has it under a similar name
https://wiki.facepunch.com/steamworks/SteamClient.RestartAppIfNecessary
but this is more #archived-networking related. you might get more help in there although i notice not many people talk about facepunch ever
Hello, I'm having issue with the following code. https://gdl.space/ecojezinon.cs
The code is for controlling a 2D character and I'm attempting to run a coroutine that makes the character "ground pound". The intention is to check if the character is on the ground and, if he isn't, allow the player to press "S" to initiate a ground pound which holds the character in the air for 1 second before moving him downward quickly until he is grounded again. When trying to execute the code, the character will hang in the air but then the game will freeze once it attempts to start the downward movement. I've whittled it down to the "while (IsGrounded()==false)" command as the culprit of the crash but I'm unsure on why this won't work as programmed.
How do I get the value of a custom variable that I've assigned to a gameobject
I am trying to run a script so that if a room is placed in a green square, the red one will run a method to recompute its walls. How do I make it so that when a user places the green room, all adjacent rooms will run a method?
I will refer to the gameobject that you are getting the variable from as fromObject . If you are trying to access this variable from another class, you need to create an object from fromObject's class by fromObjectClassName localVarName = new fromObjectClassName(some parameters). To use that variable elsewhere in your code, use localVarName.
fromObjectClassName would be the script fromObject is using that stores the variable you are using
something like neighbor checking
yeah I'm asking how to do neighbor checking, are there any good sources about how to implement neighbor checking?
ideally you want have some sort of grid system / tiles to tell if neighbors do exists with some algorithms
nodes and such
check if tiles / nodes are occupied
like that
ah, ok
is there a good way to do that? Every room is some multiple of 3m x 3m x 3m (6x6x6 unity units) but I don't know how to create a genuine grid system, I have more of a faux grid right now
what kind of system ? it can really be as simple as doing a 2D array or you can even just make a center point on each room and lay those out on grid based on Vector3Int
btw 1 unity unit = 1m
this series might help you out
https://www.youtube.com/playlist?list=PLcRSafycjWFepsLiAHxxi8D_5GGvu6arf
yeah every room has an empty object as a centerpoint for parenting and localization purposes, how do I "send a message" to it to run the killChildren method to remove walls?
ideally you loop around the area you're placing at
do the neighboor checking and run methods on them
I have ways to know if there are methods I just don't know how to get the neighbors to run the methods after I detect them
I'm getting a weird issue when using a lerping value as a variable. returnSpeed has a value of ten and returnSpeedP is just a constantly decreasing value. When I enter returnSpeed as the variable multiplied by deltaTime (highlighted yellow), I get no errors and it works as intended, but when I enter the lerping returnSpeedP I get errors saying the Quaternion is a null value (NaN, NaN, NaN, NaN). Not sure why this happens and I can't seem to find anything about it online.
quickest way I can think of rn is a 2D array
make it a bool one and set occupied true for all filled tiles
dictionary would probably work too tbh
The first two variables of lerp shouldn't change until you get all the way to b.
Looks like every lerp has a changing a parameter
Oh, yeah and they are setting back to the same variable
wydm by "b"
Lerp(a, b, fraction)
okay I see
Is there a way to lerp at a changing rate?
because doesn't deltaTime already change?
You would modify the last parameter (what I called fraction). Which yeah, is what you're doing with deltaTime.
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
So multiplying the time parameter wouldn't work? Would I have to change the parameter itself's value?
You need some form of "Parent" service that manages all the rooms, and stores a reference to every single room.
Ideally as a Dictionary<Vector2Int,Room> or whatever.
All your CRUD operations to mutate rooms should happen in that service.
Not sure what you mean.
The NaN issue may be unrelated to what I'm saying. What I was saying just jumped out at me. I think it's an issue with the rotations being unset until used in the lerp and slerp
Are targetRot and currentRot set earlier? How?
Yes, they are set by some sin functions earlier in the code
The code runs perfectly fine when just deltaTime, it's only when I'm using the lerping value do the quaternions throw a fit
Then it may be about setting the same value as the first parameter. Like targetRot is the variable you store lerp in, but also the a parameter
Quaternions are really tricky. I have to look into that more
Yeah I've been trying to figure them out as well, I came upon this potential solution becuase you can't really easily subtract quaternions so I'm using this method as a workaround
you can add by the inverse of a quaternion for subtraction but it's still funky
Yeah, I am not sure what is going on. Sorry.
S'all good, I see if the unity forums have any wisdom, or i'll just bump this later.
what would the reference include and how would I do this?
that's weird to use the Time.deltaTime for t in your Mathf.Lerp as its the interpolant clamped between [0, 1]. returnSpeedP is not lerping at all; it's set to a value very close to itself, slightly closer to 0 each time . . .
Yeah I know it's weird and I know it's usually not recommended. I agree, but I'm using it as an easing function that never needs to hit it's target value
is there a better way to wait an amount of time then
timeelapsed += Time.deltaTime;
if (timeelapsed > 2f)
{
// do action
}
specifically in the update function not in other functions
What are u looking to do differently?
Is there something in this you're wanting to avoid?
not specifically, I just try to avoid if statements and nested code where I can
I would've suggested a coroutine but you wanted it to not be another function
oh sorry I just mean Im running it in the update function mb, sorry
That's pretty much the bare minimum of a timer though
In general there is nothing wrong with using if-statements, there are probably other ways you could change the readability, though if you wanted to remove the "+=" deltatime logic, you could make the time you want to wait a variable and use Time.time instead to check for a difference, this will tell you the time since the scene loaded, for example:
if (Time.time < timePassed) {return;}
DoSomehingInteresting();
timeePassed = Time.time + someWaitTime;
I use this approach often, to exit if there is still a cooldown, otherwise do the logic and add some value to the time to wait in the future, you could even have a "remaining time" for some UI by subtracting the Time.time from timePassed if you wanted
Thank you both so much!!
writing the logic of an if statement on the same line is ๐คข imo
Understandable, I personally like using one-liners if the logic inside { } is basically just a single keyword (I do the same if a property is only a get;set;), and it looks more compact on Discods codeblock, but I also understand not everybody likes one-liners lol
whenever i see stuff like that, i just assume the person wrote it to save on line count. For some reason people thinks it matters
Its all personal preference imo, some programmers I know like
if (condition){
}
Others
if (condition)
{
}
And some
if (condition){}
They all do the same thing, though I find the first are often preferred by programmers I know with a JS or web level background, imo it just looks odd having only 1 short line in between brackets more than "lines cost too much so save on them"
I always like single line if statements for empty returns, just makes it clear the contents of the if statement isnt that important
people generally like to act like they have a preference for one of the first 2, but i would bet that 99% of the populations preference is just whichever their first IDE used.
its just not as readable, its expected that the logic is at least on the next line. If your if statement is long (character length) as well, the logic may have to be on the next line so its not far off the screen
So it just doesnt really make sense when you could just do
if(condition)
something
in all cases
ya I can see that especially for a team of multiple people
Thats a good point, and yes on a team project its best to go with whatever convention the codebase is using, on solo projects its fine to go with whatever your preference is, I personally always like seeing the { } on any if-statement even if its not on one line, in my mind it makes it more clear what logic is meant to be grouped together, but thats entirely a personal thing for me
I also bet alot of people who started with python really prefer options 1 & 2 seeing as one line if statements are mostly impossible
for me it's . . .```cs
// C++
if () {
}
// C#
if ()
{
}
// Return or one-liner here.
if () { return; }
Heretics
I prefer if(){
}
In no matter what languages
I follow the C# standards except I use tabs not spaces (spaces are truly cursed and I will never understand their reasoning)
I do that normally but visual studio audomatically turns if(){ } into
{
}```
I think there are settings to change the "code style" defaults per-language in VS as well: https://learn.microsoft.com/en-us/visualstudio/ide/code-styles-and-code-cleanup?view=vs-2022
does anyone know why my intelliSense isn't working even though i have the C# extension enabled?
vscode?
!vscode
Have you used C# observable collections or custom one? to update for example a list based on changes data
Whats a good way of checking if the player is looking left or right in a first person 3D environment ?
Mouse delta does not work very well.
How are you first determining forward
Wdym??
how do you define direction? eg head and body are two different transform you define the forward as body.transform.forward, then your problem is solved
Can I create an editor like UI in game? I want to add a tool for creating some data and there will be lists of values, is there a convenient way to add the dropdowns and + and - buttons? Possibly with my own textures?
I am very confused lol
I'm using the input system and adding to move dir and multiplying it by the force
Movedirrelative = orientation.forward * movedir.z + orientation.right * movedir.x;```
rb.AddForce(Movedirrelative.normalized * Force * 10f, ForceMode.Force);```
Yes, you should be able to. Not entirely sure what you mean though
So the funny thing about this BTW is, once upon a time it did, and still does in specific niche areas.
Namely, there is a practice of printing code off on paper for code reviews for security / protocol reasons.
IIRC, NASA still does this, and some other places where human lives depend on code. You can look up NASAs code standards documentation, they have a big list of "must do"s and "never do"s, it's actually quite fascinating haha
Is there a delta for camera rotation?
Are you trying to do data binding, or just update some JSON file or List<string> or something similar? Also is your system intended for your team to use in a build or for players to use in release? Im also guessing you are using the Canvas system as opposed to UIToolkit or another way of handling UI?
Can Anybody help
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
m_ShootingSound.Play();
else shooting = Input.GetKeyDown(KeyCode.Mouse0);
This code
has an error
it says that 'else' cannot start a statement
how do i make it play the shooting sound when i click mouse0?
This is why we use {}
Please for the love of god encapsulate
if()
{
}
else
{
}
@mellow zinc
Canvas system, players add some things to their game, not sure what you mean by data binding, but I want them to add data to the game for the data to later be used later in the game. Not modifying existing data, but creating your own. Like creating character configs
How do I loop through polygons on a mesh?
I dont really know how to word this since im fairly new but i have the enemy object on the left that keeps getting stuck where i drew the red arrow. itll keep running into it unless i move the player in a different direction. Does anyone know a fix or how i can make it repath or something.
meshes are defined by vertex and triangle arrays - it's implicit that every block of 3 elements in the triangle array define the vertices for that triangle
So, I can not get a polygon by it self?
like if i wanted to loop through each of these faces/polygons, can I do that?
they are all flat
help when i walk left the player doesnt look too the left
Vector2 moveDirection = new Vector2(horizontalInput * speed, rb.velocity.y);
rb.velocity = moveDirection;```
Ah I see, ill give you an example of what I meant by data binding, maybe it could give you some ideas - for one project I wanted to make it easier for our designer to generate and edit Scriptable Object (SO) files in a build, essentially using the SO to have UI fill a resizable "container" with rows of prefabs setup for certain data fields (like a "int row" for numbers, "text row" for strings, "dropdown row" for enums, etc), changing data of those rows, are bound to set the value of the SO, or JSON file or any other approach, this could be useful if you need to save/load this data back into Unity or maybe through a "workshop" server, but if this is just for a session or to sync over multiplayer, maybe data binding isnt very useful
Creating character configs sounds like you could largely edit/create JSON files from a serialized class, and maybe take a similar approach to looping through data types to generate prefab "row types", then instead of binding the data, store it in a class instance and create a new file or overwrite an existing file with that instance - is this what you might be looking to do?
You dont ever rotate the player, you only give it force in a direction.
i know but how do i rotate the player its the fist time worked whit Input.GetAxis
is it a 2d game
yes
then you rotate the player left or right, depending on the velocity
whenever the player moves
private void Move(){
horizontalInput = Input.GetAxis("Horizontal"); // Left Stick
Vector2 moveDirection = new Vector2(horizontalInput * speed, rb.velocity.y);
rb.velocity = moveDirection;
if(horizontalInput < 0){
//rotate player left with either using another image of the player or somehow mirror the image, idk I haven't done anything 2d
}
else{
//rotate player right
}
}
thanks
Does anyone know how/if I can loop through every polygon/face?
since I need to loop through every polygon on a mesh and convert the polygon to a ConvexPolygon2D
Im not sure if theres a built-in utility API or something, you could maybe checkout a video on "mesh generation", CodeMonkey I know has a good one, AFAIK, the mesh only has verts, so you would have to group those verts into what you would define as a "face" within that collection of verts, I think TextMeshPro uses something similar to group individual characters from vert data, though that goes above my head
yes and no, there's no one liner to do it afaik, likely you're going to have to build up that structure by traversing vertices and decide how you want to format it yourself. Blender might have better tools for automating that than Unity, but I'm not familiar with it
Is there any way at all to make methods that don't belong to any object or class? I'm not 100% against making a dummy wrapper class, but I don't really want to unless I have to.
Not sure if it makes a difference but I wanted to have a dictionary with delegate as the value type, so the methods could be invoked by anything with access to the dictionary, so for that reason having the methods belong to anything doesn't really seem necessary to me.
Actually hold on, I possibly have an idea. Can I possibly follow all of the vertices and the edges they make up to get all the vertices that make a face?
like if 4 edges make up a face/polygon, can I detect that?
god dammit I suck at describing my ideas
hello, is there a channel wher i can get helped?
yes
oh, where?
depends on what kind of help you need
i need help with unity, literally. i dont know how to turn a 2d object to a photo
like what do you mean loop? if you have the vertices represented by vectors, you can just make an array or list of vectors, and do foreach or a for loop
possibly, but you'd need to know the edges - I think if you imported this mesh into Unity you'd lose that information?
In this picture, I have a bunch of faces that make up a "glass shatter map". I want to go through each of these faces on the map aka get the vertices that make each of the faces up
I'd look into what blender can do for you first if you have access to it personally
could someone help me pelase?
Ask the question you asked in like unity talk or code/begginer
ok thanks ๐
yeah i feel like that would be hard, i was dealing w/ a similar problem and it seemed like the only solution would just be an algorithm that has to check literally every possible combination of vertices to check if each one makes a face
which is obv less than ideal
I mean, I am trying to make what was explained in this video https://www.youtube.com/watch?v=nuHg6_IIyK8 (important parts are 0:30-0:35 and 1:00 to 1:15). They make it sound so easy and I feel like there is an easy-ish solution to this
In this video, David shows you how we made the glass breaking effect in Receiver 2.
โข Get Receiver 2 - https://store.steampowered.com/app/1129310/Receiver_2/
โข Discord - https://discord.gg/Wolfire
โข Reddit - http://www.reddit.com/r/Receiver
โข Instagram - https://www.instagram.com/WolfireGram
โข Twitter - http://www.twitter.com/Wolfire
โข Facebook...
I the video at around 1:05 he says that he broke the polygons down into triangles and extruded them back as 3d models, but before that he needed to cut away the part of the fracture pattern that extended out of the bound of the glass. That is the thing I'm trying to create right now, to cut off the part that extends too far. But for that I need to maintain them as polygons right? since if I did it with triangles then I couldn't really put the remaining parts back together right?
does anybody know how to make gun audio with a raycast shooting script
What could blender do to help?
split the mesh to solve your original problem immediately perhaps
The only workaround I can think of is to make every face into separate objects, but that is clearly not what was done in the video
wdym split the mesh?
like do this?
probably the easiest solution, but yeah like in the video, each shard can be further divided by more shots
you're right, he does make it sound really easy, and just gives like 0 insight into it LMFAO
my geometry chops are weak tho
Your question might be a bit unclear, audio and raycasts are completely independent systems, so you cant really make a raycast play audio, but you can play audio in response to calculating something about the raycast (assuming you have an AudioSource you want to use) - what is it specifically that you are trying to do? Are you trying to play audio at the point a raycast hit say a wall or crate or floor tile? Or are you trying to play a "bang" sound every time your weapon is fired? Or are you trying to do something else in specific?
yes
Im trying to make a shooting sound when the weapon is fired
I've searched up tutorial and they say to include it under my script where I have Input.GetKeyDown(KeyCode.Mouse0);
But I dont have that and I can't find where the script tells the gun to shoot
Generally when your shoot logic fires off (from input or an event or some other way), that is a good place to handle playing audio, but does depend on you Input solution and code setup (for example, are you using the Input class and KeyCode enum, or the "new" Input package?) - did you write this script yourself or followed a tutorial or copied it from somewhere online? Could you also show the full script? You can use a code pasting site like pastebin, hastebin, pastemyst, etc
I followed a tutorial and heres a hastbin https://hastebin.com/share/onudecawon.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ah I see, it looks like you have a Shoot function that gets called from your input, that could be a good place to play audio, and it looks like your storing all your references in this class as well, so you could make a public reference for the AudioSource
how would i do that
Sorry I dont understand, are you asking how to create a public reference?
Generally, yes a variable or reference is <access> <type> <name>, in your case public is the "access" and AudioSource is the "type", the name can be whatever youd like (within reason of syntax), though how familiar are you with C#? Specifically, how much of this script do you currently understand what its doing?
Im empty on C#
Ah I see, personally I would maybe start with C# basics tutorials first (with Console applications or maybe even WinForms if you prefer visual learning), before hopping into Unity, mostly because the engine itself, has a lot of "syntax sugar" and can be confusing building a game with only relying on tutorials for super specific things (like "how to make a gun"), if youd like a good understanding of the engine "Unity Learn" may be a better starting point imo than specific tutorials, so you get to learn a good understanding of the basics of how everything from simple to complex is generally structured, then tweak that to your specific preferences
i have done a couple of tutorials on unity learn
like completed them
Did you understand the code and the projects you completed? Or just went through the steps they outlined mostly cause the tutorials said to do x step next?
I understood them
Ah ok, thats good then, if you personally feel that you already have a good understanding of the basics of C# in general, I would continue to go through more of their projects to familiarize yourself with the engine more and maybe refresh on how references and data works in Unity, but also try to understand this script or any script you find, and the reasons why certain code is structured the way it is or why it even exists in x script, that way itll be easier to follow the logic of the script to make small changes to it and eventually write your own unique scripts from the default Mono template (or a blank script file entirely)
Np, hopefully that helps out with your current problem as well, if not after trying some things, you could try asking again later with all the info we went over in #๐ปโcode-beginner for further help, GL
ok
Hi everyone
I understand it is best to provide a code snippet but i dont have my laptop with myself
Ive been encountering a weird glitch with using Raycasts for wall detection.
I cast two of them for two of the walls and they work fine when above 50 fps but if i drop my fps to sth like 30 fps the wall run starts and stops immediately
Now the weird part is, this only happens with some scenes. If i save my player and level as a prefab and create a new scene everything works fine even at 15fps. If i create another scene the bug has a random chance of appearing
And it wont go away
I even modified the code with fixeddeltatime but it still happens randomly
Its not even consistent
I think that kind of problem might need more context, when you are able to access your laptop, it may be good to provide the code your using for raycasting and where you are using it, off the top of my head with the description you gave, it could be many factors, it could be the distance or direction of the cast, the cast could be hitting a internal collider (if the origin is for example, from within your player collider), gravity could play a part or some other factor - you can also use Debug.DrawRay (https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html) or Debug.DrawLine (https://docs.unity3d.com/ScriptReference/Debug.DrawLine.html) if your using a raycast to get a better idea whats going on in the Scene view as you playtest your game, or Vertx has a very nice package to visualize the rest of the Physics class if you are using a shape like a SphereCast or something: https://github.com/vertxxyz/Vertx.Debugging
Looks like properties of my ScriptableObject aren't serialized. If I add an extra public string on it, I can see it persists, but the data I actually want to use seems to ne wiped on domain reload?
(I have a custom editor window to list what's in the dictionary, WorldLocationType and SceneName are enums)
```
Seems like this ^^^won't serialize on a scriptable object?
Unity can't serialize Dictionaries at all
You can try SerializableDictionary, for example. It is 3rd party
well... that explains it. nah, I was just confused. Can it do lists? I can build the other stuff on deman it's just for displaying and house keeping at runtime I just need a list really, thank you!
Lists are fine. HashSets not
You can't mute people because you do not have moderator rights here
<@&502884371011731486> Shitposting
You agreed to rules entering here, please follow them
Your spam here clearly shows otherwise
!ban 1137393118984028301 Shitpost account
johndev0598#0 was banned.
can anybody help, when I start the game my main fps cam just starts slowly going up until a certain point https://hastebin.com/share/ijujizefuh.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how would i fix that
There should be only line 31, if I'd guess
so i should delete 32?
Maybe? The script makes use of multiple positions
You should know, you wrote that right?
nope
Start by writing your own instead of blindly copy-pasting from others, and it'll be better
ok
If you need tutorials, there's the Unity !learn website
๐งโ๐ซ 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/
ok
What's a good way to debug why the unity editor freezes (I'm on osx, it just spins the beachball and is unresponsive, I can forcequit the app). I'm pretty sure it's my code somehow, but not sure what it is exactly)
Any infinite loop will cause the editor to freeze. Search for anything that would cause that. for and while loops with flawed exit conditions
Attaching the debugger while playing might help, you can pause the execution when frozen, and it'll show you where the code is executing
there is no Unity namespace
there is actually, pretty sure the AI navigation package is in it
Nope, UnityEngine
mate i literally just linked you to what i was referring to
and I just screenshotted you what I was refering to
yes and i said the "AI Navigation package" which you said nope to. what you screenshot is the NavMeshAgent which, not surprisingly, is not part of the package i referred to though it is related
How to stop a navmesh agent immediately and put a new destination for it?
It seems like it wants to finsh the last destination before applying the new one using navMesh.destination = position;
call the SetDestination method on it
assigning to the destination property doesn't immediately recalculate the path afaik
Yep, that seems to work better, thanks
Hi im making a hunting simulator that works with laser detection like when you shot at the screen with laser catridge a camera detects the laser Place what do i need to get started
my bad, I was looking at an old version which was in UnityEngine.AI
using System.Collections.Generic;
namespace UnityEngine.AI
{
[ExecuteInEditMode]
[DefaultExecutionOrder(-101)]
[AddComponentMenu("Navigation/NavMeshLink", 33)]
[HelpURL("https://github.com/Unity-Technologies/NavMeshComponents#documentation-draft")]
public class NavMeshLink : MonoBehaviour
{
Hello. Anyone have experience with build Unity app for WebGL? I build my app and add it to my Asp.Net application. when it runs, I get an error that repeats: ```
Build.loader.js:1 exception thrown: RuntimeError: memory access out of bounds,RuntimeError: memory access out of bounds
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[2879]:0xb958a
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[11920]:0x3739ca
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[14690]:0x509197
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[14680]:0x508bc8
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[31482]:0x8dcf13
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[24633]:0x6bcf12
at invoke_i (https://localhost:7191/Build/Build/Build.framework.js:3:328923)
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[24650]:0x6c4338
at Module._main (https://localhost:7191/Build/Build/Build.framework.js:3:279311)
at callMain (https://localhost:7191/Build/Build/Build.framework.js:3:340108)
at doRun (https://localhost:7191/Build/Build/Build.framework.js:3:340668)
at run (https://localhost:7191/Build/Build/Build.framework.js:3:340840)
at runCaller (https://localhost:7191/Build/Build/Build.framework.js:3:339767)
at Object.removeRunDependency (https://localhost:7191/Build/Build/Build.framework.js:3:16285)
at https://localhost:7191/Build/Build/Build.framework.js:3:1948
at doCallback (https://localhost:7191/Build/Build/Build.framework.js:3:93134)
at done (https://localhost:7191/Build/Build/Build.framework.js:3:93288)
at transaction.oncomplete (https://localhost:7191/Build/Build/Build.framework.js:3:86393)
Has Unity abandoned that package? I've not seen anything changing on it for a very long time
Is it just deemed acceptable enough and left as is?
does anyone have experiance with using il2cppinspector scaffolding to build mods for unity games?
ApplicationManager* appMgr = (ApplicationManager*)(GameObject_GetComponent(gameCtrl, GetType("ApplicationManager"), nullptr));
for some reason this line gives me the error Il2CppExceptionWrapper at memory location
no, it's been updated as recently as may
it went to 2.0 has that abandoned lol
Oh I didn't realize it hit 2.0 my bad
It was in 1.1.4 for ages if I recall, I thought it was abandoned back then
Think I confused it with that
yeah it was they stripped , the one that comes with editor and they made it into this 1 package
the extras you meant
AINavigationExtras or w/e it was called
back in github days
Hello, so I have this function where, for some reason it says that the index was outside the bounds of the array over here:
Vector3[] newVertices = {
vertices[triangles[triangleStart]],
vertices[triangles[triangleStart+1]],
vertices[triangles[triangleStart+2]]
};
Here is the full function in case you need it: ```cs
private GameObject[] GetFracturePieces(){
Mesh mesh = shatterMapPrefab.GetComponent<MeshFilter>().sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
GameObject[] fracturePieces = new GameObject[triangles.Length/3];
for(int i = 0; i < triangles.Length/3; i++){
int triangleStart = i+i*3;
GameObject fracture = new GameObject();
MeshFilter meshFilter = fracture.AddComponent(typeof(MeshFilter)) as MeshFilter;
Mesh newMesh = new Mesh();
Vector3[] newVertices = {
vertices[triangles[triangleStart]],
vertices[triangles[triangleStart+1]],
vertices[triangles[triangleStart+2]]
};
int[] newTriangle = {0, 1, 2};
newMesh.vertices = newVertices;
newMesh.triangles = newTriangle;
meshFilter.sharedMesh = newMesh;
int firstEmpty = Array.IndexOf(fracturePieces, null);
fracturePieces[firstEmpty] = fracture;
}
return fracturePieces;
}
Now, this is most likely due to me being a dumbass, so I'd guess it is something simple that I just forgot :p
Well which line does it throw on, and whats the state of things when you put a breakpoint and debug it?
Vector3[] newVertices = { this line, and not quite sure how debugs could help here
cause you'll see the actual value of things and it should be instantly apparant what is wrong
There is no actual value to look at yet, since the error comes when I try to make a variable
man, it's pretty obvious that the value of triangleStart is not what you think it should be
you have 3 variables you refer to in that one line of code, all of which can be inspected to see whats wrong
and if they attach the debugger and breakpoint on that line, I bet they'll figure it out lickity split :3
indeed
Yeah, I just realised that, it just confused me because it said the error was on this line Vector3[] newVertices = { not the entire thing
Im shocked we dont have a !command for "use the debugger" in some capacity, cuz way to often the problems posted here are instantly solved with a single breakpoint
it just confused me because it said the error was on this line Vector3[] newVertices = { not the entire thing
thats the first time you try and use triangleStart
^
people have problems using Debug.Log, using the actual debugger is like asking for nirvana
but its one button press @_@;
I know, you know, they dont want to learn, too much effort
the frequency I see people using debug logging when the button is like, right there lol, drives me up the wall @_@;
'I just want to make my game, wdym I have to learn shit first'?
you guys still going on about me?
dont take it personally, please, this is just a general malaise
Yeah, it's fine, I just didn't know that unity gives you the start of the array as the line that errors not the actual line in code that errors
I have no idea what I coded wrong but for some reason my characters like always moving, btw its 3D, and when I walk of the edge the character like snapes to the edge and changes direction
For me I often get the opposite problem, "index out of range" often points to just } when opening from Unity console (I usually know what the actual problem is, just odd VS doesnt point to inside the loop)
this doesn't help.
oh I am currently investigating what script is doing it and I will paste the code
sorry
i am making a gun for my game does anyone know where i went wrong with this code
oh wait its not even a script its just the character being a child of the main camera and the main camera being a child of a gameobject
and this is the CharacterJump code:
What is not working?
this is the full code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
private float Damage = 10;
void Update()
{
if(Input.GetMouseButtonDown(0)) {
Shoot();
}
}
private void Shoot() {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
Debug.Log(hit.collider.name);
private GameObject ShotObject = hit.collider.gameObject;
if(ShotObject.GetComponent<Health>() != null) {
ShotObject.GetComponent<Health>().myHealth -= Damage;
}
// if (hit.collider != null) {
// hit.collider.enabled = false;
// }
}
}
}
also whats not working is the code
any errors?
what are they?
line 21-32 i think
"i think"
Usually the first error cascades into the others, likely resolving the first may also resolve many, or all of the other 13 errors, though whats the first error say word for word?
what does the error say?
you dont need access modifier when declare local variable
1: Assets\Scripts\Gun.cs(21,42): error CS1513: } expected
2: Assets\Scripts\Gun.cs(23,13): error CS1519: Invalid token 'if' in class, record, struct, or interface member declaration
3: Assets\Scripts\Gun.cs(23,47): error CS8124: Tuple must contain at least two elements.
the "private" GameObject
private GameObject ShotObject = hit.collider.gameObject; - private is incorrect here
Only class variables can have access modifiers (private, public, etc.)
removed private
and your vs code doesnt get configured correctly....
Do you have a script called Health?
not yet i will add one to a test object sry
well then thats why it errors
yeah i did everything
show inspector for player, also why is player parented to cam ?
for some reason when Im not even moving my character moves a littlebit and the character like snaps to the edge, ive figured out that its because of my weird hierarchy (character and the camera being children of the player gameobject) did I set something wrong?
not anymore
uh where is character jump
nvm discord stupid picture placement
its in the players inspector
oh yea
im still not used to it
true
oh ty that worked
but I still have the other bug
but it solved the main issue
the other bug is just when I slip of the edge it totally changes the rotation of the camera for some reason
oh I found the issue :D
I just had to froze Y too
tyvm
!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.
sorry to boughter you guys but how do I make this code (https://gdl.space/ogohohoyeq.cs) make the jump not infinite but just make it 1 jump until I touch the ground again
Hello! I'm having a weird issue with a class. Every time I reset my scene the List<Transform> named cameraBoundingPoints is lost (it has no elements). It appears to be reseted to default state being just new() List but from my understating it should remember it's state before entering playmode. So if a set lets say 3 elements in that list upon restarting the scene it should keep those three elements. It is also a private variable so no other classes have access to it. Does anybody know what I'm doing wrong here? I used lists a lot in my project and never saw that happen before
using UnityEngine;
public class LevelDataHolder : MonoBehaviour
{
[SerializeField] private LevelData level;
[SerializeField] private List<Transform> cameraBoundingPoints = new();
public LevelData Level { get { return level; } }
public List<Transform> CameraBoundingPoints { get { return cameraBoundingPoints; } }
}```
when you reload a scene objects get unloaded
then your new() is running again
you can use DDOL and keep the object from unloading
do you know why doesn't it happen on other classes? I have almost identical list here for example and it keeps all it's data on every scene reload:
private List<RagdollPart> _radollParts = new List<RagdollPart>() { };```
could it be because it is a attached to a prefab?
are you adding elements to the list at runtime and expecting them to persist across scene changes? or are they added at edit time?
this list is not modified at all and it is not meant to be in runtime
only in editor
then it should be loading the serialized values. what is the actual error you are getting?
i'm not getting any errors in the console if thats what you mean
so when you switch scenes the list inside the editor gets cleared ?
when I reload a scene, yes
so you're not getting any errors at all? you're just seeing that the list is empty when looking at it in the inspector?
right
are you looking at the right object
yes, I am certain about that
you're looking at the one in the scene and not the prefab, yes?
thought you just said it is not a prefab
I asked about a different case there. I used lists quite a lot and they keep their data upon scene changing, but I thought it may be due to the fact that they are prefabs
the object I'm talking about is not
inpector gets cleared, I need to find the object again in the hierachy
could you record this behavior?
right so the list is populated and the scene is saved before u switch scenes ?
yes, just give me a second
I am running into Unityframework issue. After I build to Xcode I am receiving the following errors:
.
I am believe these files are untracked by unity. therefore after the build they are getting lost somehow.
.
Any insight is greatly appreciated else I will keep on digging.
if you think this is a bug of sort you should open issue ticket
I have never stated a ticket before but will take a look into doing so. Thanks for the advice.
if you click Help in unity then Report a Bug
Guys, i am trying to create an preview of the trajectory that an object will follow, before the game runs, so i can place objects more easily into orbit, the problem is i didn't find anything or any tutorial/forum post that really helped me.
oh btw am i in the right channel?
do you have some equation that represents the path it will take? if so, you can use a line renderer and just sample different points in that trajectory equation to draw the line
i don't know what equation to do
I wanted to show it better but discord accepts only 25 MB files so I needed to be quick
how are you planning to move the object?
that is certainly odd. have you tried saving the scene before entering play mode to see if that might fix it? i would assume that it shouldn't make a difference but since the scene is unsaved it's possible that could be the cause
if saving the scene doesn't fix it, try restarting the editor because this is definitely not how it should work. unless you have some other code that is causing a new object to be spawned
looks like its losing the references cause all the children arent in the scene anymore
Well, i am using newton's gravitational equation F = G * (m1*m2) / d^2, i alreadly have it implemented and it works preety well, i want to know what path will the object, example an ball follow in the future
yes, saving the scene fix the issue. Still, I have no idea why this was happening
probably because the scene wasn't saved. so when you completely reloaded the scene, it loaded the version that was saved
most logical way is usually the way lol
unsaved changes = list gets messed up on reload scene
unity keeps all that inside a yaml file
that's not really a trajectory though, that's just calculating the force of gravity, no?
well technically it is an trajectory, depending on the speed and attractors the trajectory changes
how are you actually applying this? because that equation is literally not a trajectory. it is just the calculation of the force of gravity. it has no direction which is, you know, the point of calculating a trajectory
i mean, with timestep you could technically preview the movement, every timestep
well then congratulations, you have the equation you need. just change plug different time steps in to get different points for the line renderer
is there any extra equation i need to calculate the trajectory though
what, was calculating just the force of gravity not enough for you? i thought you said you could preview the movement just from that ๐
well i guess so, i just don't know how to work with trail renderer though
there is no "equation for a trajectory" a trajectory is a path. you need to simulate the physics in order to determine where the object will go over time. you can use Physics.Simulate to do this without actually waiting for it to simulate normally
if you want to preview the trajectory, you would want to simulate it for a given amount of time, recording its position regularly. then use a line renderer (not a trail renderer), then plug in those positions into the line renderer
- there absolutely are formulas to calculate the trajectory of an object
- what if they aren't using unity's physics? they haven't actually said how they are moving the object despite my earlier question asking them
I'm finding conflicting info on how to ensure scriptable object changes are saved. If you just use a default inspector changes either are saved automatically when interacted with or when you hit ctrl+s, but what if I have a singleton scriptable object modified from other inspectors, How do I save my scriptable object instance to ensure the changes are serialized?
If theyre not using Unity physics it needs some mathematics and physics knowledge
However if theyre using a rigidbody i found this example which might prove useful
https://github.com/llamacademy/projectile-trajectory/blob/main/Assets/Scripts/GrenadeThrower.cs
yeah. but trying to give someone asking programming questions advice in the form of "go solve an n-body problem in astrophysics" isnt very useful lol
i use this
I mean peeps create physics engines from scratch by themselves
Im too stupid to do it myself but its possible :^)
Youre using rigidbodies check the sample ive sent to get an idea how the formula works
that example only works with objects with parabolic trajecetories. if youre doing a space game with planets it wouldn't work
especially 3+ bodies, which is what they drew in their example
Hmm
i am indeed doing an space game with planets, and i plan to adding atleast Earth-Moon-Sun system
so you have a good understanding of astrophysics?
My brain stopped workin here because the last time i did advanced physics was for a high school course 6 years ago
a little
i am learning onto it
that aint gonna work, this is , literally, rocket science, you will need to understand it
well in that case i know enough of it to do this i think
not if u do it the way i suggested and just use Phsyics.simulate to let unity do it for you
how exactly do i do that?
that is irrelevant, Unity cannot simulate multi body physics, you need to implement your own
?
the above function simulates the whole scene, which can have an arbitrary number of bodies
which will apply the same physics parameters to all of the bodies which, in a multi body physics scenario is not the case
well
you would turn off the auto simulation, then apply all the forces you want, then call simulate
how i turn off auto sim?
i believe this value
by default it's FixedUpdate. but you want it to be Script when you're doing your preivew thing
so i use script to calculate the trajectory, and fixedupdate for the gravity calc?
yeah that's what i would do
I trying use fileStream to save multiple objects variables but i have no idea how to do that correctly
farthest I got was save a single object's variables
filestream is just a thing for reading/writing files
i use it to write save files
there's like 20 other steps involved in a save system
that are much more relevant to discuss
most importantly being:
- what data are you trying to save
- how are you serializing it?
I'm trying to set the position of a rect transform. This is my code, and this is what it's being set to:
RectTransform t = GetComponent<RectTransform>();
t.anchorMin = new Vector2(0.5f, 0.5f);
t.anchorMax = new Vector2(0.5f, 0.5f);
t.position = new Vector2(22, -15);
t.localScale = Vector3.one;
many things wrong
what many things?
trying to save = the variables of multiple gameobjects info script into a single savefile
serializing = BinaryFormatter.Serialize();
- the position shown in inspector is relative to its parent
- the way that interacts with world space psotioon depends on which canvas render mode it's in
- Those numbers depend heavily on the anchor preset
you'll want to look at rt.sizeDelta and rt.anchoredPosition
sizeDelta sounds like it's for stretch mode
actually it just seems like one thing was wrong, not many things. I saw a property I didn't see before and that fixes it. Thanks anyways.
I don't know how to turn that into an script after trying to think about it for some time
what are u struggling with
how can I place multiple object variables inside, if it even possible to?
YOu should not be using BinaryFormatter
it's insecure
Bro my mums getting annoyed im staying up to 2am to code lmao
Something I'm sure we all needed to know
what should I use instead?
literally anything else
most people go with Json serializers
for example Unity's JsonUtility
is it possible to JsonUtility achieve my main goal?
a save system that let me save more than a single object
YOu're thinking about it the wrong way if you're asking that
I dont know much about save file creator systems
The general appraoch is you make an object called like SaveData
and wrap all of your data you want to save in it
then you serialize that and save it to a file
Have you used observable collections or implement it to show a list of some stuff with the ability of adding, removing element
. Net also has a collection observable collections to raise events when changes
Hi everyone, I'm unsure on if this is the correct chat to ask this in so please let me know if I should ask this in a different one as I realise this is more to do with general unity then code help. But I was wondering if I could get some help on an issue to do with script re-compilation times. The company I am working for has been working on a project for a while and recently script recompelation times have gotten extreme. To the point where making a single change in Rider will cause a 1:30 recompilation, then have the editor hang for a moment then pressing play also takes about another 1:30.
This seems to be happening to everyone on the team, though I am apparently the only one who is getting fed up with it, so is there a way I could potentially fix this? Are there any ways I can avoid re-compelations happening on minor code changes to code until play mode (unless its editor only code as that I will obviously need to happen when going back to the editor). And is there anything we can do to improve the time it takes to recompile anyway?
Try visualising it to see what things are causing it to take so long https://github.com/needle-tools/compilation-visualizer
Hey people! I've been having errors (8) in a script called "XRPokeFollowAffordance.cs". The script is included in the XR Interaction Toolkit.
These are the following errors:
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(2,26): error CS0234: The type or namespace name 'Bindings' does not exist in the namespace 'Unity.XR.CoreUtils' (are you missing an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(3,42): error CS0234: The type or namespace name 'AffordanceSystem' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit' (are you missing an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(4,42): error CS0234: The type or namespace name 'Filtering' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit' (are you missing an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(5,52): error CS0234: The type or namespace name 'Tweenables' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit.Utilities' (are you missing an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(161,37): error CS0246: The type or namespace name 'PokeStateData' could not be found (are you missing a using directive or an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(100,9): error CS0246: The type or namespace name 'IPokeStateDataProvider' could not be found (are you missing a using directive or an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(102,18): error CS0246: The type or namespace name 'Vector3TweenableVariable' could not be found (are you missing a using directive or an assembly reference?)
Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(103,18): error CS0246: The type or namespace name 'BindingsGroup' could not be found (are you missing a using directive or an assembly reference?)
This is it, but please help.
(DM ME IF YOU KNOW HOW TO FIX)
Thank you ill look into this
-MonkePro2000
most of these look like you just didnt import something from the package manager. These errors are literally just tells you that something doesnt exist, when your code is trying to use it
I know that, but what package do I have to import?
Googling one of those types you can find it's in the XR Interaction Toolkit
so presumably that's not installed
Show it in the package manager
did you go through all the steps?
https://docs.unity3d.com/Manual/xr-create-projects.html#create-a-new-xr-project
step 8 lists 2 packages to install, if thats relevant
2.0.4 seems quite low a version
that's what I have, how do i update it?
not the unity version, but just the toolbox version
that's just the version of unity im using.
Did you install the starter assets via that button, or did you get them elsewhere?
I got them from that button
you can directly change the version number in package-lock.json
Odd. It says 2.3.0 in the samples directory
ok
I just had to re-import the assets. No more errors. Thanks for helping ig.
I searched a bit about it and I think it will work exactly as I want, thanks!
Hey, guys! I've just set up Git to version control my Unity project, and everything works amazingly so far. However, I can no longer see error lines in my code. Do any of you know how to fix this? I've tried a handful of things, but to no avail.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code*
โข JetBrains Rider
โข Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
wow a response came way quicker than i thought! Thank you. I'll start figuring out my IDE.
// Upper-left corner of the sprite, middle of the screen (probably)
Vector2 position = Camera.main.WorldToScreenPoint(Vector2.zero);
Vector2 size = new Vector2(texture2D.width, texture2D.height);
// Adjusting to the correct position
position = new Vector2(position.x - size.x / 2, position.y + size.y / 2);
Rect textureRect = new Rect(position, size);
Graphics.DrawTexture(textureRect, texture2D);
Yo, I'm struggling a little bit to draw a texture on my screen, tried a couple of things but nothing seems to work. Could anyone tell me what I might be doing wrong?
hii, I'm using RigidBody2d (rb), and when I do rb.velocity = new Vector3(Speed* Time.deltaTime ,0,0); the character goes very slow, no matter how much the variable speed increases, it doesn't go faster, am I using time.deltatime correctly?
you should not be multiplying your velocty by deltaTIme
that doesn't make sense
why?
ohhhhh, you're right, thank you ๐
sorry for the trouble
Might be a stupid question but how can I get my class to compile inside of NavMeshPlus's NavMeshLink class:
namespace NavMeshPlus.Components
{
[ExecuteInEditMode]
[DefaultExecutionOrder(-101)]
[AddComponentMenu("Navigation/Navigation Link", 33)]
[HelpURL("https://github.com/Unity-Technologies/NavMeshPlus#documentation-draft")]
public class NavMeshLink : MonoBehaviour
How does one make those arrow dropdowns on scripts like the advanced dropdown on the event system for example?
do you mean the foldouts? if so you can use a custom inspector, or you can grab something like naughty attributes which includes a Foldout attribute
most likely you would need to add a reference to your own assembly in its asmdef. but why you would edit a package's class instead of just making your own or even just inheriting from it in your own assembly is beyond me
ok right yea i just overrode the class thanks
i am looking for examples online of the code and its usually preety big
and some that i find calculate more things than what i need
if you have knowledge of programming you should be able to implement what i described pretty easily yourself. but if not, then maybe you should try to get more coding practice under your belt until youre more capable of making a system like this
how much knownledge would i need
is there a way to display a scriptable objects inspector inside of a custom editor window?
You should be able to create it as a Editor: https://docs.unity3d.com/ScriptReference/Editor.CreateEditor.html - you could then pass in your ScriptableObject and store the return as a variable, then call one of the Draw functions or OnInspectorGUI or similar
enough until you can make things yourself instead of copying it from tutorials
nothing wrong with using tutorials. but eventually you will want to create things that nobody has made a tutorial on (like right now). so thats why you gotta practice, research for yourself, participate in game jams, etc
What if I just want to draw the default inspector?
https://hastebin.skyra.pw/jihijerado.pgsql
When i move, the headbob only applies in one direction
what could be the issue?
i have a question regarding bullet spread
im using this tutorial : https://www.youtube.com/watch?v=eeZnVWPwY_w
Back from all the busy stuff! Here's a quick tutorial as a sacrifice.
We'll be going through some very basic bullet spread mechanics.
โบ Timestamps:
= Intro - 01:00
= Basic Variable Cleanup - 02:13
= Bullet Spread - 03:53
= Fin - 07:33
= Extras - 07:34-onwards
โโบF...
the spread works, but now the bullet prefab comes out of the centre of the scene, not the gunTip transform
here is my code:
//calculate spread
Vector3 shootDirection = GunTip.transform.localPosition;
shootDirection.x += Random.Range(-spreadFactor, spreadFactor);
shootDirection.y += Random.Range(-spreadFactor, spreadFactor);
//fire the bullet
GameObject bullet = Instantiate(bulletPrefab, shootDirection, GunTip.rotation);
bullet.GetComponent<Rigidbody>().AddForce(GunTip.forward * bulletSpeed);
Destroy(bullet, 5f);
You could pass a relevant Selection like activeObject to CreateEditor instead: https://docs.unity3d.com/ScriptReference/Selection.html
Looks like your instantiating your bullet prefab from thee shoot direction only, im guessing you wanted to instead add that shoot direction to your position as the 2nd param, or passed as a variable
yes
what could be the reason that when i am in air the force gets applied really fast pushing the character to the side immediately way to fast and characters stops again very fast but when doing jumping and using force on other objects it works perfectly normal
I made it work! i was doing Guntip.transform.localposition, where i should of done guntip.transform.forward
and i was supposed to make the bullet instantiate where the guntip is, and apply the force in the shootdirection.
beginner chat abandoned me so now imma ask here how to fix this wallcling thing that i never implemented
[ code for reference ]
https://hastebin.com/share/opalejeduv.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
[ outdated because i changed collision to other ]
Set your physics material to be frictionless
would that make the normal movement less snappy
It would make it so it is frictionless
ok but how tf do i make it frictionless
i said i normally ask for help in beginner chat so who are you to assume my knowledge
istg why tf do i always sound so rude
Just google it, idk what you're getting annoyed for
"Unity 2d how to make my object frictionless" will definitely find you some results
show code
also every GameObject has a layer
you also never really showed the inspector of the wall
you only showed with the wall selected + other objects at the same time
show full script !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.
I see it
OnTriggerXXX is a little fishy?
does that mean your colliders are triggers?
what other components are on the player?
if (view.IsMine)
{
RaycastHit info;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out info, 1000, LayerMask.GetMask("Default")))
{
//This can be used to access the 2d array for both chesspieces and chessboard tiles
Vector2Int hitPosition = LookupTileIndex(info.transform.gameObject);
//Is it our turn
if (chessPieces[hitPosition.x, hitPosition.y] != null)
{
//rest of code
}}}
man, im getting NRE on chessPieces[hitPosition.x, hitPosition.y] and i can't figure out? which knowledge am i lacking?
did you initialize chessPieces
it is declared, not initialized
you have to do = new ChessPiece[some int, some int]; at one point
private void SpawnPieces()
{
chessPieces = new ChessPiece[TILE_COUNT, TILE_COUNT];
//...
try running through the debugger then and seeing whats null. Im inclined to say that you are accessing chessPieces before SpawnPieces, but with just snippets of code i cant firmly say anything
i think problem lies in connecting random room
everytime i open 2 builds they join different rooms
send whole script maybe?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
anyone got any ideas?
this is the whole script.. i gonna work on the room thing tomorrow though
Aight, anyone have example code for a CallbackContext with input system to handle individuating "single press" from "hold"?
specifically: repeatedly triggering an effect while the button is held down?
Does anyone know why I cannot access my method?
ASP.NET application: https://www.nombin.dev/ekpogqx5ig
// Unity client
using (UnityWebRequest api = UnityWebRequest.Get(apiUrl))
{
yield return api.SendWebRequest();
if (api.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error sending request: " + api.error);
}
else
{
Debug.Log("Response: " + api.downloadHandler.text);
}
}
it throws me that api.error here
whats the error code?
HTTP/1.1 404 Not Found
also you should see a debug log on your asp.net project as well, it'll inform you if requests are being rejected
whats the value of apiUrl?
it's string
https://databasemanager.azurewebsites.net/PlayersDatabase/DoSomething
oh wait, surprised I didnt see that sooner
but you cannot open this site, just https://databasemanager.azurewebsites.net
all controllers in Asp.Net need to be <Something>Controller as their name
but also how come you arent just testing this locally?
don't know, I don't care actually
so what do I have to change?
Route?
the class name itself
for that endpoint you want it to be named PlayersDatabaseController
I don't get it
(Asp.Net does magic automatic fetching of Controllers by specifically looking for classes named <Something>Controller)
public class PlayersDatabase : ControllerBase
so .../PlayersDatabaseController/DoSomething ?
^^^ its missing Controller at the end, so it wont get picked up by the AddControllers in Startup.cs
no same endpoint
when you do
[Route("[controller]")]
It maps it to everything except the Controller in the class
so
[Route("[controller]")]
public class PlayersDatabaseController : ControllerBase
Will map to ~/PlayersDatabase/
yes? so that initial url should be correct ??
oh.
it's about the class name?
is there any way I can do it without changing the class name?
... technically yes but not in a sane way
just name your controllers correctly so they get registered properly
I see
Over in Startup.cs you'll see a call to .AddControllers or whatever, or .AddMVC or something like that.
It "automagically" scrolls through looking for classes you have named <Something>Controller and will register them, if you dont name em right, they get missed
anyway, it still throws me an error.
the same one
namespace DatabaseManager.Data
{
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class PlayersDatabaseController : ControllerBase
{
[HttpGet("DoSomething")]
public IActionResult DoSomething()
{
return Ok("DoSomething method worked");
}
}
}
That looks correct now
private const string apiUrl = "https://databasemanager.azurewebsites.net/PlayersDatabaseController/DoSomething";
bruh
URIs are not case sensitive
Also I will heavily recommend you just test locally to save a lot of future headache
still error code 404?
yes, HTTP/1.1 404 Not Found
Test locally to start
Adding all the wild stuff for routing and DNS and shit on top of this is a lot, testing locally removes all those variables at least
is it supposed to solve my issue?
it sure will remove a lot of potential problem causing variables from the equation
I see
just run the project and you should get a console window that shows you a localhost url its listening on
use that as your domain for now (same endpoint)
does my local site work even when my application isn't opened?
which application?
ASP.NET C# application
you have asked "is the server running when it isnt running" effectively :x
actually I haven't, I can access my site even if my visual studio is closed.
I mean you can run it manually but like... just debug it with visual studio, you can even add it to your unity solution so you can debug both at the same time nicely
I see, I will try to make if local first
I havent personally tried this yet but it should work as long as you dont regenerate the project (you'll have to just re-add the project again)
what does it do?
You'll then wanna hit this, and add your Asp.Net application as part of your startup projects
lets you have both your unity projects and your asp.net project in the same solution so you can debug em together at once
I have them in the same folder
Coolio
yeah you basically just hit "add existing project" and go click that .csproj file for your asp.net app
I see, done
then you will wanna right click on the project, and hit that button "Configure Startup Projects"
And swap to Multiple startup Projects,
You'll wanna have Assembly-CSharp and DatabaseManager both set to Start and thats it, should be good to go
Id strongly recommend it
I think it shouldn't be done
why?
unity is a client
Indeed
Yup
so C# application is just one
1 instance of it.
are you sure they should be in the same solution?
I think I just don't understand something
What issue are you forseeing them being in same solution
They are still in seperate projects, so they compile out to 2 seperate executables
I don't know actually, I will trust you, you sure know it better than I do ๐
I would have separate solution for server project
The other thing you very likely will want soon, is a .Common project that will hold your classes for your API endpoints
Unity sln is Unity generated in their flavor.
It looks like a normal solution file to me as far as I can tell
anyway, it doesn't make me able to access that method ? ๐ค
You don't want to put that in a git, you don't want to modify your sln every machine / every time Unity regenerate.
I mean in a professional enviro I would have:
- Git repo for the unity project
- Second repo for the API
- Third repo for the "common" layer, that is a Nuget pkg reffed by both above but has Debug/Release switch flip in their respective .csproj for if its direct ref vs nuget ref
- a Parent repo with a submodule reffing the three above and a .sln file that brings em all together, and it would have my stuff like docker configs and whatnot, build pipeline yamls, all that jazz
Thats how I do it at my job when Im having to synch up with teams and whatnot
thats how it be, it can get even zanier if your frontend isnt unity, but is a web app with NPM packages as well
I mean if you have locally maintained unity packages, you'd wanna keep those in their own repos as well and submodule em in
but yeah I dunno if unity is gonna fuck with that .sln file much
but I havent tried it myself, Id give it a shot, if it keeps over and over removing that project ref then forget about it
I presumed unity only messes with the .sln file if you click the regenerate button
but should this site be accessible in the internet?
https://databasemanager.azurewebsites.net/PlayersDatabase/DoSomething
or no?
I mean it doesnt work for me thats for sure
yes, it doesn't work for me too
if you run it locally it should just be running on https://localhost:SomePort
but you will still be able to access https://databasemanager.azurewebsites.net ?
I dunno, thats azure stuff on the cloud
when you run the server locally you are literally running it on your machine purely for testing and verification purposes
once you confirm that it works locally, then you can test it up on azure
yes, it works locally
testing on azure first is a good way to go insane because how would you know if the issue is with your code, or your azure configuration, or your DNS resolution, or something else?
aight, I dunno how you are pushing to azure but, if it works locally and the endpoint gets hit, then yeah next Id test if pushing to azure works
but it works very strange
it opens me a localhost site once I click on StartDebugging
but when I close the site that it has opened, I cannot access it anymore
I think I have to find nice documentation for it
thank you for your help! ๐
yeah, that runs it locally, and it automatically opens a browser instance for it, but it watches for if you close that browser itll also automatically stop running
if you wanna test your azure site, you gotta publish and push to azure
clicking that Start Debugging button is purely just for running and debugging locally
im making an fps game
and it works but the sensitivity is too low
how do i make sensitivity higher
i used this https://pastebin.com/RXZ1dXgw pastebin code
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yes i know im lazy
You read your code, see where the mouse logic is, then change the sensitivity
yes i know that is what to do but
i litterrally have no darn tootin idea how to use c script
this is my first time using unity
Hey so, how could I get all the vertices on the same plane of a mesh while assuming that both sides are symmetrical? For example, lets say we have a cube as seen on the picture. I would need to somehow get the top or bottom vertices and save them in a script as the red ones, but this should work on any object that has symmetrical top and bottom like a cylinder as well.
so i have no idea where is the mouse logic
Shouldn't be copying some random code then, learn and roll your own
!learn
: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/
the tutorials said to use pastebin if the tutorials work in blender they must work in unity
No point we give you instructions if you won't understand what we're saying
oh fair enough
Intersect with Y plane?
The object may be rotated
Like I would need the vertices of the object that you would see when you look at its front in a 2d view
So make a Plane and see if the edge intersects with it
Could it be possible to do it in a script without creating new gameobjects? I just need to store the data not make a gameobject with it
Plane is not game object
Oh you mean a plane like that
But my problem is how
Like I need to get the vertices that are on the same plane as the transform.forward facing face on the mesh
oh shit
I can use triangle.normal
alr i think i found the part of the code that changes the sensitivity
i think i need to change the red numbers
You don't think the variable named "lookSpeed" would be more likely?
OOOOOH thank you so much
I see, so I want to publish it in order my method to be accessible?
why when i put the same input it has an error? my "Get" didnt show up on the intellisence.
void OnMove(InputAction value) => moveInput = value.Get<Vector2>();```
the one on the attachment is ok. this is from a youtube tutorial
but the one i put on it has error on my "get"
why? ๐ฆ
ty for pointing out my stupidity ... man, when im panicking, im so blind.
hahaha . sorry for that. thank you so much btw
Hello, does anyone have any advice or can point me in the right direction on how to implement acceleration and deceleration in my character controller? I'm using the charactercontroller component.
Anyone setup the newtonsoft json package? The docs say that by simply installing it will (https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters#sample-with-this-package) but even though I have added this package to my project, when I try their example and simply serializing a Vector3 value, I get the problem they're mentioning should only happen without it ( I think I only installed the newtonsoft.json package, NOT the json-for-unity converters one...JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. )
I don't think you can serialize Vector3's, instead create a Vector3Data class that holds the relevant data, i.e. the X, Y, Z values and then construct a new Vec3 when you load the data.
Edit: ok nvm, just saw the example. I guess it can work with the UnityConverter package. If you use the normal JSON converter you have to do it like I wrote above
Or make a custom JsonConverter<Vector3>, but yeah that's exactly what the extension is doing herฤ
trying to find that in the registry I found that there's actually a builtin JsonUtility.ToJson / FromJson<T> that actually do what I need (it serializes Vector3 and List<string> which is all I need for my gamestate)
Is it bad practice to recreate a game's player movement without using its source code and using the math that they are using?
Since I took a waay different approach of doing it.
Ask yourself why you're recreating the game
Is it to achieve the same result your way, or to make an exact copy
If it's the latter, you might as well just copy paste the code since you have access to it
I'm not really recreating it, I'm recreating the base of it then building up with my own mechanics.
I just though if I were to recreate it on my own, adding my own mechanics would be much faster.
At that point I don't think you should focus on how similar it is to the source code
Ah.
So, about making a custom mesh at runtime, does the game object pivot point go to the center of the mesh (probably not)? If not, how could I move the vertices to have the pivot point be in the center of the mesh while keeping the same shape?
ive been meaning to ask
Is it possible to use both cinemachine and the normal unity camera system in a single scene? I only want cinemachine for cutscenes as im actually using a custom fps camera and controller and moving to cinemachine for fps camera is meh
Like if i disable the cinemachinebrain and all virtual cameras would a normal camera work fine? I think in my tests it did work fine but i wanna know if anyone found any problems down the line with this
Cinemachine is just another version of a camera as long as you disable them when not in use it wont bother the regular cameras. (I havent tried it personally but i dont see any way it could affect each other)
Splendid, ty
Ill implement it then
The mesh is in local space, so it depends how you set up the mesh.
If you start at 0,0,0 and go up for a cube the pivot is at the bottom. If you go from -1,-1,-1 to 1,1,1 it's at the center.
I know that it is in local space, but the problem is that my mesh's starts off at like 2,0,0 (this is the furthest it can be on the x axis*) from the pivot point and so the vertices are around position, but I want the pivot to be in that position too, so the best thing I can come up with right now is to move all the vertices by x,y,z towards the pivot and then move the whole gameobject by -x,-y,-z to give the effect of moving the pivot, but I just dont know how to do it while keeping the shape the vertices make the same
The only information I have to do this with is the pivot point and the vertices positions.
Maybe calculate the bounds and get the center from that and move the vertices to the middle or something like that?
If you change the vertex pos of all vertices the shape will stay the same
Well, I guess I could probably get the bounds position, move all the verts by the -amount of how far the bounds are from the pivot and save that, then move the pivot by the same amount back
Hey, so I made a script that brings the player to the next level if he touches the object this script is attached to. But for some reason it only works in Level 1 and in the next Levels it just doesn't work anymore, even though i copied the exact same object. Does anyone know a solution to this problem? here's the script:
You need to configure Visual Studio so it works with Unity
!vs
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)
See the guide above
Close VS, move the script from one folder to another and back in Unity, and open it again
This should trigger a compilation and solve it
okay thanks
Quick sanity check cuz I havent had my coffee yet:
This is the right way I go about "toggling" a flag for a flagged enum right?
public void OnMenu(InputAction.CallbackContext context)
{
GameState.SceneState ^= SceneState.Menu;
}
Yup looks good to me
how the hell do i rotate canvas with screen space overlay? I'm sorry but it's straight up dumb that screen space overlay canvas matches with game mode, but simulator mode just gives the canvas in the wrong direction
for some reason the simulator isnt rotating the screen itself, thats odd
you shouldnt need to rotate at all, your phone itself handles the rotation on its own
yeah, but It's really hard to redesign the whole UI for portait mode, when everything in scene will be flipped 90 degrees
after an hour of trying to fix it, i just pressed play and it automatically went into portrait mode
sometimes i seriously hate game dev
Hello, why am i getting this error message in my own voice chat system?
Length of recording must be less than one hour (was: 220500 seconds)
when I just pressed the PTT key for half a second?
Nobody sane enough will download an archive file from a complete stranger on the internet
Please post the !code as a code block or to a paste website
๐ 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.
also #archived-networking (NGO server in the pins)
Not everybody can see these embeds
VoiceChat.cs -> https://gdl.space/ufidohezux.cs
VoiceRecorder.cs -> https://gdl.space/yenovurohu.cs
WavUtility.cs -> https://gdl.space/acomivelow.cs
I wanna add my audio files in the clips section and I need to drag and drop them from the project window but when I select the files it changes the window in inspector to the audio file instead of the player. can someone please help?
Lock the Inspector on your object by clicking the "Inspector" tab at the top > Lock
It won't go away until you unlock it
ty my friend
another neat trick to keep in mind if you wanna do it on multiple script or just never bother locking the inspector you can pop out the script if you right click it and click Properties
oh thats interesting
ty for that too
also does anybody know why its not actually playing any sound when Im in the game
I will paste my entire code here
are you sure the window is not muted ?
๐ 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.
speaker symbol on game view
tryina find an image on google lol
๐ซก
I remember I turned it off because I was testing a unity asset and it was really loud
never turned it back on
Does anyone know why Mathf.PerlinNoise() is returning "NaN"?
Bit confused how that's even possible
yeah some assets do have earbleeding sounds
When it's suppose to be a float value
NaN is "Not a Number" thats all I know
Well yeah, but I'm confused how it's returning "Not a Number" when the function is suppose to return a number
Like how is that even possible and why is it happening
well its like "Math error"
for example 0/0 is math error
aka NaN
or for example
square root of negative numbers is a Math error
aka NaN
thats all I know
sorry for not really helping but I tried to at least explain what NaN is
So is the PerlinNoise function broken or something I'm confused why there'd be an invalid math operation being returned by a built-in function
instead of your not super useful log, print this instead: Debug.Log($"Noise Result {Mathf.PerlinNoise(nx, ny)} from coordinates ({nx},{ny})");
Okay
Oh I figured it out. I rotated the polygons to be along the x/z axis but forgot to modify some functions to account for that
Does anyone have an idea on how I would go about creating an upgrades/items system like Enter the Gungeon and Binding of Isaac have? I've been looking everywhere and can't find a useful answer
I've tried abstract classes but it isn't seemingly what I'm trying to go for
e.g one upgrade may increase your health by 2, whilst another could summon a fireball every 3rd shot etc.
I need to be able to have them in a list and call their functions, whilst having different code inside?
That'd deped entirely on how to choose to implement it. There isn't some sort of way to implement that system in a few lines of code
I'm aware, I'm just tring to find some sort of idea on how to make it, not code itself.
can anyone help me with adding walking animations to my character
I have it setup so that when the player levels up, an x amount of buttons show up on the UI, each corresponding with an upgrade, similar to 20 Minutes till Dawn.
Dossnt necessarily needs to be with abstraction u can create a central stats script with all the needed stats
Then create a manager which modifys that script and add listeners to your buttons to call the methods of the manager to modify your player stats
I somehow messed up can somebody tell me how do I get back to the main scene from the UI thing cuz I was making health UI and now Im stuck in it
If you want abilities just add bools to activate or deactivate them from
Ive never played the aforementioned games so sadlt idk how they work but if like with each lvl you want to gives options to increase health or add ability damage this works
i thought of that but it didn't seem like a very neat way to implement it.
Here's a quick diagram that might give you some ideas. It combines a bit of inheritance with some abstract methods to implement a system:
Its simple
You can expand and fix it later on
games like these have lots of items with lots of different abilities which means lots of bools and other such things
Create a prototype of your system and make it more clean as you progress
pretty smart tbh
Almost every project ive done had the ugliest things imaginable but i cleaned them up as i went along
the only issue i have with an approach like this is how would I give said upgrade a name/level/whatever without having to attach it to a gameobject
similar to a scriptable object but not exactly?
hm
ill try it
This is basic C# object oriented functionality - no need to inherit from monobehavior if you do not want to
In fact you'll notice monobehavior is not mentioned in the diagram
ah
IF you change your mind and decide you do want it to have Monobehavior in the mix then have the BaseUpgrade inherit from Monobehavior.
can someone please help me get back from this to my 3D game?
You cant attach non mono behvaior scripts to GameObjects afaik
It throws funky errors
looks like you have the scene/game view port maxed. doubleclick on the 'scene' tab might rever it
Out of curiosity, what did you use to make that diagram?
nope that just made it full screen
Are you talking about exiting the 2D "UI" mode from within the Scene view?
Correct - but he just said he didnt want it to be monobehavior.
You CAN however compose a monobehavior class with objects inside of it that are not derived from monobehavior such as:
`
public class MyGreatUpgrade: MonoBehavior
{
private NukeUpgrade nukeUpgrade;
private void Start()
{
nukeUpgarde = new Uprgrade();
}
}
`
nono I had a hole 3D world but then I created a UI health text and now I dont know how to get back to the 3D world
if you have in the upper right access to the "Layout" menu choose the drop down and then Default might work too.
I don't want to attach it to a gameobject. I just want the classes inheriting from the main upgrade class to be able to be generalised and stored in a list for access of their variables and functions
maybe ur in the wrong scene
Oh nice, I may check that one out, thanks
why dont scriptable objects work?
I should be in the same scene
ah click on 2D on the top right of ur game window
Also of note ... you are in "2D" mode which sort of restricts your ability to navigate the scene in 3D. Theres a tiny extra set of button on the "Scene" strip one of which is "2D" maybe thats confusing you?
this happens when I click 2D
You can also select any object from your hierarchy and hit "F" while your mouse is over tthe Scene view, and the camera should focus on that object
now find ur world by looking around
with this, could I have all the SpecificUpgrades all be in the same script, with multiple classes in it?
its a 2D world you cant move around
You could - I would not recommend it.
To define an extra public class inside of another class file makes it a bit hard to find in the future. The only good use case for that is if the class file itself is the only class that will likely ever make use of the other class thats located inside of it.
but I somehoe need to go back to the real 3D world
well click on a cube and press F and u should teleport to it
ah alright. I'll try it your way then.
The canvas is comparatively massive in that view (which is normal), and you are IN the same scene it looks like. You probably just need to zoom way in. Or select the cube and hit f like John said
that worked ty
yep ty everyone
Maybe this helps a little more:
In this example because DisplayUpgrades is meant to display them to the player, its likely that class extends Monobehavior
Hey all, I'm running into an interaction I'm unfamiliar with.
I have two classes: Unit and SubmittedCommand. The Unit class has an array SubmittedCommand[] submittedCommands, which I instantiate as submittedCommands = new SubmittedCommand[5] inside of Unit.Awake(). I ran a Debug.Log right after the instantiation, and submittedCommands is now a list of 5 null entries. This is good, and what I want/expect.
Now heres whats confusing me; if I mark the SubmittedCommand class as [System.Serializable], after the Unit.Awake() call, the submittedCommands array now contains 5 created SubmittedCommand instances (all with null fields).
How come [System.Serializable] is populating this list?
I can provide code/screenshots/etc if needed
alright. One last question; I can set the upgrade name inside of script using " ", but how would I set the upgrade icon?
Even though BaseUpgrade does NOT need to inherit from Monobehavior if you import the proper unity imports it CAN still have things like Image , Sprite, GameObject as class member variables so your BaseUpgrade should have a property for an Image or Sprite -- whichever one you want to use for your icon.
if you look at the diagram, you'll see I included that as an Image already
Does anyone know how to detect if a touch is over the UI?
Can someone help me, If I click middle mouse or right click it comes off of focus but if I click left click or escape it stays. Could it be something with a right click menu or something? nameMonsterUI.monsterNickname.onEndEdit.AddListener(val => { if(Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { Submit(); } else if (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2) || Input.GetKeyDown(KeyCode.Escape)) { nameMonsterUI.monsterNickname.Select(); nameMonsterUI.monsterNickname.ActivateInputField(); } });
I am using tmp_inputfield
I don't know what you're trying to do here but using the new input system would make your life a lot easier
ah okay, should I just change the keybinds in there then?
I don't need mouse input for anything else
I am just trying to make it so the user never can click out of an input field
Oh, I've never used a tmp input field so idk about that part. I just saw that you are using Input.GetKeyDown
Not sure you can with that onEndEdit event, it's probably getting called after focus is lost. See if you can inherit from TMP_InputField and provide your own focus logic by oveeriding some methods (if you even can)
It's easier to use the new system, so switching will make your code simpler and then maybe you'll see why it isn't working
I will have to research how to use that with what I am trying to do
Is there a wayto not use system.reflections if I dont know which script I am gonna run method from? Like I have variable var component and want to run ethod from it?
Sure thing, you can use a base class or interface with that method declared in it
The sub-class will provide its custom implementation
May you give me example? I dont quiet understand. I was using this for now:
MethodInfo method = script.GetMethod("use");
object[] parameters = new object[] {//parameters};
method.Invoke(component, parameters);
You just make a InputAction field for your script, and serialize it so you can set it in the editor. Then go in the editor and set the key you want to trigger this input action. Unity makes this part very easy. Then go in your script and add a method you want to be called when the key is pressed. Add the OnEnable and OnDisable methods to your script. Add: inputActionName.performed += methodName(); and inputActionName.Enable(); to the on enable method, and vice versa for on disable. Now whenever the key is pressed, the method you made will be called
Alright I will try it out thank you
Let's say you're making a damage system. But you also want to use that system to activate stuff (shoot buttons to activate them).
You can make an interface IDamageReceiver that has a Damage() method, like this
interface IDamageReceiver {
void Damage();
}
And then have an enemy implement that
public class Enemy : MonoBehaviour, IDamageReceiver {
public void Damage() { // you are forced by the compiler to implement this
Die();
}
}
And the button
public class Button : MonoBehaviour, IDamageReceiver {
public void Damage() {
Activate();
}
}
Then on the gun, no matter what you hit, you try to get the interface instead of a concrete class, and use the method on it
ray.gameObject.GetComponent<IDamageReceiver>().Damage();
Then whatever you hit, be it an enemy or button, C# will take care of running the correct method.
And of course interface methods are like other methods, so they can accept arguments and return a value
They don't have to be void ...()
Sorry new to this, how do I add the onEnable and onDisable
void OnEnable()
{
}
void OnDisable()
{
}
Ohโฆ
lol
!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.
They activate when the script is enabled and disabled, you want to use them when using the new input system as I showed you before to ensure a method is not called when the object it is on is disabled, which would case an error
{
inputAction.performed += Submit();
inputAction.performed.Enable();
}
void OnDisable()
{
inputAction.performed -= Submit();
inputAction.performed.Disable();
}
public void Submit()
{
if(!inEvent)
{
StartCoroutine(nameMonsterUI.DeselectInput());
StartCoroutine(ShowChoice());
inEvent = true;
}
}```
I am getting errors for the inputAction.perform
There are errors for this
What error are you getting?
I don't see any problem with that code so idk
oh you realize input action is just the name of an InputAction field right?
do you have an InputAction field named inputAction somewhere
What is the error you get?
Cannot implicitly convert type 'void' to 'System.Action<UnityEngine.InputSystem.InputAction.CallbackContext>'
oh my bad I forgot about part of this
You have to put InputAction.CallbackContext context as a parameter
in the method
when subscribing to an event you subscribe the method group which means you don't include the ()
that too
where does the paramater get used in the function?
{
inputAction.performed += Submit;
inputAction.performed.Enable();
}
void OnDisable(InputAction.CallbackContext context)
{
inputAction.performed -= Submit;
inputAction.performed.Disable();
}
public void Submit()
{
if(!inEvent)
{
StartCoroutine(nameMonsterUI.DeselectInput());
StartCoroutine(ShowChoice());
inEvent = true;
}
}```
you put the parameter on submit
nice
do I have to += enable and disable too
its saying it can only go on the += or -=
?
inputAction.perform.Enable() is throwing an error
Oh your not supposed to put any parameters on enable and disable btw
yeah I got rid of those
The event 'InputAction.performed' can only appear on the left hand side of += or -=
thats the error
idk
I'm dumb
looks like its on the left to me
Yup outside the class that declares the event, you can only use += or -=
its just inputAction.enable and disable not performed
oh, I didn't notice you doing that lmao
so this should work ``` void OnEnable()
{
inputAction.performed += Submit;
inputAction.Enable();
}
void OnDisable()
{
inputAction.performed -= Submit;
inputAction.Disable();
}
public void Submit(InputAction.CallbackContext context)
{
if(!inEvent)
{
StartCoroutine(nameMonsterUI.DeselectInput());
StartCoroutine(ShowChoice());
inEvent = true;
}
}```
yes
without calling the OnEnable or OnDisable anywhere
Yeah, they get called automatically when the object is enabled and disabled
