#💻┃code-beginner
1 messages · Page 534 of 1
the coroutine is not active when the object is destroyed
thats fine, but something is trying to reference Gun
when it no longer exists..
just gotta walk thru the code and figure out what
Okay. Thanks for your help!
whats the best way to make destructable/physics affected tiles
afaik regular TileMap wont help, since tiles are just purely for rendering purposes
unless im wrong
destructable/physics affected tiles
This is pretty vague
You'd have to get into details about what kind of interactions you want.
oh
my bad
let me elaborate
@wintry quarry have you played Space Station 13 by any chance?
no
oh, its ok, they just have the mechanic im looking to replicate
Basically a 2D game, Players can interact with tiles and objects on them
Construct/Deconstruct (Changes tile/object texture)
UnWeld - Make tile draggable around the map
Weld - Set tile to the desired grid position
Other mechanics work around it, like explosions making tiles unweld and apply force and stuff
This would definitely be done with a tilemap
Oh, then i dont know that much about tilemaps then
like explosions making tiles unweld and apply force and stuff
As for localized individually moving tiles, those you would replace with GameObjects at least temporarily.
sooo, remove the tile from grid and spawn the GameObject on that spot?
Can be done several different ways:
- Have a separate tilemap for that layer with a trigger collider
- Just check which tile is at a particular place and if it's the damaging one you do damage
- Use GameObjects for that particular interaction
well, first one isnt gonna work for me, since there is will be different tiles, with different interactions. (could probably make it more abstract)
Second one works, but idk how flexible is that, having to add different functionality for each tile with if/else chaind doesnt sound good to me.
No idea how third one works, I assume you mean just the same case with my original problem
you don't need if/else chains.
yeah, my bad
I can just store functions
alr, thanks!
can someone help get out off this and back to the original set up
top right of the screen
press Layout > Reset
it could be that Scene view is just maximized.. Double Click the tab where it says "Scene"
Shift + Space (while hovering a window toggles it from minimized to maximized btw)
@rocky canyon thanks
ur also i ISO metric view..
click the little square (in the middle of the directional gizmo in the top right corner)
to toggle from Perspective to Isometric
It keeps saying that the template checker is having an error and it doesn’t let me add items
can you show a screenshot of this error?
heyo so ive been messing with the particle system for a bit, and it seems everything other than the actual color & shape of my particles seem to work just fine
it seems to just be stuck on this purple square texture
have to pick a material that works w/ the particle system
scroll down and open Renderer you'll find the material there
oh thank u!!
if (!playFabSettingsValid)
{
if (EditorUtility.DisplayDialog(
"PlayFab Settings Warning",
"You are currently not logged into PlayFab.\n\n" +
"Please open the PlayFab EdEx window and log in to update your settings.",
"Open PlayFab EdEx",
"Cancel"))
{
OpenPlayFabEdExWindow();
}
}
}
private static void OpenPlayFabEdExWindow()
{
EditorApplication.ExecuteMenuItem("Window/PlayFab/Editor Extensions");
}
private static void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
{
CheckSettings();
}
}
private static void OnBuildPlayer(BuildPlayerOptions options)
{
if (PlayerSettings.companyName == "Company Name" || PlayerSettings.productName == "Game Name")
{
EditorUtility.DisplayDialog(
"Build Error",
"Cannot build the project. Your player settings are still set to the default values.\n\n" +
"Company Name: \"Company Name\"\n" +
"Product Name: \"Game Name\"\n\n" +
"Please update these values in the Player Settings.",
"OK");
throw new BuildPlayerWindow.BuildMethodException();
}
if (string.IsNullOrEmpty(PlayFabSettings.staticSettings.TitleId))
{
EditorUtility.DisplayDialog(
"Build Error",
"Cannot build the project. You are currently not logged into PlayFab.\n\n" +
"Please open the PlayFab EdEx window and log in to update your settings.",
"OK");
throw new BuildPlayerWindow.BuildMethodException();
}
BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
}
}
#endif
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
use an appropriate method to share code ☝️
also, i was just referring to a screenshot of the actual error..
(like is it in the console?)
(was it a pop-up?)
etc
i've never heard of the error, is why i ask
use Window key + Shift + S
it a vr
can take a smaller, little pic of it instead of a big screenshot
ya, but it still should appear in the console in the editor (in the pc)
or is the error happening only on the VR headset?
Build completed with a result of 'Failed' in 97 seconds (96610 ms)
TaskCanceledException: A task was canceled.
UnityEditor.BuildPlayerWindow/DefaultBuildMethods:BuildPlayer (UnityEditor.BuildPlayerOptions)
TemplateDefaultChecker:OnBuildPlayer (UnityEditor.BuildPlayerOptions) (at Assets/Editor/TemplateDefaultChecker.cs:89)
no in utiyt
oh okay.. so its a Build Error
yes
🫡 gotcha.. thats what i was confused about.. and the direct wording of it
do you see it
ya.. im just lookin into something.. (i thought files in /Editor/ didn't matter as they dont get built into the final build) but it appears that they can matter..
and secondly.. thats not a script You made im guessing...
looks like something Unity would include itself.. soo it makes me question why it isnt working..
im thinking something along the lines of corruption
are you signed into Unity Hub?
@rocky canyon dms so i can give you tae link i use forme github
also looks like something that could happen due to a network timeout..
one sce it wrek
A Gorilla Tag Fan Game Template by Glitched Cat Studios! - Glitched-Cat-Studios/GTag-Fan-Game-Template
@rocky canyon
ahh, ya, third party asset then
waht how do i fix
did you ever change ur Company and Product name?
- "You are currently not logged into PlayFab.\n\n" +
- if (PlayerSettings.companyName == "Company Name" || PlayerSettings.productName == "Game Name")
these are the only two things i see in that code that would cause an error
the line number is this
so maybe check that function as well
all the code seems to imply that it would log errors if any of that fails but idk.. im not the asset's creator
Ye I did
Can you fix it pls
does oncollisionenter and ontriggerenter get called from children and parent object or just the parent
but how much does it actually matter ?\
they get called on the object which has the Rigidbody
well there are situations where it matters a lot, but for the most part if you just use == you can probably not worry about it
cuz like != looks cleaner to me and the first option you see nothing
okay thats my problem then ,,, thank ya
what about in my case cuz it makes the code look worse imo
just do what makes sense to you
did you bother reading the page? because using the == operator (or implicit cast to bool) is very important with objects deriving from UnityEngine.Object
my comparison is different?
huh?
is not null is very different to != null, yes
but less readable
you shouldn't be using is not null with unityengine.objects
like I give a shit, do what works not what looks nice
it works
also what looks nice also does matter for readability and code structure
rubbish
"it works"
yet comparing with the is operator is bound to lead to exceptions being thrown
and, no, it does not work with Unity objects
my game works fine 🤷♂️
until it doesn't 😉
you do you, just dont come back when it does not work
but do i really have to use is not null cuz loks ugly compared to != and what is the advantage
holy shit, have you not bothered reading any of what was said?
im not a native englisch speaker 🤷♂️
go read the information that was presented to you again.
alr guess i will keep it like != for now then 🙂
again, that is what you have to use with unityengine objects
why am i getting this error
i don t understand the difference used to using != in ue5
doesn t get me much further 🤷♂️
myinput is null or the Find("up") returns null
it would if you would fucking read it
that page explains exactly why you need to use the == operator over the is operator and other null operators
but what has that to do with =! never use is if not needed
why would you expect C++ in Unreal to be the same as C# in Unity?
not saying that just saying what i know
read what is being said to you
yeah I know but they both look like they would make sense
-
Player is the name of the input actions map
-
Up is exactly what the action is called
whatever arguing about pointless things isn t worth it
null ref is a run time error. the DATA is not what you expect it to be, nothing wrong with the code
so what do I do to fix it?
check what is null and why
my guy, you are the one arguing pointlessly. this whole time you've apparently been on the side of using != when that is what everyone and everything is telling you to use
read the information on that page that was linked to understand why
For reference, is null/is not null/?./?? do raw null checks, which bypass overrides that are available for equality. Unity has an overload for equality of UnityEngine.Objects since they live in C++ land, but are exposed to C#. So the C# object can be perfectly fine and not null, while the internal one is invalid (hence the custom equality that checks lifetime), so using it in the api will throw exceptions.
You can easily see this in action with this example:
// assign in inspector
[SerializeField] private GameObject _obj;
private void Start() {
Debug.Log(_obj); // _obj/true, C# not null
Debug.Log(_obj != null); // true, C# not null
Debug.Log(_obj is not null); // true, C# not null
DestroyImmediate(_obj);
Debug.Log(_obj); // internal null/false, C# not null
Debug.Log(_obj != null); // false, C# not null
Debug.Log(_obj is not null); // true, C# not null
}
if you let air out of a baloon does it only go from one side?
when I do Debug.Log(my_input);
or if (my_input is null)
still nothing debugs in the log
Im trying to make it so that if this object is over 5 away from target it walks towards it, any ideas on why it doesnt stop?
where are you logging that?
- !code 👇
- where do you tell it to stop?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i dont really know can u help?
have you looked at the documentation for the navmeshagent?
tell it to stop if it is closer https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-isStopped.html
ty
after i move away it is standing still how do i make it move again?
read the documentation
if(Targetfurtherawayfromplayer){
//set destination and allow movement
}
else{
//do not allow movement
}
Doesn't it just log to the console
i meant where in the code
if it is after the line that is throwing the exception, then it is no wonder it isn't logging since that line would not run
yes, i already pointed that out. what is InputSystem.actions and are you sure it has an action map called Player
they are both under the name Player, the one in the code and the actionmap itself is named Player
show it.
okay and is this the input action asset you've actually assigned in the input system settings?
Yes
that is not the input system settings, that is the Player Input component
you should make sure you actually read the documentation for the properties you use https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/api/UnityEngine.InputSystem.InputSystem.html#UnityEngine_InputSystem_InputSystem_actions
My player’s IsGrounded boxcast is ticking true at the apex of his mini jump which seems to be causing the state machine to switch from the jump state to the running state momentarily. I checked the boxcast size and location and distance and it all seems correct, is there anything else it might be that I’m not considering?
You shouldn't be using PlayerInput at all if you're using InputSystem.actions
Very simple to figure out why with a couple Debug.Log statements.
Just log the object it's hitting
or otherwise log why the bool is becoming true.
Should I just remove it or replace it with something else
Pick one or the other
ok
ok the error is gone
(PraetorBlue was right - it was linking only the main action maps and not the new one)
and ty BoxFriend for checking everything else
Sorry, I didn’t explain it well, it’s colliding with the ground underneath the player. I just can’t figure out why, because it shouldn’t be.
A bug in your code
I’m definitely missing something obvious but I can’t tell what
Share your code !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
How did you verify the ground is what the boxcast was hitting?
@wintry quarry I have a few debug.logs that print whether the player is grounded and what the collision is and what state they are leaving and entering
The log says they are grounded, then running, then jump state, then colliding with the ground, then running again (in mid air), then not grounded, null collision, falling state (finally)
This doesn’t happen with stationary jumps it only happens when the jump has a running start.
@wintry quarry Holy crumbs, I googled my problem and clicked a link that looked related from a couple years ago and YOU were the person that replied to help them, what a coincidence! Are you a Unity employee or just a really helpful person?
I'm noticing that I can get a direction vector3 by subtracting the origin from the destination, but I have to multiple it by -1 in order for it to point in the right direction. Am I doing this right?
if you have to multiply it by -1 that means your direction is backwards. remember, direction is (endPosition - startPosition) in that order
ooh that makes sense
How do I procedurally generate terrain? I have tried looking it up but all I got was links to github repos that I can't figure out how to use.
Then maybe it's too early for you. Start with something simpler.
I figured that would be the case but I have no idea how to do anything in my project without terrain to do it on
many youtube videos out there you can follow
You could make a non procedural terrain. Or start with a simpler project.
Hey guys, what's up...? Just a quick question, for the "new" Unity Input System how can I use the equivalent of GetKeyDown if I use the Invoke Unity Events method...?
I have to jump but when I press and hold space my character jumps on the ground as long as I hold the jump button
Same thing with wall-jump, I just want it so that the player jumps only when you press the button and not hold it
Ok then can you explain how meshes work and how I can manipulate them so I can create terrain or is there something important that im missing
There must be a callback that corresponds to a key press or release. Check the documentation or ask in #🖱️┃input-system
use the terrain system built into unity or use polybrush to create terrain
where do I find the terrain system? should I just look it up
Generate a landscape through code!
Check out Skillshare! http://skl.sh/brackeys11
This video is based on this greatwritten tutorial by Catlike Coding:
https://bit.ly/2Qd1o1d
● Perlin Noise: https://youtu.be/bG0uEXV6aHQ
● More on generating terrain: https://youtu.be/wbpMiKiSKm8
● Singleton: http://wiki.unity3d.com/index.php/Singleton
❤️...
its math and code
tutorials would also help to learn the terrain system
the video isnt available
it says
This is a huge topic that is difficult to explain properly in discord.
A simple and insufficient explanation is:
Meshes are made of vertices that compose triangles or faces. To modify a mesh, you need to modify or add vertices.
on youtube?
yes
prob geo locked for u or something me no know
Why is the terrain object immune to scaling
You can find more on our docs as well: https://docs.unity3d.com/ScriptReference/Mesh.html (For meshes). A terrain is nothing more than a bigger mesh, however, it's easier to modify this "mesh" using Unity.
b/c all its scaling and stuff is done thru the Terrain component and its settings..
similar to how u can't change the Field of View on a Camera when its being controlled w/ a Cinemachine brain. (it needs to be done thru the Cinemachine Camera's instead)
what is cinemachine
its just a Camera supplement plug-in for unity..
was just an example.. not important to know really
https://pastebin.com/1dAqwAwJ
I have this code but i cant assingn from the hereachy the text nor the name to the manager.
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.
but the Terrains scaling, and positioning, and all that stuff is done thru its component
I have a bit of a janky way I made a terrain have hills using perlin noise. You want to get the terrain in a Monobehavior class like this: Terrain terrain = GetComponent<Terrain>();
^ yup, that proves my point.. ur actually modifying the Terrain Component
not the transform component
there is no scaling option here
its not really a scale.. its *terrain size, terrain height etc
you don't assign things via hierarchy, you assign via inspector. Did you Drag and Drop a text component into the field?
Yes.
then I fed it a function like this: terrain.terrainData = MakeTerrain(terrain.terrainData); which looked like ```TerrainData MakeTerrain(TerrainData terrainData)
{
terrainData.heightmapResolution = width + 1;
terrainData.size = new Vector3 (width, depth, height); // set terrain size
terrainData.SetHeights(0, 0, GenerateMesh()); //starting x and y, and a grid of floats
return terrainData;
}```
I tried dragging and dropping
The generate mesh function adds noise: ```private float[,] GenerateMesh() // generates height based on
{
float[,] mesh = new float[width, height]; // create grid based on wanted size.
for(int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//create perlin noise based on the coordinates, offset randomly.
mesh[x, y] = Mathf.PerlinNoise( (float)x / width * scale + PerlinOffsetX, (float)y / height * scale + +PerlinOffsetY);
}
}
return mesh;
}```
youll have to play with it a lot to make it work in your usecase
show me the inspector for the script
are you dragging a TMP text into it or just the default
Yea.
oooohhh
you would use TMPtext(I think it was) for your type
i thought they would be the same
TMP_Text and you'll need the using TMPro; using statement
that does not mean they are the same, its like saying an apple and orange are the same because they are fruits
they both have a .text parameter.. soo yea at the end of hte day.. they can function the same..
but u must have the correct type to reference it
Fair enough.
I have a network transform with a network rigidbody for Mirror networking, but it doesn't appear to be affected by gravity. Am I missing something obvious? Gravity is checked in the rigidbody component.
all 'child' rigidbodies in the network I believe are made kinematic
and just move with the authorative rb
is there a way to make the authoritative RB have gravity?
I am using the authoritative RB from Mirror
#archived-networking or ask in the Mirror discord
ok, ty!
https://i.gyazo.com/3568aa2ec5bec875b04ca413a66e0722.png
Is there a way to force layout element to work with Grid layout?
It works fine for Vertical Layout group, but when I swapped it to Grid Layout it no longer accepts min height.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Eh, Gridlayout is just junk tbh. Use a combination of both horizontal and vertical to make a pseudo GridLayout
or grab a better GridLayout off the asset store ;p
Tbh I need a vertical layout, the reason I picked grid layout was for an easy way to resize all objects
Except the one I want to override
I might do just that.
I had to redo it a bit to make it work with scrollview, which now forces me to do the above
Because I want a vertical list with header which is larger.
Not a Unity employee
https://paste.ofcode.org/D352jpHmBPM6PXH4MFcRVA does anybody know why the playerscore doesnt update properly when the bullet collides with the player ive tried fixing it so much but nothing comes to mind
// playerScoreTextUpdater.text = $"your score is {playerScore}";
This part is commented out
so it won't update UI
even the debug.log is not updating gets stuck at 1
that means you are not colliding
it does debug when it hits the player but the actual variable doesnt go up in value
you can manually place a bullet and drag it around in play mode to see if it works
oh
thats probably because you store a variable on a bullet script
but you destroy the bullet
so each bullet holds "playerScore"
you'd need to update your player object score or something, depends on how u want to handle that
ohhh ok thank you
You can look into Singleton pattern, its very simple and could work here(you'd create Score script and make it static so you can do Score.Add(1); etc)
i have a question how does destroying a gameobject affect variables updating that makes no sense to me
you increment the variable on the object being destroyed. that variable is an instance variable so each Bulletscript object has its own playerScore with the values being entirely separate from each other. it's typical to store the score on a separate object that isn't being destroyed and just update that when necessary. you could even make it a public property that updates the displayed text when the score is assigned to as well
Maybe I missed some context from earlier, but there's not enough info to answer your question. Normally, destroying an object is not related to updating variables in any way. If there is a correlation in your project, that must be due to your code or setup.
i think their confusion stems from their misunderstanding of how instance variables work, as their previous issue was the common "update instance variable's value and immediately destroy object" issue where they expect them to act more like a static variable
Ah, I see.
oh ok thank you i see
25
https://paste.ofcode.org/34vkXuGXPT2GHWLFHUSPYvy for this code does anybody know why the debug.log isnt triggering when i collide with an enemy parent
don't use string equality to check a tag, make sure to use the CompareTag method instead. it will actually throw relevant errors when a tag doesn't exist instead of failing silently
also give this a read: https://unity.huh.how/physics-messages
thank you
Where can I ask for help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
oh that's just there now isn't it
we can't help when you don't tell us what you need help with...
hint: read the bot message
#💻┃code-beginner message
I am atempting to make a flappy bird to to learn about unity. I created a pipe object with two child object Pipe Bottom and pipe top. Both of them have psrite renderers with the Jpeg that they need put inside. Neither will render into the game scene.
not a code question. your camera is likely too close to the object to see it. make sure your camera is at or behind -10 on the Z axis, that is the convention for orthographic camera placement
It is at -10 and I can move the pipes onto the bird and they will still not render
check the Pipe object and make sure it isn't behind the camera
How to I do that
click it and look at its position
i used the other keyword but it still doesnt track if i hit the enemy properly could someone check if i messed up something with the tag please
what do you mean by "the other keyword"?
what component is this code on?
has VSC been buggy for anyone? I can't even declare a string 🤔
also just fyi, other is not a keyword, you've just changed the name of the parameter to other but it was perfectly fine as collision
you're using OnTriggerEnter2D but enemy isn't a trigger
!configure
what was it
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
oh i thought that was for a different snippet
oh i should change it back one sec
clearly not, it's autocompleting words instead of... anything else
have you at least restarted the language server?
sorry for the late response but it was on an empty object in the hierachy i attached this script on
so it was not attached to any collider or rigidbody involved in the trigger overlap/collision?
why would it collide with anything then
yup that worked 😅
sorry for the inconvenience
i guess not i will try to fix that
OnTriggerEnter2D and OnCollisionEnter2D (and the other variants) are called on objects involved in the collision. unrelated objects will not receive those messages
Anyone know why this code correctly returns false for isGrounded during freefall but true for GroundCheck()? Debug.Log says GroundCheck returns true every frame no matter what, yet isGrounded returns correctly every frame. If I use "if(!GroundCheck())" elsewhere, nothing happens but "if(!isGrounded)" works fine. The boxcast and collisions are correct and nothing overwrites the values elsewhere. It's probably something obvious and fundamental -_-
cs
public bool GroundCheck()
{
RaycastHit2D hit = Physics2D.BoxCast(capsuleCollider2d.bounds.center, capsuleCollider2d.bounds.size, 0f, Vector2.down, 0.02f, groundLayer);
if(hit.collider !=null)
{isGrounded = true;}
else
{isGrounded = false;}
return hit != null;
hit cannot be null because it is a struct. but hit.collider can be, which is what you are checking in that if statement
also you can just return hit, it's got an implicit cast to bool that just checks if its collider property is null (which is also what you are doing in the if statement)
So if(!GroundCheck) { insert FallingState transition here} can’t ever work? Or it could work if I return hit instead?
huh? i was referring to the last line of that method where you attempt to compare something that can never be null to null and how you are doing something entirely different in the if statement that is inside the method
Sorry for being confusing, I meant if I return hit in the last line instead of hit != null, can I use !GroundCheck() elsewhere in the code (my FallingState example was just an example)
Hi. I have this question: I have 10 objects, and half of them are turned off. I want to turn off the disabled objects through the script, but I do not know which ones are on and off. Would it be better to check whether the object is turned off through the for loop and through if, or turn on all objects immediately through the for loop? For example:
what do you mean by "turned off"? because if you mean that they are disabled then that if statement will never be true because that is how you check if an object is destroyed or null, not if it is inactive.
but the second option would be just fine if you wanted to just make sure all of the objects in the list are enabled
Well, it's just that he was noticed, that is, he found out if he was noticed, and he was noticed, that is, he noticed (I put if"!")
Sorry, to be clear I’m asking this stuff because it still doesn’t work, not because I am not trying. IsGrounded() just returns true always. I tried returning hit instead but I must be doing it wrong.
i have no idea wtf you are trying to say
show the full !code. use a bin site that the bot links to do so 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I don't care. Option 2 is better, as you said. Thanks)
okay?
Can I just clarify what you meant by return hit? Do you literally mean replace “return hit != null” with “return hit” in the above code?
yes
Well then the new code is exactly what is above except with that one change lol
great! now show the full code
can u visualize enum property on UI button OnclickEvent?
then i guess i gonna do this instead
public directionOffset direction;
public void DirectionUp() => direction = directionOffset.Up;
public void DirectionDown() => direction = directionOffset.Down;```
Vsc, specifically, needs to be reconfigured periodically in my experience.
Hi, I'm a C++ dev and new to Unity and C# for the most part. I am trying to find a GameObject in a list that is directly in front of my Player GameObject.
What I can't figure out is how to clone the Player's transform. What I'm doing is something like
var targetTile = player.transform;
targetTile.Translate(new Vector3(1.0F, 0.0F, 0.0F));
I know that C# uses reference based semantics so it makes sense that this mucks with my Player object, but I don't know how to make a copy of the transform. From some googling it looks like I should Instantiate another GameObject from it?
You want to query a space. This is often accomplished with things like Raycasting (or sphere/capsule/box casting), or CheckBox (and other shapes) or other spatial queries like that
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.CheckBox.html
Ah, the edit changes the question a bit
Yeah sorry, I hit enter too quickly
Why are you needing to clone the transform?
I don't necessarily want to, I just want to use a transform that is 1.0 units in front of the player to lookup the tile in my list that is closest to that point
So, a transform is a component, not a position in Unity
So targetTile IS player.transform (meaning the component attached to the player)
If you want a POSITION that is 1 unit in front, use a Vector3
player.transform.forward happens to be shorthand for 1 unit forward (on the Z axis)
Yep. And I found out when I tried using Instantiate that it clones the whole game object, e.g. the Player haha
Oooo ok, that makes sense. As someone who works in the robotics space it seems weird that the transform itself isn't a plain-old-data structure like Vector3, but yeah, this makes sense
Yeah, I can totally understand that confusion.
Cool, thanks for the quick help!
You're thinking of a Transform as just a bit of data but it's a full fledged Component on the GameObject
(I see you figured that out now)
anyone available to help me with using LeanTween with Unity 2022.3.47? I can't get it to compile to save my life
it's cursed or something
nobody can help you if the only information you provide is 'it's cursed or something'
I can jump into a call and stream my setup. I'm just not sure what information is needed to help me
Anytime I've attempted to use 'LeanTween', i get the 'type/namespace could not be found' error
so far, i've tried:
- re-importing LeanTween
- re-downloading LeanTween
- adding any files related to 'DentedPixel' and 'LeanTween' to the Script Execution Order
- added/removed 'using DentedPixel;'
Does it use assembly definitions? If so, you'll probably need to use them as well and reference the assembly properly.
not sure. I haven't ever messed with assembly definitions so I don't know
The other way around might also be an issue. If you use assembly definitions and the asset doesn't, and it's code happens to be outside your assembly, that would make issues like you have now.
Before we get into more complex stuff, are there any compile errors aside from the namespace not being found?
if I don't use the namespace 'DentedPixel' i get the compilation error I had earlier. If I do use the namespace 'DentedPixel', then I get the same but for 'DentedPixel'
those are the only errors
Also, did you do this?
To use LeanTween move the included Plugins folder into the root of your project (or move LeanTween.cs directly into any pre-existing Assets/Plugins folder).
First, fix all the errors in your code, let unity recompile with the plugin and try again.
I couldn't find any 'Plugins' folder (i could just be blind):
You're supposed to create one.
🤦♂️
thank you dlich
let me try that and see if it fixes it
Did that work? It might just be confusing wording tbh
I'll try creating a 'Plugins' folder and moving the 'LeanTween.cs' file there
doesn't look like it did:
First of all, it's not just lean tween. All of these files are related to the plugin. Taking the script out of the files and moving around is not gonna help.
And 2: comment out the erroring code and let it compile once. Then try again.
so I need to stuff the whole 'LeanTween' folder into the folder?
I will try commenting out the code first
Yes. And the script needs to go back where you moved it out from.
I'll move it back then put the 'LeanTween' package into 'Plugins'
this is what I interpreted it as
it's still not quite working
What is dented pixel?
A namespace? It doesn't seem like you need to use it. Looking at the code from GitHub, it's commented out.
this is at the bottom of 'LeanTween.cs' (and the reason I added 'DentedPixel' as a using directive)
I removed said using directive and still this:
i'm going to bed. I'll figure this out later
Feel free to keep suggesting stuff and I might pop back in if I think of an idea
This seems to be purely for unit tests if I'm not mistaken.
You'll need to provide all the errors in your console as well as the code that throws them when you come back.
I can do that rq
ill link my github rq
It looks like you're using assembly definition in your project, so you'll need to do some setup changes as I mentioned earlier
I've never messed with assembly definitions so I'm gonna need to learn how. I'm assuming Unity has manuals for it
It does, yes.
Or you could just remove it if you don't specifically need it
Hello, I get a bunch of warnings and even errors cause I have cyclical serialization. However in my case I pretty much need it. Is there a way to set a limit on how many times it can serialize itself within itself? Cause I doubt I'd ever need more than 3 self containments ever.
any tips are appreciated.
Depends on your serializer. I doubt JSONUtility has a solution because it sucks. Newtonsoft has it configurable and STJ probably does too
Decouple the data. Use IDs into a data storage. You can even do that during serialization and keep your current code structure as is.
Basically flatten your serialized objects.
Where do I find input settings in? For exampe, there's Input.GetAxisRaw("Horizontal");, where do I add new axes and button bindings?
Not sure what this means but I'll research it later today, thanks
Under Edit > Project Settings > Input Manager > Axes
This is for the old input system
I see. Yeah I guess I want to use the new system
I searched it on YT and there's a video from 5 years ago for the new system
And then the author has
But I don't have that in my interface
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
In this Unity tutorial you'll learn how to use a feature of Unity's new input system called Input Action Assets.
📦 Example Project: https://www.patreon.com/posts/25093570
#unity3d #unitytips #gamedevelopment
👨💻 Join our community: https://discord.gg/NjjQ3BU
❤️ Support the ...
And it's completely different to what he has
I just opened a new project and without doing anyting i got this error...
Seems like a dependency file is missing. Try deleting your library folder and letting unity regenerate it. And/or check the package manager to see if the used package is compatible with your unity version.
Collab hasn't existed for years, you can just uninstall the package. And if you're starting a new project you shouldn't be using such an old editor version anyway that includes Collab
private void OnTriggerEnter(Collider other)
{
if (other.transform == player) // Ensure it's the player colliding
{
// Apply knockback force
Vector3 knockbackDirection = (transform.position - player.position).normalized; // Direction away from player
m_Agent.isStopped = true;
m_Rigidbody.isKinematic = false;
m_Rigidbody.linearVelocity = knockbackDirection * knockbackForce;
// Temporarily disable movement for the knockback duration
StartCoroutine(ApplyKnockback());
}
}
private IEnumerator ApplyKnockback()
{
isKnockedBack = true;
while (m_Rigidbody.linearVelocity.magnitude > 3f) // Continue until velocity is less than 3
{
m_Rigidbody.linearVelocity *= 1-knockbackRes;
m_Agent.velocity = Vector3.zero;
m_Agent.destination = transform.position;
yield return null; // Wait for the next frame
}
// Re-enable NavMeshAgent to continue movement towards the player
m_Agent.isStopped = false;
isKnockedBack = false;
m_Rigidbody.isKinematic = true;
}
this is for a navmesh agent, for some reason in the corutine, the y value keeps decreasing, cause the linear velocity to be (0,-3,0) and making its magnitude bigger then 3.
why is the y velocity decreasing while its on the ground?
What y value? And how are you confirming it? Add some logs.
I was using breakpoints
yea i should really get into the habit of creating logs
the linearVelocity's Y value is decreasing for some reason
-# im gonna add logs rn actually that would help a lot
You are multiplying it by 1-knockbackRes, so it's probably fluctuating rather than decreasing.
Assuming the result is negative
I figured it out
thanku lots though
how can i decrease the time my Capsule needs to reach the highest point of one Jump?
increase velocity and gravity
ah ok thanks
(assuming you want to keep the highest point the same)
yeah
from v'^2 = v^2 + 2as
v' = 0 (apex)
s is constant (height)
a=g is negative (gravity)
-1/2 • v^2/g = s
to maintain the same jump height you have to keep the ratio v^2/g constant
@rough bough
To tweak my gravity I use Demos with the formula y = vt - gt^2 given v and g :)
It helps visualize the changes.
but where do i need to add this ? 😅
Yeah. It’s a useful tool for double checking math
try plugging these in and playing with s and v
s=1
v=1
g=\frac{v^{2}}{2s}
y=vx-gx^{2}\left\{y\ge0\right\}
```(you can copy these straight into desmos)
alright thanks for your help 🙂
(keep in mind the x axis is time, not distance)
ok
Question about raycast. Lets say I was trying to do a system where you could pick up items. I still have an issue with occasional camera snapping but it got noticebly worse when I added more scripts, and one of them was a raycast script, and I'm wondering if (for any of you that may use raycasts) when you have an item you want the player to be able to interact with, do you think it would be better if I had it where the player raycast wouldn't be sent unless I clicked a specific key, and then tried to make the item have some sort of distinction (whether it be a glow or something) for the player, or do you just let it run in void update, and work around it?
I still have an issue with occasional camera snapping but it got noticebly worse when I added more scripts, and one of them was a raycast script
What does "camera snapping" mean, and why would it have anything to do with raycasts.
Idk I just assumed it could be a performance thing, since it seemed to get worse when I enabled the rest of the scripts
do you think it would be better if I had it where the player raycast wouldn't be sent unless I clicked a specific key, and then tried to make the item have some sort of distinction (whether it be a glow or something) for the player, or do you just let it run in void update, and work around it?
You would typically be doing it every frame because you want to be able to do things exacrtly like that selection glow
Sometimes the camera would just sort of jump while turning
Doing a single raycast every frame is absolutely miniscule in terms of performance
Likely a bug in your code
nothing to do with raycasts
No I mean like having it glow so the player knows they can interact with it, and then only having it send the raycast to interact with the item once they've clicked on it
The typical reason for something like that is improperly factoring Time.deltaTime into mouse input, which is not correct.
I know exactly what you mean
ah
That's what I'm talking about
so... Time.deltaTime bad in this situation
If you're multiplying it into your already-framerate-independent mouse input, yes it's bad
Very common mistake.
Nothing
you don't need any time-based adjustment for mouse input
How would Time.time make sense>
Think about what the code is doing.
when you're trying to do something per unit time, you design it in per second, but you implement it per frame or per physics tick. deltaTime/fixedDeltaTime lets you do that conversion, from per second to per frame or per tick
when you aren't doing something per unit time, all of that goes out the window, because you don't have to factor time into anything
I'm going to be entirely honest, I still don't properly understand all of the properties of the Time. I mean some of it I understand from the documentation but most of it kind of just goes over me.
Mouse input is already "how much the mouse moved during the last frame
So it doesn't need to be adjusted
Try to understand. They're not that complicated.
I will do my best
Time.deltaTime is simply "the number of seconds that have passed since the previous frame"
Thank you, it actually worked. Its been bugging me for weeks, so I was just ignoring it and trying to work around it on other things.
I gotta understand this time. class a bit better because I constantly see it in tutorials but i never really questioned why it was there.
Time is just a central spot for time-related stuff. you need to understand deltaTime specifically, and when to use or not use it
It’s typically better just to update your game on a fixed frame rate
not if you want your game to feel smooth and responsive.
Also reading input in FixedUpdate results in missed input
Not for input polling, no.
depends on the kind of polling you are doing
Yeah fair enough
If it updates 60 times per second it should not matter
it does
oh, it will matter a great deal, many events only fire on one specific frame, miss that frame and you are fucked
what if you have more than 60 fps
It will completely break the experience of your game. Try it and see.
Hello
Wdym?
and why would you ping me?
exactly what I wrote
The rendering logic is decoupled from the game logic, so it’ll still run
My current project uses this method and I haven’t ran into problems yet.
Nothing
good luck ¯_(ツ)_/¯
inputs are frame-bound. if you're checking for pressed/released events in fixedupdate, you might miss the frame where pressed/released was true.
That won't survive someone else playing it on a different machine.
then don't #📖┃code-of-conduct #854851968446365696
what happens if you update position 60 times a second when you render 120 times a second?
Likewise if you're handling mouse input in FixedUpdate you are missing frames which will result in stuttery/jagged motion.
Okay
A press is held till the end of the frame once it is polled.
I don’t use mouse input.
right.. so if you update slower than fps, it's gonna miss that frame
That's one reason you haven't noticed an issue yet then.
How are you doing there
For your information I have someone that can make an avatar from the scratch if you don't mind
Wouldn’t that happen regardless? I am still recording the inputs in update just processing them at a fixed tine stamp
not if you update when you receive the input
You said you were using FixedUpdate only
so that's not true
https://nohello.net/en/ please
this is not a place to advertise #📖┃code-of-conduct
This is a coding channel
No. For the game logic.
"game logic" is really vague, but yes you need to process things in the correct places, that's the entire point.
it's a bit misleading to say "update your game on a fixed frame rate" then imo
since "update your game" is incredibly broad
That is why I clarified “#💻┃code-beginner message”
Oh sorry
that clarification just sounds like you're denying that input gets missed lmao
but aight, makes a bit more sense now
Oh, my apologies then.
I just used the fixed time stamp for progressing game time, physics calculations, etc.
Yes, physics calculations are explicitly what FixedUpdate is for.
Oh sorry
Hey yall, I'd like some advice for a 2D shooter-
I'm recreating Gun Smoke for a class project. Gun Smoke's shooting system allows the player to shoot left, right or middle
So i've placed some empty gameobjects for where I want the bullets to instantiate from, but i'm stuck on how to approach accessing the "left", "middle" OR "right" gameobjects
lets say the player clicks both left and right mouse, this would have the player shoot from the "forward" points (refer to image)
The only idea that I've gotten is creating a for-loop within the shooting script, and then just accessing the specified indexes in an array of transforms, so for this example it'd be firepoint[2] and firepoint[3]
with some plans to bringing in powerups like a shotgun, which will shoot more bullets from the same points, is this a good idea or is there a way better way to deal with this?
It depends how you want to access them, but if you want to be able to, in your code, spefically specify one of them, just make a field for each one.
if you want to write a for loop and shoot all of them at once, for example, then put them in an array
and there's nothing that says you can't do both
e.g.
public Transform leftFirepoint;
public Transform rightFirepoint;
Transform[] allFirepoints;
void Awake {
allFirepoints = {leftFirepoint, rightFirepoint};
}```
and for this purpose it'd be a lot better to have one PlayerShooting script instead of a GunShoot script for each firepoint object?
Why would each firepoint have its own script?
It's not really a question that can be answered in general
ah you're right
Hey guys, student currently extremely delirious and losing his mind due to lack of sleep.
I have a presentation in a couple hours and it seems I managed to break my buttons and reverting isn't fixing them. Zero clue how, even tried doing it from scratch in a new project.
It's in VR on an HTC vive. They were working PERFECTLY before I tried to add a new button. I reverted the change but they're STILL BROKEN.
Yes, I did reimport all, I deleted Library, and I started a fresh project and went piece by piece there but maybe the sleep deprivation is getting to me because nope still nothing.
!code, please use a paste site
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I can't use the basic "button" component, because I need it to be "do function while button held"
ah sorry
Right now explain what is 'broken'
So it's supposed to (while held) raise a table, and then at max table height it extends a tray until max tray extension.
There's also a button for the inverse.
And a button that makes it go to the "table all the way up, tray fully retracted" state
VRHoldButton.cs is for the first two
VRHomeButton.cs is for the bottom one
So why is there absolutely no evidence of debugging in your code?
because I send it directly to an htc focus 3 and don't get logs
oh yes you do, add debugs and do a developemt build then look at the player log
I'm also incredibly sleep deprived right now and this is my first project in Unity... or C#... let alone VR
still haven't said what's broken
then sleep/ Inexperience+Tierd == incompetent
Steve, shut up.. you're not helping at all 😄
oh right, so uhh it used to work but now it doesn't at all. I didn't mess with the buttons I only tried to add a different new button.
The ray interactions still work properly from the controller, as there are other things that are still working in the scene. But even though I didn't change anything about the controllers or how they trigger on the buttons... they stopped working
so, still not telling us what's not working
I tried going from scratch just setting up the controllers (just the sample xr interaction setup) and then setting up the canvas with those scripts.
"not working" and "its broken" are not discriptions of what is/ isn't happening
NOTHING is happening. I click at the button and nothing happens. It used to complete the, as I explained earlier, "moving the table" task
so.. you need to troubleshoot it
it's literally just supposed to be translating a table along the y-axis, and if at max then it translates the tray that is a child of the table instead
Look at the inspector, make sure everything that needs assigning is still assigned.
Add debug logs all over the place to make sure the various things are being called when you expect them to.
are you able to move it in the editor? do you have GraphicRaycaster components in your canvas?
Man, just debug your damn code
as I said before I don't know how????????
This is literally my first time ever touching unity or vr
And I told you how
no you vaguely mentioned a path. Idk what you're talking about or where to see the logs
you know how to write a Debug.Log statement, right?
Debug.Log("enter some useful text so you know where it's coming from");
yes but if I'm building directly to a VR headset idk how to check its logs
so don't build directly to the headset, run it in editor..
!logs, look at the Documentation link
you want player log
dev build has a console btw so logging works
IPointer's don't work on colliders, they're for UI
why did you add box collider and rigidbody?
throwing everything that makes sense at it at this point bc im barely maintaining consciousness
I got it to work with arrow keys in editor and it moves
It ain't gonna run away from you overnight
remove those, re-enable the image components - make sure 'raycast target' is enabled
I'm a student who broke his project the night before the presentation
my presentation is in a few hours and this is important
I got the directional shooting pinned down basically, though now there's the issue of the left + right click not registering consistently
so if i were to spam left + right, i'm expecting the player to shoot from the middle, but they're shooting from left & right simultaneously
now I understand that this is because of how Update is handled, it's checking every frame so the chances of mouse clicks lining up is very small, but even with some timing handlers I'm still getting inconsistent results, even tried adjusting the buffer to higher values
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
wait that might be literally it
Thank you I love you I hope you win the lottery
You couldn't have had this issue on Friday when the euro lotto was £170+ mil 😄
Ngl that sucks 😭
I had accidentally disabled the image component while I was copying it around without remembering raycast target was in it
I had set the alpha values to 0 so it made no difference to the screen
just fyi - adding something that wasn't there before to try and fix what once worked, doesn't make sense
sleep deprivation goes crazy, but thanks to you I might get to get a nap in ❤️ ❤️ ❤️
it's also a good time for learning git and not waiting until the last minute possible to finish your tasks 🙃
nah those were there before thanks to the desperate attempt at asking gpt for help
ah, we've all been there as students
never go to GPT
gpt will most likely lead you into the wrong direction
oh no, it was all fine yesterday. I just wanted to add an extra button
anyway, stop chatting in here now.. and go finish what you need to / sleep
it will give you the most common second idiots answer
also for some reason our project hates git
every time we pull we need to fully rebuild library and often everything gets unlinked or loses textures
are you commiting the .meta files?
it's not your project that hates git.. sounds like you've got it setup incorrectly
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yes, but it's easier to say it's the project because there are 3 of us
... I uhh... we might be I gotta fix thaaaaat
if you are then its fixed.
look for something else
look for your bed
hey yall, having issues with implementing simultaneous button presses
https://hastebin.com/share/yehidohoza.csharp
I want the player to be able to spam-click to shoot in any of the three directions (which is why i'm using getbuttondown instead of getbutton)
However i'm having great issue with triggering the forward shooting, even while raising the buffer timer, it's very inconsistent and activates about 10% of the time
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
if i want to get the children from OnlineButtonToggle, will it also get the children of its children?
I just want to get backToMenu and Rematch
it should be just the first layer of children
so back to menu and rematch
but not the image from backtomenu
you'd need to use recursion to get children of children
i have different cities i want it so thats its buildable in each city and if u upgrade one city it doesnt upgrade in others i know what im doing is wrong but is there a way to do something like this
as long as you keep them as seperate instances it should be fine.
cool, i dont want the children of children so thats fine
i left unity for a while so i forgot what instance means
do u mean like seperate scripts for each type of building
it means each time you put this script on a gameobject it creates a new instance for you.
so each one has their own copy of the values
ohhh
but i want it so that its easy to add buildings and players can mod it
so write the code clean
what does that mean
write code that is easy to do what you want it to do
This part indicates that you need to transform everything you write into a usable API that people will need later on to build on top of it
ok but my question rn is how i can do something like this
have an instance of each , i told you
Design things in such a way that it allows extensibility, specifically since others may need to use the features you want to implement, so they need to understand what's going on, how it works, & why it works
so players will be able to make new prefabs if i make an api or something like varonex said
yeah sure , you'd probably need to look into asset bundles or something like that to insert the asset. the data is easy cause it can just be Json ,CSV etc. ? whichever
so right now im gonna make a script called building stats and make different building gameobjects and instances
I mean sure you can make it a separate class too. It just needs to live on an instance so you can change the data
How do I improve consistency for the ShootForward function? https://hastebin.com/share/yehidohoza.csharp
I've been stuck on this for hours now, in the video you can see I'm trying to get it to trigger with very little success
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what do you mean by consistency?
basically i'm trying to get the player to shoot forward (or from the middle), by clicking left & right mouse
but it's only doing the shooting left and right
maybe around 10% of the time I get what i need
unrelated but i dont think you should use rigidbodies for your bullets unless you want them to have physics
if they just go straight then they can just raycast for collisions, rigidbody is worse for performance and will not register collisions sometimes when its a fast moving bullet
pretty sure you were already advised to add some debugging to your code which you do not appear to have done
rigidbodies are fine, and if set to continuous detection will work fine
no, i haven't had anyone respond, it was for the other person in chat at the same time
it solely depends on what you are looking for, raycast bullets are not the only one you should do
well your logic in update looks very suspect so I advise start adding debugs there
it's not fine, especially with continuous the performance will be even worse and will still tunnel through colliders. raycasting is just far better
i'll look into raycasting later, it's just this one issue that's been incredibly frustrating to figure out
you shouldn't be putting any type of object up to speeds of which the collision system cannot register collisions, it is fine. As for performance look into pooling objects and other performance options. Rigidbodies are fine
besides as I stated before it depends on what style of bullets you actually want, and moving objects via transforms is horrid so rigidbodies will work fine
these bullets look fast enough for them to tunnel through stuff, dont they?
no
unless you are working with a paper thin collider which most of the time you wouldn't be
like every mesh collider? 😄 what's wrong with moving objects with transforms btw?
They would most likely clip through walls
of which you would need to make your own collision detection, which rigidbodies do and are probably optimized for the physics engine
but with bullets isnt a single raycast enough? or boxcast if you want it to be more precise
it depends on what type of bullet you want
if you want a hitscan bullet sure use raycasts, if you want a projectile use a rigidbody.
i always thought a bullet moving via transform and raycasting forward every frame was better than a rigidbody bullet though
it probably depends on how fast you want this projectile to be, but this argument is arbitrary anyway as none are greater than the other
most of the time, rigidbodies would be fine but it depends on what you actually want as a bullet
tried some debugging and it's just made me even more confused
I'm using Mathf.Abs to get a comparable value to the buffer timer
the only time the shootforward goes through is if the mathf.abs results in a 0
i tend to use a combo of both rigidbody and hitscans for my projectiles
rigidbody one is more as a graphical thing.. doesn't really hit exactly everytime..
with a raycast i can have better detections.. w/ the fancy projectile as fluff
hii how do i make it so that 10 damage will be taken away every 2 seconds in this else statement
"Every 2 seconds" and "in this else statement" seem to be contradictory
Unless this is a condition that runs every 2 seconds
how do i make a condition? pls
ooh how do i run it every a seconds?
To run something at a regular interval you would either use a coroutine or use a timer in Update which you decrement each frame and check to see if 2 seconds has elapsed.
Hello, guys! I have a question. How to play infinitely a sound effect or a music?
What I mean is that I don't want my sound effect to loop but instead to play this sound effect infinitely
@polar acorn
So, what you're saying is you don't want it to loop, you want it to loop
I mean I want it to loop but infinitely bro
Yes I have it checked
So it'll loop.
Maybe the issue is with my clip?
When it reaches the end, it'll go back to the beginning
Because it is 1.20 in duration
when it arrives at 1.20 it stops
It loop sorry
So, I hear the reset sound
That's not cool
Do I really have to worry about it ?
That's what you want isn't it?
Then what do you want
If I am disabling the loop checkbox it just stops when the time comes
8 hours of sleep and a BMI of 18.5
Do you mean you want a seamless transition
And have you been a good boy this year? 🎅
Like that you don't want to notice the music or clip is resetting
Don't talk to me that way.
It makes my knees weak
I am noticing bro that's the problem it is a detail to tell you the truth but the player shouldn't notice that detail
Then the clip should be built in a way that it seamlessly loops
sleep at 3pm to get full hours of sleep 
I have a project, based on a grid of cubes, that change state - whether you can walk through them or not, Occasionally I am able to walk through a cube that visually seems as though I should not be able to walk through.
I assume you want the clip to be like this:
Blahlahlahlahlahlahlah
yes
Anyway- i have a problem of my own, and no, it's not my ammount of sleep per night:
Hopefully this should be quick.
I'm trying to make a raycast return true or false, and am debugging it per frame, but it only ever returns true
Debug.Log(Physics.Raycast(rayOrigin.position, rayOrigin.transform.TransformDirection(Vector3.forward), maxDistance));
But it's going blahblahblahblah (noticing the b's)
Sounds like a loop to me
Not as in it returns true EVERY frame, it`s just that when i'm not hitting anything, it simply doesn't show anything in the log
Show the full !code for this function
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Grid manager: https://pastebin.com/F8MbU4mf
Player movement: https://pastebin.com/VkeTRcB1
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.
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.
I don't think that's at all relevant, but here you go:
literally just do TAF = Physics.Raycast(rayOrigin.position, rayOrigin.transform.TransformDirection(Vector3.forward), maxDistance) as a raycast returns boolean if all you want is a true or false
I think I got my answer. Thanks!
Needed to make sure that it's not inside a condition. Do you have any errors in the console? If you do, the function ends and the log won't run
No errors, no
there's a warning that i'm not using a certain variable but i'll get to that bit of the code later on
Like i said, it never returns false
A semi ghetto way you could do it is making 2 clips, one that starts with the correct Blah, and another that can continue with the rest lah's
So it goes like:
Clip 1 play normally, no loop
Clip 2 starts immediately after, which should loop
So it goes clip 1 > clip 2 > clip 2, etc
I mean, if you loop the sound, it loops the sound. If your sound isn't ending on the same sample as it starts, you're going to hear a difference. This isn't a Unity problem
Yes probably audio file issue
Then it seems like it's just never false
That makes no sense
when i point it up at the skybox, shouldn't it return false?
Like i said, it's not that it always returns true, it's that when it's supposed to return false, the log doesn't update
So added lives to my game and every time u die u get 1 life off with a picture of a pingiun getting of the screen. I made a game data but the lives go down it but the pictures always go back to 3 even when i restart
so it's more like:
Frame 1: true
Frame 2: true
frame 3:
frame 4:
frame 5: true
that is assuming i point at the skybox during frames 3 and 4
Try storing the result and logging which object it hits
Do you have Collapse enabled in the logs
Try disabling it and see
same behavior
Can you send a screenshot of your Unity window with the console open after you've been pointing at the sky for a while?
Is anyone able to help me please?
The whole window so I can check a bunch of stuff at once
Yeah that's what I was expecting
what are the runtime errors
null reference exception on line 55 of this script
i didn't check if it was hiting something before checking if that something had a certain component
rayOrigin is null
Hello. I have a problem that I am confronting for a long time. I know how to make the character move, but I am not able to make a jump function to work properly. Any advice on how to do that?
how is it null? right here you can see a reference to it
what is "not working properly"
On this instance at least
either it doesn't work unless I use a condition that checks the ground (in wich the case, it only does the jump animation) or it jumps to infinity by spamming the jump button
is this func alr made it for dynamically loading different scnes for the levels
that didn't seem to be the problem
i just added an hit.collider != null to the if statement on the 55th line
and not everything works as intended
huh.
Post the code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ground check is always needed if you dont want infinite jumps. Perhaps show your setup like code and everything else that helps others help you
one sec
Raycasts may not hit anything, so Physics.Raycast() returns a bool indicating whether something was hit or not, you should use it
if (Physics.Raycast(...))
{
// code
}
CharacterController characterController;
Animator anim;
Rigidbody rb;
int isWalkingHash;
int isRunningHash;
int isJumpingHash;
[SerializeField] float speed = 5f;
[SerializeField] float jumpSpeed = 5f;
[SerializeField] float gravity = 10f;
[SerializeField] float speedH;
[SerializeField] float speedV;
string _currentDirection;
private float yaw = 0.0f;
private float pitch = 0.0f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
anim = GetComponent<Animator>();
characterController = GetComponent<CharacterController>();
isWalkingHash = Animator.StringToHash("isWalking");
isRunningHash = Animator.StringToHash("isRunning");
isJumpingHash = Animator.StringToHash("isJumping");
}
// Update is called once per frame
void Update()
{
//Vector3 forward = transform.TransformDirection(Vector3.forward);
//float curSpeed = speed * Input.GetAxis("Vertical");
//gameObject.GetComponent<CharacterController>().SimpleMove(forward * curSpeed);
bool isRunning = anim.GetBool(isRunningHash);
bool isWalking = anim.GetBool(isWalkingHash);
bool isJumping = anim.GetBool(isJumpingHash);
bool forwardPress = Input.GetKey("w");
bool runningPress = Input.GetKey("left shift");
bool jumpingPress = Input.GetKey("space");
Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection = moveDirection * speed;
// Handle walking animation
if (!isWalking && forwardPress)
{
anim.SetBool(isWalkingHash, true);
}
if (isWalking && !forwardPress)
{
anim.SetBool(isWalkingHash, false);
}
// Handle running animation
if (!isRunning && (forwardPress && runningPress))
{
anim.SetBool(isRunningHash, true);
}
if (isRunning && (!forwardPress || !runningPress))
{
anim.SetBool(isRunningHash, false);
}
if (jumpingPress && characterController.isGrounded)
{
moveDirection.y = jumpSpeed;
anim.SetBool(isJumpingHash, true);
}
// Check if jump animation has ended
AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0); // Assuming layer 0
if (stateInfo.IsName("Jump") && stateInfo.normalizedTime >= 1.0f) // Animation has completed
{
anim.SetBool(isJumpingHash, false);
}
// Apply gravity
moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
it's a mess and I need to clear it a bit more
what's the reason for the RB when you are using a CC 🤔
caecpr is this code alright?
to use the animations?
Im the wrong person to ask, my brains as smooth as a raw chicken breast, but just so i have context, what are you trying to achieve here?
Make your script control animation… not the other way around.
why would you need a RB for animations
...Collisions?
Supposedly you do want your character to collide with stuff
basically dynamically loading secnes when buttons are pressed on my loading screen and i love chicken breast 🧟
Which the CharacterController does
character controllers provide collisions?
you literally do not need a rb for animations
like i said, brain's smooth as a baby's bottom
You shouldn't have a Rigidbody and CharacterController on the same object
oh, I see
can I use animations with something else that's not rb?
these are unrelated concepts
animation clips do not require RB or CC
I suggest you use the animator as the animation component is legacy
perhaps you are thinking specifically of root motion?
(but I don't see any sign of that in your code)
animator as in puting the animations there?
fen can you rate my code? (it is for dynamically loading scenes
I took a look into it
Are you setting your button texts based on the names of the buton's GameObject name?
yeah
They already are.
alright, so i've been doing some debugging for the past hour or so regarding my input detection
I still can't figure out why the ShootForward is being very inconsistent, only ShootLeft and ShootRight are being triggered most of the time
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yup I see that
You have to click both buttons on the same frame
That sounds challenging.
Perhaps you meant to use GetButton
that i understand yeah, though i've tried implementing a buffering system
yes, you must choose only 1
GetButtonDown only returns true on the frame that you press the button
I'd like the player to be able to spam-click said button, which is why it's buttonDown and not just button
this is the code btw if you wanna take a look at the code it works good
if (fire1Pressed && fire2Pressed && (clickTime < fireBufferTime))
{
ShootForward();
fire1Pressed = fire2Pressed = false;
}
else if (fire1Pressed && !fire2Pressed)
{
ShootLeft();
fire1Pressed = false;
}
else if (fire2Pressed && !fire1Pressed)
{
ShootRight();
fire2Pressed = false;
}
This will not give you a "grace period" -- it will immediately fire the left side and reset fire1Pressed
So if you right click one frame later, fire1Pressed is already false again
Perhaps you meant to do this?
bool bufferOver = (clickTime >= fireBufferTime);
if (fire1Pressed && fire2Pressed)
{
ShootForward();
fire1Pressed = fire2Pressed = false;
}
else if (fire1Pressed && !fire2Pressed && bufferOver)
{
ShootLeft();
fire1Pressed = false;
}
else if (fire2Pressed && !fire1Pressed && bufferOver)
{
ShootRight();
fire2Pressed = false;
}
This would only fire the left or right sides after enough time has elapsed
I bet that wouldn't feel very good, though.
i'll try this real quick
oh no imagene that sort of stuff with chess moves
But if the buffer period is very short (maybe 50ms or 100ms), it will feel..decent enough
that's actually exactly what i've been looking for i think
because it's working a lot better now
ahhh thank you so much
public void ResetPlayerState()
{
currentLives = maxLives;
Color Color3 = Pinguin3.color;
Color.a = 1f; // Set alpha to 1 (not transparent)
Pinguin3.color = Color3;
Color Color2 = Pinguin2.color;
Color2.a = 1f; // Set alpha to 1 (not transparent)
Pinguin2.color = Color2;
Color Color1 = Pinguin1.color;
Color1.a = 1f; // Set alpha to 1 (not transparent)
Pinguin1.color = Color1;
}
what's wrong with this?
you've accessed the non static property a of the static class color
because you typo'd a variable name
because you put Color.a instead of Color3.a
oooh
as advised in #archived-code-general, you should really be using a loop to do this
you're doing the same operation many times
Look at all the time you're wasting with copy and paste errors
fen is this code ok 🙃
make sure that your !IDE is configured so you can easily see and fix these mistakes and so that you are less likely to actually make them due to autocorrect and other useful features
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Do you speak portuguese by any chance?
i think you should explain a bit more on what "dynamic loading" means
dutch
hallo
hallo
it binds the scenes to the levels by name
and does it work?
yeah but i wonder if the code looks good
if it works then it's good
getting the name from the button isn't very modular
you're doing the opposite, instead of buttons from list of levels/names available
then linking each created button to that name or index
yeah?
but is it bad then 🥲 ?
yes its bad
basically if you want to make more levels then it's not good
you should have the list of level names in an array of string, then you can loop each one to create button for it / linked to it
or use index/integer if just level1,level2,etc
so if you want to add more levels later then it's easier for you
not the way you do it
i mean i make a new scene and give the text of the button the same name and it works
you're grabbing the level name to LoadScene from the button/ui text, that is silly
your code should as functional as possible even without a UI.
but don t understand your suggestions how you bind it to a scene
So here's how I do it in my game!
based on the number of levels you loop through them to create a button for each level.
Each of my levels (I call them "scenes", how confusing!) is defined by a scriptable object
but why do i want to cuz it needs to fit in the ui will have 5 levels max max but prob 3
The object stores information like the name and description, plus the actual scene to load and a thumbnail
I have a Scene Button component that takes a single scene definition and sets itself up
well, actually, I used to -- now I have a more complex scene-selection menu
I love doing this kind of thing. It turns a bunch of random pieces of data into a single object
SOs are goat
So now I'm not juggling four different things and making sure they're not getting out of sync
🙆♂️
not a big deal now but I'm telling you its not going to scale well to create a button first and put the name of the level there instead of tracking it in a levelmanager
It's impossible for the "Level 3" button to accidentally take me to Level 4
I removed the possibility of that happening
I already make enough mistakes 😛
wow that's cool. what's guid and what type are the label and description?
The label and description are localized strings
My game is almost exclusively only playable in English, but I use localized strings everywhere
so that once I do some translating, it'll be easy
I use almost no plain strings
oh is that part of the unity's localization package?
Yeah
will keep it in mind atleast it is intresting for me to work with c# for the first time and wokring with a new engine a lot to learn never made multiple levels with ue5 just big open world games 🙂
Guid is part of my "object registry" system. You can read about the idea here
https://bronsonzgeb.com/index.php/2021/09/11/the-scriptable-object-asset-registry-pattern/
I use this everywhere, too
Each setting in my game is a scriptable object asset. Saved settings data is a bunch of key-value pairs where the keys are GUIDs
It's a good habit to get into early (:
gonna be reading that, thank you! 👍
I use almost no strings (except for string representations of GUIDs 😛 )
so when I rename settings, nothing breaks
yeah but also wanna release a game everything can eb better at the end but at some point something has to be made
there is such a thing as too much foresight, haha
time will learn ig just happy c# feels natural and unity has a decent ui (still not a nice as ue5 tho 😏 )
or sometimes you end up digging yourself deep then go, phew should've done it this other way.. lol and waste more time fixing mistake than redoing it properly
not really have 2 weeks for it
yeah but not planning to make it a big game and should be pretty easy to fix then
it can be tiny you just have to understand your codebase so you can easily fix it / extend it
but happy with all the help feels like im learning the engine quite quick 🙂
you eventually come up with your own system that works for you, there usually never one sepcific way to do something (solve problem)
At the same time constantly overhauling things when it isn't totally necessary can waste a lot of time.
A lot of it just goes for life and engineering in general
The best part is no part, and don't optimize something that shouldn't exist anyway
simply do the right thing, and not the wrong thing 😉
you develop a sense for this over time
sort of
i would like to reduce damage with a delay, does anyone know how to do this?
- Don't share code with screenshots. Use !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Second,
i would like to reduce damage with a delay
What does that actually mean?
As I mentioned to you earlier: #💻┃code-beginner message there are two basic ways to do something at a regular interval. Use one of those.
in the if statement damage is being taken away instantly , i want a 2 second pause every time
no it's not "instantly"
it happens when the code runs
which is every frame, since you're in Update
Like I said, use one of these.
alr tyy
does anybody know where i can learn just the basics? idk, i try using documentation, doing my own scripts and trying everything and i couldnt even get player movement to work. Finally i had to google the right script but there is no fun for me doing that, i would really like to get any help.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
When I make an enum, should it be outside the monobehaviour class, above the variable declaration in the class, or under the variable declaration in the class? Assuming I only have one class in the script and the enum doesn't need to be accessed anywhere else. This is mostly a question on best practice and not necessarily function. I'm new and just learned about enums but I'm not sure about this
If it's only accessed inside the class, then it can be declared inside that class
Otherwise enums are types like others, the best practices recommend to put them in their own file
okay. but the class will be able to access it if it is outside of it in the same file, or in a different file and made public, right?
Yeah it depends on the usage. If used only within the calss, you can define it within.
If used otherwise, then you could either define it in the same file or in a separate file depending on how closely coupled it is to the other class in the file
Which file you define it in has no bearing on where you can access it from
as long as the two files are in the same assembly
Okay so it needs to be made public in both situations
All the usual rules about access modifiers apply
Not ncessarily public
if it's public it can be accessed from anywhere
If it's internal it can be accessed from the same assembly
Inside classes they can be made private
got it, thanks guys
🤓☝️ there is the file access modifier
(basically only relevant for code-generation)
if working on a game like hearthstone, where there are thousands of cards each with a special characteristics and effects. How do you like design the card's code?
I've seen approaches where each card have their own c# class (inheriting from scriptable object BaseCard class), but is that approach good?
Is there a way to have a key only register once every time you hold it down or tap
for context I'm making the pause menu, and every time you press esc, it registers like 10-20 times and if you hold it for a second like 500 times
how are you detecting these key presses
the new input system, in an action map
okay but how
what do you want me to show you? my code? my action map?
mate, this is a code channel. i am asking about your code and how you are detecting the key presses in your code
didn't see the input channel sorry
okay but it's clearly something you are doing wrong in the code. so share the code if you want help
It will still be useful to see what you're actually doing, yes
there are like half a dozen ways to use the input system, you've shared almost no information about how you are using it
An InputActionMap is just a list of InputActions; it's not how you actually receive input!
we need to know how you are actually receiving this input
Is it better do everything in 1 singular script, or make multiple and connect them together?