#💻┃code-beginner
1 messages · Page 566 of 1
No, nothing seemed to work
you dont want to change the position on button press
probably
unless ur game is a top down rpg or something
It's a frogger
Yes, 1 tile
gotchu
so you already know how to increase the position
in a script on the character, you need to check if the player is pressing anything
you need to do this every frame
so inside the script, you need to work inside void Update
Also, will something be different if it's touchscreen?
which goes executes every frame by default
well yea you would need on-screen controls
dont need to worry abt that rn
inside update you can check
if (Input.GetKeyDown(KeyCode.W))
then you change the position as you know
but honestly i think theres probably a way to move a set tile instead of moving a random position that you add
so could probably look a tutorial for that but this is the idea of what u wanna do
I found a lot of tutorials, but none with touchscreen
touchscreen is just using all ur same code but with different inputs, it shouldnt be that hard
if you are just starting out, why are you worried about touchscreen specifically
if its frogger
its just direction movement
I'm trying to create a (terrible) C# Script system (I previously used Lua, but it was too slow). Basically I need a field in the inspector into which I can drag in a C# file. This file will have a single class extending a base class and I wanna create an instance of BaseClass using the class inside this file. I hope this explanation is understandable enough
A work around solution I came up with is to create a giant enum where each value represents each class, but it quickly gets cumbersome updating that, so hoping for an easier solution
you could easily change WASD and left mouse click to directional swipes and tapping the screen i mean so probably just follow the tutorial to learn a bit abt unity and c# then you could add touchscreen in minutes
what is this exactly? is it stats or something
Im making a bullet hell game, and each pattern allows you to write custom bullet behaviour via state machines.
Previously this behaviour was stored in Lua scripts, but having 10k Lua interpreters running destroys fps surprisingly much
can't you use scriptable objects for this?
you can write c# code in scriptable objects?
yes
oh wait, you mean like a class that extends ScriptableObject?
thats actually pretty genius
although don't Scriptable Objects share data? I'd need to potentially create thousands of instances of the class, and they'd need their own parameters to not mess with each other
yeah, if you intend to store data in them, then every usage should be a new instance
this shouldn't be an issue though, you would probably need to store this data somewhere anyway
SOs should be immutable anyway. You should create a runtime class that makes use of the SO data if you need something to store mutable state.
How would I implement an attackCoolDown function for when an enemy damages the player? Here is my code:
Considering the use case custom behaviours will often require additional paramters not found in the base class bullet
Additional parameters are fine. It's just data.
I meant like parameters that might change during runtime
These should be in the runtime class, not the so. Ideally.
But since arbitrary behaviours can require arbitrary data it means I'd need to make a generic storage system that can support anything or add more parameters to the base container class for every new script, both not super ideal. Perhaps SO's are not ideal for this specific job?
A dynamic storage system is too fancy a term, what I mean is for example a set of dictionaries with string keys and various values, like floats, ints, vectors, and the bullet script can update data in the dictionary via the key
What's an "arbitrary behavior"?
If you really need something like that, then it's an option. But I think you're overestimating the amount of different parameters you might need.
well for example you might wanna make a simple bullet which moves but also oscillates with a sine wave. Maybe you wanna make a pattern where there's a grid of bullets and one moves causing bullets in the grid to accelerate away from it, or a pattern where the bullets can stop, change orientation and continue moving, etc etc
That's where composition comes to the rescue. You can have separate behaviors for bullet movement, rotation, effects, etc... And these behaviors can further be broken down into more basic components.
For example, you could have a base movement behaviour that just moves the bullet forward over time. And then extra behaviors that apply additional effect to the movement, like adding offset based on the sine wave.
this is pretty tricky to combine with the state machine approach from my experience, basically bullets have states and each state has its own update function. This makes it way easier to create super specific bahaviours, or allow bullets affect other bullets by switching their state externally
I don't see any problem with using a state machine. Though it depends what exactly you're doing.
Like, what states do even bullets have? Flying and not flying?
I mean, if the current architecture is not following composition it could be a huge undertaking
I really think the simplest solution would be to inherit from ScriptableObject and then create a new instance for each usage
if for some reason you're against mutable SOs you could probably use prefabs as well
then every different bullet behaviour would have its own SO and it would be easily swappable
The states are basically an interface with 3 functions, on state enter, update and exit. These functions can be defined as anything, so yes flying and not flying is possible. This is useful if you wanna make bullets that can switch between complex behaviours based on timers or other parameters
This sounds a bit weird to me. But I don't see any issue with combining it with composition. In fact, you could compose the states as well.
I guess I will research how to do that, although it's hard to imagine right now
Hello, I think I get what you mean. Although I'm not entirely sure what you mean with composition, like some sort of smaller list of helper classes?
Like a collection of classes which extend some interface and bullet scripts can have a list of "processing" interfaces that help with position calculation?
ScriptableObject
thanks , what's the diff between this and a c#script ? and why use it ?
Sounds like lack of experience tbh
Value types are immutable as they are passed by value. Modifying the property directly is impossible since you get a vlaue type when you access it, so it points nowhere. That's why you first get the value, modify it, then reassign it
You can call methods like Normalize() since they modify the actual struct rather than getting a copy
This is not a script at all, it's an object/asset.
This is more like an instance of a script on a GameObject than a script itself. The script is separate.
ok thanks a lot
so i beforehand create my script , then create a scriptableobject of it ?
sry i'm new to dev , i'm an artist and i want to continue a project that i was doing with a dev friend, sadly he left the project so i try to continue it
you could have a coroutine that waits a certain amount of time before changing the variable that allows the enemy to damaged again
you make a class that defines the SO and then you can make instances of the SO yes
well what i said didnt make sense since the code actually works
u can do position += new vector3
whats the best way to learn coding?
That's still reassigning, though. Same thing applies here
yt or
that's subjective
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You learn by doing. It doesn't really matter what you follow, or where you follow it on, you have to make sure you attempt to develop yourself at some point
okay
Composition pattern. There are many ways to implemented, but the point is that you break down behavior into smaller components(not necessarily unity components) and implement them separately. The main class then implements the general logic, while the exact behavior is abstracted and delegated to these components. Look up composition programming pattern as my explanation is probably not great.
Why can't I change the maxTerrainCount in unity?
you mean cant see it in the inspector?
yeah
Is there any way to use Resources.Load() outside of Awake() or Start()? Or is there something I can use as an alternative?
Sounds like you might have a compile error. Have you checked the Console?
Could it be that it is private?
must be some errors
void DetermineRecoil()
{
transform.localPosition -= Vector3.forward * 0.1f;
if (randomizeRecoil)
{
float xRecoil = Random.Range(-randomRecoilConstraints.x, randomRecoilConstraints.x);
float yRecoil = Random.Range(-randomRecoilConstraints.y, randomRecoilConstraints.y);
Vector2 recoil = new Vector2(xRecoil, yRecoil);
_currentRotation += recoil;
}
else
{
int currentStep = clipSize + 1 - _currentAmmoInClip;
currentStep = MathF.Clamp(currentStep, 0, recoilPattern.Length - 1);
_currentRotation += recoilPattern[currentStep];
}
}
how do i fix red lines and how do i add weapon sway
Console shows nothing and I already tried to make it public
Resources.Load does work outside of Start and Awake 🤔
Yes, exactly the same way you do in awake and start.
Take a screenshot of your whole console window including the buttons on the top right.
Does this class have a custom editor script
you dont have the "_currentRotation" setup in your script
This is just not valid code in a lot of places. You also need to make sure you declare the correct imports (with Using statements up top).
"MathF" for instance is wrong- The class name is Mathf
Wait, is there a class called MathF too...
Anyway, should be Mathf, I'm pretty sure.
What do the errors actually say
_CurrentRotation, capital C
You are using Random from System. You want to use Random from UnityEngine.
Try accessing it as UnityEngine.Random.
yeah it turns out i was doing something stupid in my testing class, which was causing all of these problems
I thought it was an issue with the main class but it wasn't 😢
The actual Hint in this screenshot even explains the issue and how to fix it... 
i would recommend learning c# before continuing with unity. it'll save you a lot of time in the future
You probably want to stop what you're doing and find a good introductory tutorial or course for C# (Check out Mosh' course on Youtube).
There's not enough hand-holding in the world we can do that will help you advance with your project if you don't know the super basics of programming.
jinx lol
it'll only take like a week...
i dont have week
What's a good tutorial?
so how do i fix that error
you need to know the basic fundamentals of programming before starting anything
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
sani needs spoonfeeding that is it
free code camp has a good one on yt
Aight
i know basics but tutorial i started was trash
You're trying to access an index of an array that is outside the bounds of the array
we cant have you come here asking for help with problems you should be able to solve yourself
ur in a code-beginner
YOU are in code beginner more than anyone else
I agree, you should be able to ask your questions :) You don't know what you don't know.
But in this case, you're not aware of just how much of the pure basics you're lacking- So our answer to you will inevitably be that you need to read up more on C# and programming fundamentals.
We can't code your project for you.
whats index of array
A very basic and fundamental concept of programming.
we're saving you a lot of time right now by not just spoon feeding you answers. it'll take you more than a week to finish what youre trying to do now than to learn c# basics
This?
why are yall gatekeeping it
no, just a c# tutorial first is what you need. then you can go into unity stuff
Nobody is gatekeeping anything. Here, read about Arrays
https://www.geeksforgeeks.org/what-is-array/
free code camp has a 4hr c# tutorial
but what does that have to do with my code
yeah thats what i used starting out and it was pretty great
Your error
You don't know how to use arrays.
thing is, we can teach you but what happens is you are not learning during the process
i will learn after it
I started my project in 2022 and made a few basic things in it but haven't touched it since. I've forgotten everything even what my scripts are for. Hopefully I don't have to start from scratch
simply throwing yourself at the problem won't make it work
arrays don't even take that long to learn
i dont even know where it is
Errors literally tell you what line the error is on
you can double click an error and it opens up in your editor
as long as you relearn c# basics you should be able to read any basic script. you dont need much unity specific knowledge for that
After this error, there will be another error, just as the 3 errors before it we already helped you fix.
At some point, helping you is just us doing your work for you, and your insisting on us doing it is a bit.. Impolite, let's say.
Take your time to learn programming instead, or give up. Those are your options.
double click the big red exclamation mark
bruh those were spelling errors
this one isnt...
Spelling errors that you needed us to help you fix.
you will just follow what we say and that's it, you go back to creating your game by following other tutorials and ending up going back here with more errors
Yes and why did we need to solve those when you literally have an IDE that makes it almost impossible to make spelling errors
it wasnt even red lined
You literally sent us a screenshot of the red lines
This is all valid code. You're just showing us you don't even know how to find the line where the error is occurring.
Why doesn't maxTerrainCount appear in inspector? I'm following a tutorial
it wasnt
that one was correct
Does this class have a custom inspector
No it wasn't. That's why it was underlined.
it was this that made it underlined
spelling mistake
it's case sensitive
exactly
is it corrected now?
yes
No, that's completely valid. You can name a variable whatever you want. You just have to actually use that name
Tbh, I don't even know what that means
i fixed those errors but new error came up
what's the current error
make sure to solve all the code errors. you can check the unity console
You have already been told what this one is. You're trying to access an index of an array that is outside the bounds of the array. You can't get the sixth element from a list with five things in it
Hi, I followed the 3d platformer controller tutorial by the "Dave / GameDevelopment" youtube channel, and i want to add a way to jump multiple time in the air until the amount of jumps that you already did is less or equal to a "maxJumps" variable. how can i do this?
this is my code:
https://www.codebin.cc/code/cm5l4xtup0001mv03bx69utjo:EH85KYr7o8pQPDH3MbwcGEKujpo9UA8LuHPXD4WDkWzP
Codebin Paste:
Description: platformer go brrrr
Language: csharp
Last Edited: 1/6/2025, 2:26:48 PM
Expires: never
do you know how to use the debugger in the ide
put a breakpoint at like line 90
look at currentStep
recoilPattern is an array, and currentStep is an index of that array. If the index is higher or lower (outside the bounds), an exception will be thrown because you can't access anything with an invalid index.
I get so many questions everyday on my videos of people asking why their code isn't working. Sometimes its a simple typo you can infer from an error message, other times its a deeper issue.
Many beginner tutorials first tell you to start putting Debug.Log statements everywhere, which can work and if done well can be a good practice - but its mu...
make sure currentStep isn't more than the length of recoilPattern
Can the adaptive performance be why it doens't work?
Are you in play mode?
yep
you click big green button, put a breakpoint on line 90, then run the game
the game will stop when it hits said breakpoint
in your unty project it'll prompt you to turn on debug mode, enable it
I was, but it doesn't show up either way
Make sure you are not in play mode, and your script wasn't saved either
Can anyone help please?
Thank you, solved it
under the Jumping header add an integer for jumps
where do you call the Jump() function? in the area where you call the Jump function you'll check for the variable you created
do you even know what the code does
yeah i know
but how do i combine this part of code(the one that makes the player jump) with your suggestion? when do i check if the player is grounded?
this is the code:
if (Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
if you want multiple jumps you would need to remove the grounded bool or change it in a another way
under the Jumping header add an integer for number of jumps
in this if condition you can check if the number of jumps ++ is less than the max number of jumps
in resetjump you can set number of jumps back to the default value
we can't spoon-feed you code but this is how it's done
the grounded bool is set to this:
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);
yeah it is checking for the ground so you are only able to jump when you are grounded which is not what you want. you have to edit a few steps
when you are grounded, reset the number of jumps to the max number of jumps
when you attempt to jump, if there's ≥1 jump, consume 1 jump to Jump()
thank you it works now. i needed to do some MAJOR changes to make it work
This is a very basic question but I can't find much in the way of documentation with Mathf.Lerp; If I were to use it to say, lerp an animator's speed over the span of a second, would I do A or B?
animator.speed = animator.speed * Mathf.Lerp(animator.speed, newValue, 1);
animator.speed = Mathf.Lerp(animator.speed, newValue, 1).
All that Lerp does is give you a value somewhere between two other values
That's it. It doesn't do anything "over time"
Mathf.Lerp(foo, bar, 1) returns bar
because you asked for a value 100% of the way from foo to bar
That is all it does, ever.
Beat me to literally every point I was gonna make lmao
If you want something to change over time, you need to repeatedly set the value (perhaps in a coroutine)
Ah, that would make more sense
I was considering throwing it in a while loop
IEnumerator ChangeSpeed(Animator animator, float target) {
float start = animator.speed;
float t = 0;
while (t < 1) {
animator.speed = Mathf.Lerp(start, target, t);
t += Time.deltaTime;
yield return null;
}
}
e.g.
actually, this has an error
On the last step, when t equals or exceeds 1, we exit the loop
the animator's speed never actually reaches target
This could be corrected by adding animator.speed = target; after the loop.
It's very important to grasp that there is no "magic" in any of the Mathf methods. All they do is compute a value given some inputs.
You were pretty much there but with a coroutine it wont hang / pause your game until the while loop is done
That makes sense, is there a reason you're subscribing t to Time.deltaTime after you do Mathf.lerp? Is it along the line of not wanting it to run the first time?
+= is not the "subscribe" operator
that is one way that it is used, yes
It's properly called the addition assignment operator
here, it's equivalent to
t = t + Time.deltaTime;
Learn something new every day 😁
Thank you, I think Mathf makes a ton more sense now
+= and -= are commonly used with event members because you aren't actually allowed to directly assign to them
Otherwise, you could absolutely do
Something.OnEvent = Something.OnEvent + MyCallback;
(that's what actually happens internally)
I really should do more research into how the things I use work. Knowing how to use it and knowing how it works are two different things after all
fun fact, you can override the add and remove functions for events (kinda like properties!)
yeah, you can define custom accessors, just like you can for properties
you just rarely need to
yea ive never done it myself but im sure it has a use
I've got a pretty fresh Unity scene open and I have both a first person controller and a Cinemachine camera set up. In the inspector, Cinemachine allows one to both track a gameobject and set up input axis controls (mouse).
I want the player to rotate with the Cinemachine camera but I do not know how to do so. What can I do?
in this code i dont understand that if the rigidbody.linearVelocity is also the target velocity (in the SmoothDamp) why do we have to write both of them in the smooth damp
What do you mean by it being the target velocity?
Target velocity is a different variable entirely
You need to provide the current velocity so smooth damp can calculate the new velocity for this frame based on it
Of course, right now you're not using the result at all so it won't do anything
if i move the player it is because of the target velocity but the character wont actually move if i dont declare the ribidybody.velocity being equal to target velocity
forget the damping for now
Yes, the velocity won't change unless you change the velocity. Seems like a truism
hence they both are the same
then why in smooth damp we add both of them
or i am understanding it wrong
Because smooth damp needs to know the previous velocity to calculate the new one
If you want to just completely overwrite the velocity and ignore the previous velocity, you can of course set it to whatever you want
but targetvelocity and rigidbody.velocity are the same where is the previous velocity?
because of this
RB.velocity is your current velocity
Target velocity is the velocity you want to be going
Smooth damp will calculate a new one in between to make it smooth
That's for "how fast the velocity is changing"
The fact is smoothdamp is just a math function
It has no idea that the thing you are damping is a velocity
Normally it's a position
Hi everyone, i been looking for a tutorial on how to make multiplayer fps for a basis of my game, so i could build atop of it. But there is many of them and i don't know which one is the way to go today. Also i want to do this as my uni project, as i lost my will to programing, but if i to do something it will be a game. So is there some guide or specific tech you can recommend?
hi guys and happy new year
can someone explain why the hit.point is keep changing even if the mouse stay still, im receiving a diffent values that the last one logged.
i have this cript attached to a sphere and it keep jumping back and forth
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Brush : MonoBehaviour
{
public float sizeChangeSpeed = 0.1f;
public float minSize = 0.1f;
public float maxSize = 5f;
void Update()
{
MoveBrush();
ChangeBrushSize();
}
private void MoveBrush()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity) && Input.GetMouseButton(0))
{
Debug.Log(hit.point);
transform.position = hit.point;
}
}
private void ChangeBrushSize()
{
float scrollInput = Input.GetAxis("Mouse ScrollWheel");
if (scrollInput != 0)
{
// Increase or decrease the size of the sphere
float newScale = Mathf.Clamp(transform.localScale.x + scrollInput * sizeChangeSpeed, minSize, maxSize);
transform.localScale = new Vector3(newScale, newScale, newScale);
}
}
}
it changes because its hitting something else
and you're calling it every frame running it before mouseheld
another collider?
you can log hit.collider.name
lolis hiting itself
yeah thanks
i did this
if (!hit.transform.CompareTag("Brush"))
but now is moving very slow, like it glitching
this is the complete opposite of using layers..
idk what you mean "moving slow" how would this at all affect movement
no, i mean the movement it glithchy
when i move the mouse, the position of the spere is snaped, not smoothing like when the mouse position is
wdym "snaped" and why would it be smooth? You are literally teleporting it to a new hit.point every time it hits a collider point
are you raycasting onto a plane collider ?
no, a mesh collider
i need it later, for collision, for getting the contacts
so why dont you just put what ray supposed to hit in terms of LayerMaskk
so it doesnt even hit it in the first place
i didnt try it, but ill check it out
this LayerMask thing is new to me
[SerializeField] private LayerMask hitLayers
...
Physics.Raycast(..,..,..,hitLayers, etc..
guys I'm trying to make my second game but me and my galaxy brain
decided it would be a good idea to make it be a multiplayer one. Is this a bad idea?
yes
bad idea
second "game" is just not enough. Is your first game a published fully polished single player game ?
or just a learning project / game.
there are soo many systems and concepts that multiplayer needs, you're gonna not have a good time learning it tbh. You can try though small bits a time to get a test to see if you don't believe me lol
can anyone tell me why unity is saying "IndexOutOfRangeException: Index was outside the bounds of the array.
GameManager.Start ()"
which line?
the whole method is full of possible
probably GreenGem is empty/ doesnt have anything in it
oh i think i know what happened thank you
Where do you set Vertical
you are passing a higher value than the clamped version
The preview values you see in the animator window can be...weird
I get NaNs in there all of the time while outside of play mode
lol no
I'm a bit ambitious, yes...
the first screenshot is basically just a value of 0
4.5 * 10^-20 is very close to zero
you can try it though just to see what its like, but honestly 2nd game just isn't enough. You should probably have many many project types , but again doesn't hurt to try / see what its all about.
Project types? Like game genres, or do you mean other stuff other than programming games?
just different types of projects, games and apps, anything in between
heard all about learning how to make a multiplayer game, heard it's just actual evil lol
I dont always make a game in unity, sometimes just work on a specific mechanic or feature
"It can't be that bad" is my thought
it forces you to think a bit different than what you are accustomed to
(It probably is that bad)
the most basics suggestion for you to learn I can say is, forget the Easy Transform Sync that netcode component takes care for you.. Thats too easy..
Instead, try to sync up the same values between clients and server, or do simple sync stuff on your own like that
RPCS
hell even NetworkVariables feel like cheating.. It does all the sync for you
Netcode did make it a bit easier tbh
I'll keep that in mind
Yeah my problem is, I've never actually been that good at programming, more on the creative side, can't exactly hire somebody else either, so I'm stuck with learning it. Been fun though! It makes me think
yeah it can get confusing, just think of it more as a tool you use for logic rather than some memorizing or skilled trait.. or some sort of talent.. anyone can get good at it just like any other tool, the more you utilize it less intimidating it is.
I used to use Game Maker n such platform that only allowed me Drag And Drop logic mainly, was always intimidated of code lol hated GML was "Scary looking"
Here I am 5 years later writing tons of code in c# instead lol
if its not code relevant why did you post it here 🤔
i came here yesterday i dont know where to post this
yes its in image component
oh right
is working fine now, thanks
Can someone please help me understand why the section for wall jumping never happens? The checks for isTouchingWall and isInAir are correct but even when both are true it only ever uses normal jump
{
if (isTouchingWall && isInAir)
{
//Wall jump logic: Add horizontal force away from the wall
Debug.Log("Wall jump");
Vector2 wallJumpDirection = new Vector2(0, 0);
if (BounceLeft())
{
wallJumpDirection = Vector2.right;
}
else if (BounceRight())
{
wallJumpDirection = Vector2.left;
}
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse);
}
else if (!isInAir)
{
//Normal jump
Debug.Log("Normal jump");
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
}
isInAir = true; //Prevent further jumping until grounded or touching a wall
}```
The checks for isTouchingWall and isInAir are correct but even when both are true it only ever uses normal jump
Not possible
you are suggesting that if is broken
it isn't
I understand that
Add some more Debug.Log lines and see what's going on
Debug.Log($"In air? {isInAir}, touching wall? {isTouchingWall}");```
It was my mistake 🤦♂️
if (!isInAir && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)))
But now I have a new issue, it wont add the impulse to the player in the opposite direection of the wall
Sounds like a problem with the logic for picking the direction
What im trying to do is check what side of my character the wall is, so BounceRight() checks for if the wall is on my right
if thats true, wallJumpDirection is set to left and then that is multiplied by wallBounceStrength when I use AddForce()
{
wallJumpDirection = Vector2.left;
}
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse); ```
As far as I can tell the logic is sound but Im worried that Im using AddForce wrong
But what if BounceRight is wrong?
Where is this code all running?
And what does BounceRight and Left do?
And what if neither one is true?
{
return Physics2D.OverlapCircle(rightWallcheck.position, WallCheckRadius, wallLayer);
}
it is an empty child object to the right of the player
I know its functioning properly because I set isTouchingWall to public so I can see it in the editor when running the game
You should get in the habit of relying more on Debug.Log and/or attaching a debugger for debugging your code
watching the inspector is sometimes convenient but it isn't a true test for how the code is behaving
Som,ething like:
if (BounceLeft())
{
wallJumpDirection = Vector2.right;
Debug.Log("Detected a wall to the left. Bouncing right");
}
else if (BounceRight())
{
wallJumpDirection = Vector2.left;
Debug.Log("Detected a wall to the right. Bouncing left");
}``` would be nice
And then logging:
Debug.Log($"Adding wall jump force: {wallJumpDirection * wallBounceForce}");```
would complete the picture and you can see if your logic is working properly.
Why is my zone trigger script not working? It doesn't have any errors.
because you're mixing up 2D and 3D?
looks good
assuming you tried to jump off a wall that's on the left of your player?
Yes
so then if you have a problem it's elsewhere
what's the issue exactly?
Also looks like it's definitely happening
which contradicts what you originally said "it never happens"
What made you say that?
Force is applied upwards correctly but player doesnt get pushed away from the wall
my original issue was different
maybe you aren't applying enough force?
How much mass does the player have and how big is it?
It was because the check for if the player was pressing space was also checking for isInAir which was redundant and preventing the code from running at all
Also you might already have a bunch of leftward velocity
so adding a force to the right might not be enough to cancel it out unless you add quite a lot
Setting wallbounceforce to a rediculous number doesnt do anything
TO make this more consistent you might consider just setting the verlocity directly like you are doing for the vertical
I would guess you have other code then interfering with the horizontal velocity
does your movement code perhaps set the horizontal velocity directly?
rb.linearVelocity = new Vector2(move * speed, rb.linearVelocity.y);
- switch your normal movement to be additive/use forces as well
- disable the normal movement code for some time after a side jump
something like one or both of those
Is there any way you could help me make the timer for the disable movement?
I dont understand how they work and all I can find online is for making level timers and stuff
could be done pretty easily with a coroutine, or just a simple float variable
timers are not complicated
I have 2 variables:
public bool movementDisabled = false;```
where did I put 3d? its supposed to be 2d
suppose the current time is 10, and I don't want to let the player move for 2 seconds
the condition for player movement is now just Time.time >= 12
OnTriggerEnter and OnTriggerExit are for 3D only
what should I write?
OnTriggerEnter2D(Collider2D other)
for example
there are 2D versions of all those things
oh got it
So I would need to set 1 variable to time of activation and another for time of completion like
Time.time >= activated + completed
If completed is how long the delay is, then yes!
You can also just store the time that movement will be allowed at again
moveDisableTime = Time.time + 2f;
Ohh I see now
Thats pretty cool
But wouldnt this be affected by framerate? Could I just use Deltatime.time in the same way?
i tested it out once it is pretty much the same. you can use delta time or Time.time
{
disableMovementStartTime = Time.time;
movementDisabled = true;
}```
and at the top of the update nethod:
```if (Time.time >= disableMovementStartTime + disableMovementTime)
{
movementDisabled = false;
}```
im having difficulty on returning an object from the explorer via script. I've tried some methods like GameObject.Find but they don't work 100% of the time
an object from the explorer via script
You mean the hierarchy?
I've tried some methods like GameObject.Find but they don't work 100% of the time
Find only works on active objects. It works 100% of the time on those
The best way to do this is a direct reference dragged and dropped in the inspector.
wdym active object and inspector?
Active objects are objects that are... active. I.e. they haven't been deactivated.
The inspector is something you should know about. If not you should go through the basic tutorials:
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
an audio source with an audio file inserted in it in the hierarchy is active or not?
GameObjects can be active or not active
not components
AudioSource is a component
it's irrelevant to our conversation
as is "with an audio file inserted in it"
To be perfectly honest is sounds to me like you're having some specific problem and you should ask about that problem
I suspect your GameObject.Find musings are not exactly related.
Show us what you're trying to do and what's going wrong
and we can help
my problem is dealing with unity engine. The coding itself is ok to me
What is your problem
explain it
and show what you tried
i've never heard about inspector
Then you know nothing about Unity basically
and idk what being active does to an object and how do I deactivate it
it's one of the most basic and fundamental parts of the editor
yes you are missing a large part of the basics of Unity
oh i know this thing but not the name
definitely listen to what praetor said. but for context, the inspector is a window (you can see a windows name on the slightly darker bar above all the UI). whether or not an object is active is the little tick in the image.
You can activate or deactivate objects either from the inspector or in code
(i was super late on that
)
i think my biggest issue is knowing the names from the stuff in unity. Y'see, I've migrated from roblox studio and there don't have a specific name for the inspector, it's just the properties tab
yes, there will be different names over there
So it does have a name, and you just said it
they're talking about the equivalent concept in Roblox Studio
Yes, "The properties tab"
so an object comes active by default when u create it, right?
That is true, yes.
https://docs.unity3d.com/Manual/working-with-gameobjects.html
This talks about the fundamentals of game objects and components
if AudioSource is a component, it's a component from what?
It's a component, which is a fundamental organizations comncept in Unity
Unity is made up of GameObjects with Components attached to them
just opened roblox studio to check. i think i see where you're confused. roblox studios doesn't actually have the ability to disable/enable objects (from what i can see from a glance atleast)
yea ik that, so what GameObject is AudioSource a component from?
You should read through this stuff and or follow the tutorials I lionked you earlier to learn all this stuff:
https://docs.unity3d.com/Manual/working-with-gameobjects.html
That question doesn't make any sense
AudioSource is a component that can be attached to any GameObject
a "cube" is a game object with:
- a MeshFilter, to hold a mesh
- a MeshRenderer, to draw the mesh
- a BoxCollider, to provide a physics shape
for example
You have a game object with:
- an AudioSource, to play sounds
GameObjects are generic. THey don't do anything themselves. There aren't different types of GameObject
That's one very important thing to grasp
there is only one type of GameObject - the differences come from which components are attached to them
Unreal, for example, doesn't do this. You create different kinds of objects
in Unity, everything is a GameObject
oh so the AudioSource can be the component from anything?
This sentence still doesn't make sense
"The component from anything"
any object(i assume)
"from" is the really confusing word here
AudioSource IS a component. It is not "from" anything. It can be attached to any GameObject
yes thats it
here's a random object from my game: a Spectator
it has three components attached to it
Objects are the things in the hiearchy and components are the things in the objects (in the inspector menu)
ok, i think i got what I was looking for
noticed another thing here. seems like, in roblox studios, the hierarchy and the project tab are the same thing (the explorer)
void DetermineRecoil()
{
transform.localPosition -= Vector3.forward * 0.1f;
if (randomizeRecoil)
{
float xRecoil = UnityEngine.Random.Range(-randomRecoilConstraints.x, randomRecoilConstraints.x);
float yRecoil = UnityEngine.Random.Range(-randomRecoilConstraints.y, randomRecoilConstraints.y);
Vector2 recoil = new Vector2(xRecoil, yRecoil);
_currentRotation += recoil;
}
else
{
if (recoilPattern == null || recoilPattern.Length == 0)
{
Debug.LogError("Recoil Pattern is null or empty!");
return;
}
int currentStep = clipSize + 1 - _currentAmmoInClip;
currentStep = Mathf.Clamp(currentStep, 0, recoilPattern.Length - 1);
_currentRotation += recoilPattern[currentStep];
}
}
IEnumerator ShootGun()
{
DetermineRecoil();
StartCoroutine(MuzzleFlash());
yield return new WaitForSeconds(fireRate);
_canShoot = true;
}
there are no errors but why does gun not have recoil
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
its not large
took up my whole monitor, seems large to me lol
what algorithm can i use for triangulation for a set o points in 3d that represents a surface?
it can fit on laptop screen
i got a smol screen 
i want to ask something for example rn i'm learning c# it tried learning c++ about 2 years back i've only done stuff in a console, and followed one of brackeys game tutorials also 2 years ago but at the end i had a game and still no idea how to make one. Now I'm learning c# and I'm wondering how do i just do stuff in unity like for example I have never done anything like move something in a console code i wrote, how do i even begin to for example move a sprite.
probably a #archived-code-general or #archived-code-advanced question. (although i've never messed with mesh stuff myself)
check out !learn pathways
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
search youtube tutorial for everything
better to start with a structured course
made an error here, project tab and hierarchy are the same thing. the inspector is called the properties tab in roblox studios
youtube is only good when you get enough experience to recognize any mistakes and improve on them
how's that working out for you?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
very good except for weapon sway and recoil
so, not well at all
when i asked how to make weapon sway
they told me i needed to separate movement from weapon
I want to change this to additively change my horizontal velocity so it can still be affected by other forces
rb.linearVelocity = new Vector2(move * speed, rb.linearVelocity.y);
but when I write rb.linearVelocity += new Vector2((move * speed) -= rb.linearVelocity.x, 0); it doesnt run
now i cant make weapon sway because weapon isnt player
cant have -=/+=/= after eachother
you'll have to do that on a seperate line
no, you cant make weapon sway because your yt tutorials have shown you what to do but you have not learned why or how
👍 thank you
yall complicate it even more
i learn more from yt than doing it by myself
yeah, take it from someone who learned the hard way (me
), youtube tutorials can help but you'll be spending ages trying to debug them if you dont have the proper knowledge on how to
in it's very nature, any dev work is complicated
@languid spire
look
this dude
learned for 2 years
2 years back*
also brackys, what did they learn really lol
to be fair, i spent 4-ish (maybe 5 now) years learning off youtube
still suck at programming
but atleast now i can code lol
a Transform value has the whole object as the value or only the name?
brackys made great unity tuts, even tho his coding skills were not perfect
i learned what i know from rlua
he just polished what other people already were doing, he just made worse by not explaining anything properly or just flat out made bad systems that can't possibly scale well
i would have left when i saw "private void"
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
u just have small screen
yup
so please use this
sani do you have a camera lerp , i think it might fix your weapon sway issue
Do you have an example of the surface you need to triangulate?
whats camera lerp
also i literally dont have script for weapon sway
@trail gulch Like can the points form a sphere or something or is it always somewhat planar?
i deleted those
in mouse settings
this appears to be a variable that isn't even used
I mean how are you actually using it
Seems like not at all
this is assigning to it, not using its value
Sure, I see you are modifying it, but not using it
I would expect you to use it to rotate your weapon transform or something
what do i need to do?
do something with the variable, presumably
float whatever = 123;
this does not do anything on its own
You are calculating a recoil value, but you aren't actually using it to do anything
guy in tutorial doesnt do it
perhaps you need to keep watching...or perhaps you missed a step
link the tutorial
Hey guys, this time around I wanted to show you all how to make a simple gun in Unity. This was done with a model that was made by JovisSE, special thanks to him for providing it! His info is below if you want to check out his video on how to make it. If you have any questions, feel free to leave them in the comments below. Any tips? Leave them ...
bro thats for sway and looking around
people here told me i should seperate looking around
from weapon
Yes, I think that's a good idea
I wouldn't want recoil to permanently change my view direction
(Some games do that)
i've shot a rifle before without flying into the ceiling, somehow
So I think you want to be doing something like this
- When you fire, add an offset to a "current recoil" variable
- Slowly return that variable to zero
- Add the "current recoil" variable to your "current rotation" variable when calculating a look direction
yea but i have completly different script for player movement so how am i supposed to use currentrotation
Maybe show your scripts
https://pastebin.com/CXgDW8ZC player movement
https://pastebin.com/ZPhzfKJL gun controller
Looking at the tutorial, looks like the GunController script should rotate the root which is the player..?
The guncontroller should only modify the gun's local rotation IMO
Not rotate the whole player
ah, that would make sense
whole player rotates in playermovement
when u look around does your arms detach and rotate around you?
So does your player rotation currently work ok?
Not sure why ApplyWeaponSway is in the player controller when you have a separate gun script. That's clearly where it belongs to
Oh so that's camera sway
i told chatgpt but i failed that day
You aren't applying the recoil anywhere. Try modifying transform.localRotation in the gun controller script (where the tutorial does this instead #💻┃code-beginner message)
You need to use _currentRotation to rotate the gun
(Also can we please stop using pastebin, there's no syntax highlighting and it has ads)
//Handle horizontal movement, disallow horizontal movement while movementDisabled variable == true
if ((Time.time >= disableMovementStartTime + disableMovementTime) && movementDisabled)
{
movementDisabled = false;
Debug.Log("movement enabled");
}
move = Input.GetAxis("Horizontal");
if (!movementDisabled && (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)))
{
rb.linearVelocity += new Vector2((move * speed) - rb.linearVelocity.x, 0);
}```
//Handle jumping, disable horizontal movement for a short period of time after bouncing off wall
if (isTouchingWall && isInAir)
{
//Wall jump logic: Add horizontal force away from the wall
Debug.Log("Wall jump");
disableMovement();
Vector2 wallJumpDirection = new Vector2(0, 0);
if (BounceLeft())
{
wallJumpDirection = Vector2.right;
Debug.Log("Detected a wall to the left. Bouncing right");
}
else if (BounceRight())
{
wallJumpDirection = Vector2.left;
Debug.Log("Detected a wall to the right. Bouncing left");
}
Debug.Log($"Adding wall jump force: {wallJumpDirection * wallBounceForce}");
rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpStrength);
rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse);
}```
//Starts a timer that disables horizontal movement
private void disableMovement()
{
Debug.Log("Movement disabled");
disableMovementStartTime = Time.time;
movementDisabled = true;
}```
Can someone please help me solve an issue where the player is able to wall jump without being pushed away if they hold the movement key in the direction of the wall?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
mb
i cant put it in here its too long
I mean use one of the links in the bot message above^ instead of pastebin
I have a vague idea of what you mean, but maybe show a video of the issue?
Sure 1 sec
And adding cs to the start of your inline code block will make it easier to read
so i need to have 2 looking around script?
This has nothing to do with "looking around"
I mean it does but that's not the thing you should do here
it made me look up and down
but not left and right
Idk what you did
Yeah deleting the code that you need help with is a great idea
i thought i needed to seperate looking around and gun
typically its the opposite (assuming you mean within the hierarchy). the gun model would typically be in front of the camera of the camera anyway, so it would have the same position and rotation as the camera (+ local position/rotation)
Player should not be able to climb the wall like that and should instead bounce off the wall when they try to jump on it like at the end
https://paste.ofcode.org/vhLnnyxkJdgdUU7QMCxsTj
relevant code is here
you didn't include the code for BounceLeft() and BounceRight() ?
{
return Physics2D.OverlapCircle(groundcheck.position, groundCheckRadius, groundLayer);
}
private bool BounceLeft()
{
return Physics2D.OverlapCircle(leftWallcheck.position, WallCheckRadius, wallLayer);
}
private bool BounceRight()
{
return Physics2D.OverlapCircle(rightWallcheck.position, WallCheckRadius, wallLayer);
}```
Where groundcheck and leftwallcheck/rightwallcheck are empty child objects of the character capsule
positioned to the left, right and bottom of it
Are you sure that this force is strong enough?cs rb.AddForce(wallJumpDirection * wallBounceForce, ForceMode2D.Impulse);
I went over the code and to me it seems OK
yes even setting wallBounceForce to something really high doesnt affect the issue
Does the "disable movement" part seem to work?
It does
I did some changes to the script (renamed it, for one) and now it runs Awake() but nothing in Start() or Update(). i checked with debug logs. tried restarting unity and delete and import back the script.
Is there an exception being thrown in Awake? Does the script get disabled?
the script is enabled
Is it disabled?
if there's an exception in Awake, it will get disabled by Unity automatically
how to check for exception?
Look in the console window
Can you show the logs?
so this is the first one. the script not working is PlayerUnit
Show the full error message
There are errors?
what script is that happening in, and on what line, etc.
But yeah it looks like there are errors
so that's the likely cause. If that's in Awake, it will disable the script
This is almost certianly a bad idea to do in Awake
referencing other singletons should happen only in Start or Update or something
because you don't know which Awake will run first
They can run in any order - .instance might not be ready yet.
i will remember how exactly the dependencies work in a moment but for now, the reason i put it in awake is the order of execution. i think of UIinventory and inventory
Order of execution is exactly why it won't work unless you're manually setting up the execution order in the Script Execution Order settings
which I wouldn't recommend
i want to trIangulaate the pink points
maybe i had modified the execution order and then it reset after i renamed the script, that's probably the reason
It's also a good reason why the SEO settings are not a great thing to rely on
It's better to design your code to work with any execution order if you can get away with it
i wouldnt need the first loop right?
Basically those settings are super invisible and as you just saw - fragile to certain classes of code modification
it would do the same thing without it
For what? What are you trying to do?
I guess you're saying because of GetComponentsInChildren?
change the shadow casting mode for all renderers in children
If you don't use the child, you probably do not.
its still going to find all the renderers
Yes especially with the way you wrote the GetComponentsInChildren, the outer loop is redundant
you will end up doing extra work this way
invisible dependencies are scary!
yeah
my game has some and it makes me unhappy
Delaunay triangulation would probably work here. Just have to project the vertices onto Vector2's first, unless you find a 3D implementation
for properties what is the c# naming conventions
like here
which one would be pascal case
i changed it to private btw
just realised
would the private one be camel or pascal?
according to Microsoft, you're meant to PascalCase any public member
I generally do not do this
i try to stick with it
I camelCase fields and PascalCase properties.
Hi everyone o/
So I'm working a game for a game jam, and I'm trying to make a subway surfer like game.
I'm trying to instantiate chunks, and sometimes (every checkpointChunkInterval chunks), I want to spawn a checkpointChunkPrefab that has an additional Checkpoint script attached to it.
I want to send down to the instantiated checkpoint a reference to some gameManager object.
I also want to refactor my code and extract the ChooseChunkToSpawn logic to some other method, but with my implementation, I lose the information about the type of the instantiated chunk. Is it a checkpoint? Who knows?!
Is there an elegant way to achieve my goal?
Should I change the way I do dependency injections ?
Also, I want to learn game dev. I know it's just a game jam and I shouldn't aim for an absolutely perfect code (it never is) but still
Hey, do anyone know how to set Collider's excludeLayers via script?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Collider-excludeLayers.html
Just set it to the LayerMask you want it to be
Hey im having a problem when i rightclick and try adding create c# script the create c# is missing
read the available options and use deductive reasoning to find the correct one
im unsure its my first time using unity for uni
Would Mono Script be the same thing?
Yes
It got renamed in Unity 6, yeah
There are a few other options in the "Scripting" category now
how do I set bloom via code
you have to do a TryGet on the Profile of the volume
sometimes its easier to just add another volume with the effects you want and just play with the volume weight to fade it in or out
I just wanna set the intensity
I listed two options lol
first one example
if(volume.profile.TryGet(out Bloom bloom)){
bloom.intensity.value = 0.2f;
}```
yep, went with Bloom tmp;
if (_globalVolume.profile.TryGet<Bloom>(out tmp))
{
_bloomComponent = tmp;
}
How do I change the shape and collider of a gameobject programatically? I want to allow the player to be able to crouch and turn the capsule into a circle
make reference to the collider component, and shrink the height property
might need to shift the center too
I wasnt a fan of how it makes the round parts look :(
you're resizing the entire thing not just the collider
How it looks and what it's colliders are need not be the same thing
scale it separately though. ideally not have the graphics / collider on the same object
maybe animate it /fade it to a circle sprite or something
So I should make the sprite on a separate, child object of the character?
Yeah its common to make graphics child object, so resizing doesn't effact the main root object (this could cause other issues with parenting / rotating)
Hmm good to know 👍 thank you
I'm really strugging, losing hairs from this.
JSMessage: {"MessageType":"joinInfo","Content":"{\"CharacterId\":\"62f991a3-64b6-4970-a248-a51da054a44b\",\"UserId\":\"1a45f5f3-15fe-455b-b162-b892056e7eb1\",\"AuthenticationToken\":\"5007fefa-a923-4a2b-9570-399e08ced3ee\",\"RoomInfo\":\"{\\n\\t\\\"image\\\": 0,\\n\\t\\\"id\\\": 2,\\n\\t\\\"scene\\\": \\\"default\\\",\\n\\t\\\"room\\\": \\\"Room\\\",\\n\\t\\\"name\\\": \\\"default\\\",\\n\\t\\\"public\\\": false,\\n\\t\\\"connect info\\\": {\\n\\t\\t\\\"tcp\\\": {\\n\\t\\t\\t\\\"host\\\": \\\"localhost\\\",\\n\\t\\t\\t\\\"port\\\": 8006\\n\\t\\t},\\n\\t\\t\\\"rudp\\\": {\\n\\t\\t\\t\\\"host\\\": \\\"localhost\\\",\\n\\t\\t\\t\\\"port\\\": 8006\\n\\t\\t}\\n\\t},\\n\\t\\\"public data\\\": null,\\n\\t\\\"tags\\\": [\\n\\t\\t\\\"default\\\"\\n\\t]\\n}\"}"}
WebGL.framework.js:2429 JsonSerializationException: Unable to find a constructor to use for type ClientCommon.Models.JSEventMessage. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'MessageType', line 1, position 15.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract objectContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, Newtonsoft.Json.Serialization.JsonProperty containerProperty, System.String id, System.Boolean& createdFromNonDefaultCreator) [0x00000] in <00000000000000000000000000000000>:0
This is an error I get from perfectly working json in the editor/windows builds.
When compiling for WebGL, it is giving me some problems.
my object is very simple.
public class JSEventMessage
{
public string MessageType;
public string Content;
public void SetContent<T>(T content)
{
if (content == null)
return;
Content = JsonConvert.SerializeObject(content);
}
public T GetContent<T>()
{
return JsonConvert.DeserializeObject<T>(Content);
}
// Serialize the EventMessage using JSON
public string Serialize()
{
return JsonConvert.SerializeObject(this);
}
// Deserialize a JSON string back into an EventMessage
public static JSEventMessage Deserialize(string json)
{
return JsonConvert.DeserializeObject<JSEventMessage>(json);
}
}```
Does anyone else have experience with a similar issue, or know of a work around?
It's telling you the exact way to fix it
Unable to find a constructor to use for type ClientCommon.Models.JSEventMessage. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute```
Thank you @wintry quarry
I added a default constructor, and recieved the same message.
The constructor might be getting stripped out by the compiler
This is a revision after many attempts to solve it over the better part of 8 hours.
interesting
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
can anyone explain whats wrong im new to coding and im following a video
https://paste.mod.gg/opxyuoqgzwhq/0 https://paste.mod.gg/mdbxacdjkgqd/1 hey guys, im running into this error on line 36 of the BallScript, and i have no idea what could be causing it? it works fine for Ball #1, but the subsequent 3 throw this error
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Hey, I have a current scene variable:
string currentScene = SceneManager.GetActiveScene().name;
But I added the Options scene additively, so it still detects the active scene as Game. How do I either
1. Change the active scene to Options temporarily
2. Make it check if Options exists instead of just the current scene
or 3. Remove Game scene but be able to return to it without losing any progress or anything in the Game scene
✅
-# ❌ Old Solution: #💻┃code-beginner message and below
-# ✅ Working Solution: #💻┃code-beginner message
Well first off in the video it's probably not Velocity it's velocity
Second - in Unity 6 it was renamed to linearVelocity
Pay closer attention to your videos.
thank you ill give that a go 🙂
You only linked something called AbilityManager. We need to see BallScript
oh didn't know this site had tabs,w eird
this blazebin thing is so confusing lol
Anyway like it says, it's on line 36:
Ability randomAbility = AbilityManager.Instance.PickRandomAbility();
the only thing on this line that could be null and cause that error is AbilityManager.Instance
which means AbilityManager.Instance is null
that means you don't have one in the scene
Oh one other problem is you're trying to access it from Awake in BallScript
Unity doesn't guarantee any execution order
so BallScript is probably running before AbilityManager.Instance has gotten a chance to get assigned
wait but thats so weird because it works for the first ball
As a rule of thumb if you plan to access other scripts, you should be using Start not Awake
so is it a case of, it slows down enough doing the stuff for ball 1 that it misses the timing for the other 3 balls?
Guys I need help, I'm trying to begin creating a weapon system. So far Ive created a model in blender with working animations, my camera sits just infront of the models eyes, perspective looks great. I now need to figure out how to lineup the weapons sight with the camera's center, and make the model somehow adjust to the gun position, as well as make the gun model fire a bullet in a path towards the center of the camera when hipfiring. Any tips?
No nothing to do with "slowing down" or the speed of your computer or anything. Unity is single threaded, only one thing happens at a time.
@wintry quarryThank you, that was my problem.
just an order of operations thing
I created a preserve attribute and added it to my classes, it's working fine.
awesome, I wasn't that confident it would work
ah i see, thank you! changing to start seems to have fixed it
Change the active scene to Options temporarily
With SceneManager.SetActiveScene
Make it check if Options exists instead of just the current scene
Withbool optionsSceneExists = SceneManager.GetScene("Options").isValid;
With the first one, does it automatically switch back once Options is removed?
I'm not sure what happens if you unload the active scene. Do try and let us know. I just think it's probably not a good idea
it seems undocumented
To be honest, I wouldn't use a separate scene just for options. Assuming it's just some ui.
https://discordapp.com/channels/489222168727519232/497874004401586176/1326004439034888213 Is this the right thread to ask this in?
not really. Seems like an #🔀┃art-asset-workflow problem?
kk
or just a general #💻┃unity-talk problem,
thankyou
Setactive scene doesn't seem to work, this is how i'm doing it:
SceneManager.LoadScene("Options");
SceneManager.SetActiveScene(SceneManager.GetSceneByName("Options"));
I think it may be becasue it tries to set the active scene before loading it fully. Is there a .then or something in C#? I'm more used with js
Might just go with the second thing mentioned anyways as it seems more efficient
LoadScene takes a whole frame to complete
it will not be ready on the next line of code
How would I wait for it to load it?
coroutine
update
Or maybe just set it to active in the start of an options script
anything you need to do to wait one frame
il;l do that
Did it, it works as expected and switches the active scene back to Game once Options is deleted. Thanks for the help.
If I write a script that makes my characters hands attach to a gun model while it's in animation, will that stop the animation?
Not sure, according to some sources it shouldn't but here's a reddit post with some things about animating weapons if that's what you need: https://www.reddit.com/r/Unity3D/comments/1c8czxn/correct_way_to_animate_with_weapons/
thankyou, im going to try it out
does anyone know why my jump mechanic isnt working?
Problem with old solution:
When the active scene is switched to Options, the Game scene resets along with everything in it. Solution to that problem:
Switch to instead of switching the active scene, just checking for Options existing instead. This can be done by using ```C#
bool optionsSceneExists = SceneManager.GetSceneByName("Options").IsValid();
as **PraetorBlue** suggested: [#💻┃code-beginner message](/guild/489222168727519232/channel/497874004401586176/)
**__NOTE:__ ** **Must be in a Method, doesn't work in the initializer MonoBehaviour or whatever.**
hi, how i can make that a proyectile detects when it touches a group of gameobjects?
i have the script for what happens when that happens, but not how i can make it happen
originally i made up the script for work for a single enemy, using it code, but i didnt fully like it, this is the script
using UnityEngine;
public class rifle_bullet_script : MonoBehaviour
{
public int riflebulletdamage = 5;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void OnTriggerEnter2D(Collider2D collision)
{
tuetue_script enemy = collision.GetComponent<tuetue_script>();
if (enemy);
{
enemy.TakeDamage(riflebulletdamage);
Destroy(gameObject);
}
}
}
when it touches a group of gameobjects
What do you need to happen when it touches the group?
In your code right now it's destroying itself as soon as it touches any object, so it's really only going to be able to touch as many objects as it can manage to touch in a single frame before it gets destroyed
note that private cannot be used in a method 😉
forgot to update that 👍
it damages the enemy
this is the enemy script
{
currenthealth -= Damage;
StartCoroutine(FlashWhite());
if (currenthealth <= 0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
private IEnumerator FlashWhite()
{
spriteRenderer.color = Color.white;
yield return new WaitForSeconds(0.2f);
spriteRenderer.color = ogColor;
}
}
```
ok so what's thje problem with it right now?
It will work for multiples
in theory everything works as desire, the issue here is, it only works for this enemy
except that it immediately destroys itself
the game will have a huge amount of different clases
i want this to work for a group of gameobjects, instead of just this fella
You're actually asking "how do I make this work for any type of enemy"?
I thought you were saying "How do I make this hit multiple enemies at once"
The best answer is to change this:
tuetue_script enemy = collision.GetComponent<tuetue_script>();
if (enemy);
{
enemy.TakeDamage(riflebulletdamage);
Destroy(gameObject);
}```
to this:
```cs
EnemyHealth enemy = collision.GetComponent<EnemyHealth>();
if (enemy)
{
enemy.TakeDamage(riflebulletdamage);
Destroy(gameObject);
}```
and just put EnemyHealth on all your different enemies
there's no reason you need to rewrite "having health and taking damage" for every different type of enemy
they will all do that the same way
hence just make a dedicated script for it and reuse it everywhere
Also note I removed the ; you put in your code before after the if statement. That was a bug and will cause errors @acoustic belfry
how do I stop an animation from effecting the models position
I don't have the root transform in the animation inspector
but wait, where i have to put it?
Move the visual/model aspect of the character to a child object
And have the animator only animate the child
Not the root
alright thanks
On all your enemies as I mentioned
but i mean, in what part of the script?
the bullet script or the enemies script?
o h
As I said
ah, ok, and what i put on it script?
I don't understand the question
im sorry i got lost
for now what i did was replace the previous script with the newer one, now what
You don't replace anything
The enemies would have both scripts on them
Remove all the health and damage logic from the original enemy script
Move it to the new script
And reuse that new script on all your enemies
i tested my script and the enemy health lows, it works, but it doesnt "shine", i mean, the sprite doesnt become fully white when its hit, what i did wrong? I set up the spriterendered to the sprite object, it should work
using System.Collections;
public class enemy_hurt_script : MonoBehaviour
{
public int maxhealth;
public int currenthealth;
public SpriteRenderer spriteRenderer;
private Color ogColor;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
currenthealth = maxhealth;
ogColor = spriteRenderer.color;
}
// Update is called once per frame
public void TakeDamage(int Damage)
{
currenthealth -= Damage;
StartCoroutine(FlashWhite());
if (currenthealth <= 0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
private IEnumerator FlashWhite()
{
spriteRenderer.color = Color.white;
yield return new WaitForSeconds(0.2f);
spriteRenderer.color = ogColor;
}
}
use links for entire classes. !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
btw sprite renderer.color is just a tint for the original sprite, its not going to make the sprite full white
that's not really a question
something can be easily googled
Im not understandin it though
link?
also this is probably better for #archived-lighting instead of code
#💻┃code-beginner message
yes large code should be posted using code paste sites and share the link instead
its difficult to read especially on mobile through discord
did you also check out about what I said in the flashing sprite issue?
How to init script in the first Scene? Should i place script in mainMenu?
(CursorManager script with 1 instance for all scenes)
That it actually doesnt do a thing cuz is more like a tint?
correct
Ok i'm a complete beginner coming from roblox
I'm having a issue where the character controller .IsGrounded just always returns false no matter what
void Update()
{
characterController.SimpleMove(Vector3.down * gravityValue * Time.deltaTime);
Debug.Log(characterController.isGrounded);
if (Input.GetKeyDown(KeyCode.Space) && characterController.isGrounded)
{
characterController.Move(new Vector3(0, jumpHeight, 0));
}
}```
And yes i'm on the ground lol
I checked the docs for isGrounded and it was the least helpful doc that has ever documented so I had to ask here
because isGrounded is generally pretty trash
Oh so should I just raycast?
Normally you make your own
every tutorial ever I saw just used isgrounded
yeah raycast is good but too thin imo
I use an overlap or spherecast, depending if i need the hitinfo
whats the solution then? I'm not really sure what unity has yet tho I assume if roblox has it unity probably does too
oh that makes sense
So I should just use a rigidbody and not a character controller?
isGrounded works on when the CC was last move, but idk barely ever used SImpleMove
or is it just the isgrounded thats trash
I'd just recommend not using CharacterController
CharacterController is okay but with Move you have to make your own gravity and other forces
yeah but I also don't have to code a lot of other stuff to be fair lol
but yeah I can do that
true.. but after a min u learn other cool programming things..
I'll research the other stuff thanks
Riidbody is good too but annoying sometimes to fully control it
I know how to do the rigid body stuff I just saw everyone used that tutorial wise
I've been coding for 3 years now in roblox which I'm so sick of roblox so i'm trying out unity lol
gravity, knockback, magnitudes.. normalizing.. lerping etc etc
Kinematic helps getting more precise rigidbody movement but it doesn't give you collisions if you knock into walls/obs
requires you to use something like rb.SweepTest
I have this so far for my rigidbody code
using System;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.TextCore.Text;
public class PlayerMovment : MonoBehaviour
{
public float speed = 50.5f;
public float jumpHeight = 10f;
public Rigidbody rigidBody;
bool isGrounded = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
rigidBody.linearVelocity = new Vector3(horizontal * speed, rigidBody.linearVelocity.y, vertical * speed);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
rigidBody.linearVelocity = new Vector3(rigidBody.linearVelocity.x, jumpHeight, rigidBody.linearVelocity.z);
}
}
void OnCollisionStay(Collision collision)
{
ContactPoint point = collision.GetContact(0);
Debug.Log(point.normal.y);
if (point.normal.y >= .8) {
isGrounded = true;
} else {
isGrounded = false;
}
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}
But I'm not done
I'm just messing around i'm very brain rotted by roblox
reverse engineer this asset
I would still not rely on OnCollisionStay for grounding
yeah it was just the only idea I had i legit just started unity today
I started 3 hours ago lol
too many possiblities to mess up or mis-detect
you good lol
if you want a quick "dirty" solution use the KCC or the unity Starter Assets controllers
I tried godot but going from roblox to godot broke me so I decided unity lol
lol.. i feel like unity gonna give equal results
perhaps..
unity has soo many things that godot still catching up to
plus godot is a lot more simplified and lightweight so I gotta learn how to do a lot more there and I want my hand held just a little lmao
godot ui isnt that bad.. i personally enjoy it
Godot c# is just not polished enough for me and missing so many things
plus godot 4 is so new not as many docs and tutorials
ya, there ya go ^
pythony like syntax grosses me lol
same same..
I mean I coded lua so nothing is that bad to me LMAO
discord bot building flashbacks.. terrifying
I love me some lua
c# is fairly easy and nice
last time i used LUA was making mods for Gmod
hmm.. navmeshsurface seems to be tucked in here now
fun times
i thought it was under using UnityEngine.AI;
its been out for a while no?
Oh that was when it came from Github
ya, i refused to use the github link
1.0 was released around 2022 came out i think
Hey yall. Having some trouble, as every time I attempt to destroy the children in my object, it still says I have all children there while I don’t. I don’t know if it’s my code or anything, but it’s breaking some parts of my game. Sorry for the horrible quality, I’m on a roadtrip and I can’t get WiFi on my computer to text it here
never done that yet... lol i feel better installing via the registry
thats when old baking modes were discarded
So for overlap I assume I just make a non collidable part of my character and check if something collides?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
just exclude the player layer from the Overlap
use if you go for overlap or cast use the non-alloc version
oh i jsut finished the sentence
😂 yall are okay. Gonna take me a minute to copy, it’s def difficult to retype code with a phone.
how is your phone connected?
nah.. if its an android it simple..
I assume character controllers are newer to unity? or are they just buggy since forever
click hold.. drag
i usually make a hotspot with my phone
thats the only way..
CC have been since Unity had PhysX they are a PhysX controller
oh why are they so buggy then? Not in the priority list of fixing?
Idk grounded seems to be fucked and other people I asked just said it had a lot of bugs and wasn't worth it
my CC is smooth as butter
but they were also like ex unity devs so
like I said most people dont use the SimpleMove method and isGrounded is not very reliable like a physics query would
SimpleMove vs Move
yeah ik meant the difference
oh look at the docs
kk
SimpleMove tries to apply gravity* speed n whatnot