#💻┃code-beginner
1 messages · Page 146 of 1
none of those are the log you just wrote
that means your raycast is not hitting at all
Is that all of the logs?
or the code is not running at all
yup
Then we have definitely shown that your raycast is not hitting anything at all
Meaning there is no object within 1 unit of the front of shootingPoint with a collider
raycast default distance is infinity
Ah, right
The balls are deleted after 5 seconds
DrawRay is the one where the distance is baked into the direction
the balls are completely irrelevant, you're using a raycast
So, either CanShoot() is never true, or the raycast never hits anything because there's no colliders in front of shootingPoint
If the balls exist at all then the raycast is hitting something and you'd get the log
https://gdl.space/zaliqugoqa.cs
this is the code
so either you didn't save, something else is spawning them, or the balls are not the bullets and you've just given me a random non-sequitur
They exist, but I did something that a bullet can't pass through something "solid" is this related?
The actual spawned bullet object has nothing to do with your raycast which is what calls the damage function on the enemy
so it doesn't matter what they collide with
ok
Since the log is before the Instantiate line, if that line is running at all then the log is going to the console
If it's not, then you probably didn't save the script before starting the game
I could swear I saved it!
Show the inspector of PlayerBody
So then your code is doing exactly what it's supposed to be doing.
The ray didn't hit an enemy so it doesn't damage the enemy
i know
so what to do?
And I forgot to say thank you, it goes without saying that you help me
Is the ray supposed to be hitting PlayerBody
no.
It's literally the player
You either want to use a layermask to disclude the player, or have the raycast start in FRONT of the player instead of inside it
Is it better to do damage in whole number increments or float decimal increments?
Whatever makes sense for your game
Do you want damage to be in whole number increments or float decimal increments?
I'm not yet sure, I plan to show health as X/100 but having defense on the character could divide damage into decimals
Although I'm kinda thinking that having defense divide the damage doesn't make much sense
As said before it depends on the game but generally I feel like most games would round it to a full number (visually to the player not in the code)
Its an arcade game so honestly it should probably be whole numbers and the defense should just directly subtract from the damage
Thanks 😂
So how do I convert integers to strings to show tye number in the text?
imagine if you typed the same thing into google
I believe you can do something like "Health: " + yourIntHere
You can use $ sure
Something similar tho
but how you wrote formatting is wrong :
$""
You still need the quotation marks
You are doing "string interpolation" which you can google for more
Alr, thanks
string text = $" health : {healthVar}"```
huh, never seen that before
google "String interpolation"
what are quarterions
rotations
Just a variable that holds a rotation
4 values as a struct.
x y z w
Not 4 axes
3 axes represented by 4 VALUES
You don't really work with quaternions directly
Stop, w was literally a question
you don't ever need to look at or care about those 4 numbers
just think about the whole thing as an opaque box that holds a rotation
0.0 don't speak the forbidden language more
okay- uh
if I just want to have a 2Dgameobject turn to face a vector2
can I use quarterion.slerp?
myObject.right = direction;
you can Slerp the direction vector
right?
yes because those are spammy and unecessary
all 4 numbers make a rotation
none of them are rotations around axes. Again, don't worry about the actual 4 numbers unless you want to spend 3 hours doing math lectures. Just think of the whole thing as a variable that represents a rotation, that's it.
As long as you use the stuff in the Quaternion struct, and not interpret the XYZW as individual angles in degrees, you're fine
Xyz represents a direction, w is the amount of twist around that direction
^ Unity has Quaternion methods in it so you only need to work with Euler angles
I'll pretend they don't exist till I need them ig lol
You won't need them. Ever
quaternion.euler and quaternion.identity are the simple ones you'll be using most likley
just worry about euler angles
I've used quaternion once already though
Not directly
You may have BUILT one from Eulers?
Not the same thing at all
you need quaternions
you just don't need to fiddle with their values
just like you don't fiddle with a Transform's 4x4 matrix
Ok fair fair haha
what does .right mean int this case?
I don't mess with the Matrix4x4. I mess with position, rotation, and scale.
the right direction of the object
the red arrow in scene view
GameObject laser = (GameObject)Instantiate(CirclePrefab, firePoint.position /*+ new Vector3(0.0f, 0.0f, 0)*/, itGuy.rotation /*Quaternion.identity*/);i was using it in two projects, what do you mean building it?
That question doesn't make sense to me.
A direction is a Vector3.
transform.right will be a Vector3 with a length of 1.
stopped using it bc i didnt understand em
Aeth was talking about trying to manipulate the underlying data that a Quaternion is made from.
Don't worry about that at all.
Ah
It's just a common error to mistake it for euler angles
I was talking about w specifically, which you were asking for
What's an euler angle?
transform.rotation.x; // not x rotation
transform.rotation.y; // not y rotation
transform.rotation.z; // not z rotation
transform.rotation.w; // ???
Euler angles are the X/Y/Z rotations you're more familiar with
It's what you see in the inspector
They produce a rotation by spinning around three different axes.
euler angles are a way to express rotation via angles around the x y and z axis
They have worse mathematical properties than quaternions, which is why Unity uses quaternions at all
The rotation in the inspector is local euler angles
Those 🤦♂️
(which is transform.localEulerAngles ! )
Interesting, what would that actually do though?
well, it gives you the local euler angles of the transform
the rotation you see in the inspector, as digi said
similar to transform.localPosition and transform.localScale
those are what the inspector shows you
it doesn't do anything, it's just information
Holy crap, so I can save that in a variable to reuse later?
well, sure, if you needed that
It... it displays the value of localEulerAngles
sure but you could also save the more effective thing which is the rotation or localRotation Quaternion
welcome to programming
what transform direction is the green line in the scene view? forward?
up
blue is forward
even in 2d view?
yes
your forward here is transform.up
Yeah, it's a little annoying for 2D
you have to decide which direction is going to be your "2d forward"
whats the inverse?
-transform.up
oh
there is no transform.down, alas
negative up
Unity 6 feature? 🥹
they do it for Vector3 but got lazy with transform
Is this what your IDE looks like, or is this a screenshot of a website 🤔
IDE?
!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
• Other/None
the thing you type code in
then you need to configure it
doubt
does it really autocomplete? If it's not underlining errors in red it needs to be configured
it is underlining errors
just not autocompletting now I assume
its 3am anyway and I got other work to do
Completion is context-aware
If you're typing stuff outside of a class, you won't get many suggestions
so is just a shitty theme then here ? why its all white lol
Normal if all of these are fields/properties
they are all variables
direction and directionNormalized should be local variables. They'll be light blue if that's the case
I would hate to use a color scheme that bad lol
It's the default for VS
But a rare sight, since you use more methods and locals in methods
props usually was bolded for me at least
Then you modified it in the settings
I watch a youtuber who has Rider set to the default VS color scheme and it makes me angry every time I see it lol
not being able to tell a value type from a reference type 😞
properties same color as local variables 😞
Correctly naming things also helps in distinguishing what is what, but oh well this is Unity, can't have everything
That was VS2017's (and before) theme. Now these can be differentiated
Does Rider let you set a color for a file tab?
prop local and method parama
Don't think so; it lets you set colors and icons for projects, but files, not that I'm aware of
looks like vs2022 lets you do that finally
is there a way to write "or" in if statements like
if ( bool == true "or" bool2 == false)
{
}
have you googled it
Yes use the or operator
nvm I have googled it
Im having an issue with using a variable from another text, for some reason i can test integars but cant seem to use strings
wait...
its not in update... mb
ok im still having the issue and its now trying to create a tupple
void Update() { if (script.speed == 6) { Debug.Log("Speedboost active"); } healthtext = script.playerhealth; }
its properly checks the integer so im not sure why a string wouldnt work similarly
public string playerhealth = ($"{health}"); unless this is just formatted wrong?
that is 100% not formatted correctly
first of all, that would only create the string at the time the object is instantiated. so the value won't update. and then you also have the () around it which is likely what is causing your error
is this only for floats?
no, you can use string interpolation anywhere. but strings are immutable so this won't update with the health variable
but also why is that a string?
public string playerhealth = $"{health}";
why is what a string?
why is playerhealth a string
health is an integer, dont i need a string to input into a text?
well you could use string interpolation at the time you need to create the string. or you can call ToString on any object (including ints)
but it seriously seems like you have a tenuous (at best) grasp of c# and i would suggest going through some beginner c# courses to learn wtf you are doing
I mean, it WILL work if the syntax is right
You had parentheses around the string though, did you do the same with ToString() ?
public string playerhealth = health.ToString();/*$"{health}";*/
im doing it in update
so you remember how i just said that strings are immutable so they won't be updated along with your health variable?
You can't have "public" in Update
If that line is in update then you will need to fix that compile error
so i need to initialize it before i can use it?
well before i can update it?
Why do you even have a string variable at all
so that i can use this textmesh thing
still learning how textmesh pro works but i assume it still needs a string
Just pass health in, no need to make a separate string variable
Just like legacy text.
Just use the health variable
integers work in the texts?
.ToString()
Yes but also you've been told like nine different ways to convert it into a string when you need it
again, tostring did not work unless you mean text= variable.ToString();
ToString absolutely works
Again, you did it in the initializer, which is why it didn't work
You do it when setting the text value.
Not before
fixing now btw, i keep getting sidetracked
well now its trying to say im converting a string to textmesh pro...
but thanks for the first fix
textObject.text =
yep, forgot .text
You have to access the text property before setting
using UnityEngine;
public class AlienMovement : MonoBehaviour
{
[SerializeField]
private float screenBorder = 30;
public float moveSpeed = 1.0f;
public Rigidbody2D rb;
public float maxVariability = 4.0f;
public float minVariability = -4.0f;
private Camera camera1;
private void Start()
{
camera1 = Camera.main;
// Generate a random variability within the specified range
float variability = Random.Range(minVariability, maxVariability);
// Set the velocity based on variability
rb.velocity = new Vector2(variability, 0) * moveSpeed;
}
private void FixedUpdate()
{
reverseVelocity();
}
/*
* Checks if the Alien is near the border
* Changes the direction to the opposite way if the Alien hits the border
*/
private void reverseVelocity()
{
Vector2 screenPosition = camera1.WorldToScreenPoint(rb.position);
if ((screenPosition.x < screenBorder) || (screenPosition.x > camera1.pixelWidth - screenBorder))
{
//Reverses the direction
rb.velocity = new Vector2(-rb.velocity.x, 0);
}
}
}
I'm trying to reverse the velocity of the gameobject after it touches the border of the screen. However, the gameobject does reverse in the unity editor but stays at the border after being built.
you do know you have to actually describe what isn't working for anyone to know how to help you, right?
i was going to just say Interesting.. :0
instead of reversing
may have something to do with ur hard coded screenBorder? edit: then again idk, maybe build a development build with debugs in ur methods
hello
uhh, can you specify how I would the get the actual screenborder value?
isnt there a screenwidth or something?
Let me try that out rq
setting
screenBorder = Screen.Width just makes the gameobject stay in place
yeah... everything that i had learned a few months ago was either incorrect or just outdated so im in the process of fixing what i had in my last two projects and learning new things that ive never used before
up until last week, i didnt even know text mesh pro was a thing and tried to argue why i used legacy instead of trying it🙄
i wasn't even referring to unity stuff though. i was referring to the fundamentals of c# which includes things like accessing variables and methods from other objects, converting things to strings, and syntax
yeah, i just learned how to access other scripts today, my last two projects had most of the code in a single c# file
didnt end well
i may have mistaken what ur trying to do. i was just saying by using screewidth u can calculate when u reach each side something like this came to mind ```cs
void Update()
{
CheckScreenEdges();
}
void CheckScreenEdges()
{
Vector2 screenPosition = mainCamera.WorldToScreenPoint(transform.position);
if (screenPosition.x >= screenWidth)
{
rb.velocity = new Vector2(-moveSpeed, 0);
}
else if (screenPosition.x <= 0)
{
rb.velocity = new Vector2(moveSpeed, 0);
}
}```
not sure why it would work in the editor but not in build
Hmm, alright
If I have a DialogueEvent that extends from the abstract class Event but has a field (string Line) that is not in Event, how I access this field from a List of type Event? I tried casting to DialogueEvent but that did not seem to work.
idk if this is the right thing, but is it possible to have an "if" with 2 variables?
so
if(bool1 and bool2)
{
}
one could google "C# and"
Google logical operator
(it's &&)
I think casting should work.. are you sure you were using the casted variable I think like this.. ((DialogueEvent)eventList[0])).Line
you're missing some parentheses to make it work
yeah you aren't useingthe casted variable
((DialogueLine)events[i]).sLine
((DialogueEvent)eventList[0])).Line
or instead of using that terrible sType variable, you can instead use the is operator to type test it and put it into a local variable all at the same time
I have had that problem many times
if(events[i] is DialogeLine dialogueLine)
oh! that's even better
does transform worth referencing if i already have other component and can just .transform
not really. it's a micro optimization at best so just accessing the component reference's transform property is perfectly fine in nearly all cases
can anybody help me out
Maybe. No one can say without hearing the issue
i got this script from a tutorial but i dont know why im not jumping ill put the script in rn
how do import 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.
Use links if it's longer 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.
Nah, that is the instruction to bring up the bot. You need to read those instructions
im so confused sorry
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
thats it
Hmm, the Move call is before you set the velocityY value for jump. Is that how it is in the tutorial?
time to start then
yep
do want the tutorial?
Nah, I don't have time to really look through it.
I would learn about Debug.Log() and place that in the UpdateMove method to check things like isGrounded and the values passed into Move
Might want to just pause and check out !learn though
huh
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If you're following a tutorial and something doesn't work, go over everything again. 99% chance that you missed something.
In my game, I'm using ScriptableObjects to create projectiles, which has worked well so far. (For example, each projectile accesses a scriptableobject to get its sprite, properties, etc.) But I want to be able to add a ParticleSystem component to them at runtime, but I don't see a way to store that using a ScriptableObject
Should I just be using prefabs or is there a way to make this work?
you can store particle system assets onto the SO
wait maybe im thinking of vfx graph sec
I can technically generate a field for one, but there's no way to populate it with a stored asset since a ParticleSystem is a component that has to be attached to an object
ah that sucks
it worked thank you
so much
I have some steep stairs that I need my character to run down from the top instead of flying off the top like the General Lee
(The car from Dukes of Hazard, not the...you guys get it)
I need to make a system to constrain her on the way down while she is in the Move state
You need to apply force in the direction of the slope, rather than applying it directly forward
by that logic, I should turn off gravity too
I'll delete my musings for this situation there
It's fine, just a future point
so right now she can climb the stairs and stay stationary because I am toggling player.rigidBody.isKinematic on Enter/Exit of Idle state
you are proposing (if I understand) that in the Move state, when I am slopeDetected(), I manually override the velocity vector?
That sounds messy in general
I would just add the force in the slope direction regardless of how steep it is. Even on flat ground, you're on a slope.
currently i need to reassign shader and reconfigure properties of a material, due to our project architecture and approach, we cannot pre-assign the material/shader to the gameobject , in order to get things done , i need surface type to set to trasparent
so, my question is, what are the shader keyword for "surface type"
somehow this is not working, surface type hasnt changed at all
are you talking perpendicular to the stair surface or parallel to the stairs surface?
Also, does one of the basic C# libraries have a constant sqrt(2) predefined?
Parallel to the surface of the ground below the player
I assume that by "Force" you mean "velocity"?
b.c. I don't know where I can apply a force on the rb
You can use AddForce on a rigidbody, or you can modify the velocity directly
if you have a dynamic RB, I strongly recommend against directly modifying velocity until you have more experience
because directly modifying velocity quickly leads to spaghetti code when multiple scripts try to do the same thing
im not sure what is wrong with the class anyone know?
https://unity.huh.how/script-loading-issues try these solutions
I need to get the dot product of a raycast with a collider's normal, does anyone know how to get that?
What are you struggling with? You just use the dot product on both of those variables, the hit has the normal, and the ray has the direction
instantly found a solution thanks so much
oh, maybe I am overcomplicating
I just want to check if a raycast is hitting normal or not
Normal is not a point
I know, I didn't say it was a point
I want to turn something on or off depending on whether my slopeCheck raycast is intersecting normal to a surface or not
(in 2D)
still not sure what the difficulty is, just get the dot product and compare it to whatever bias you want
dot product of what and what else though
I think he doesnt know what normal is
I have a bachelors degree in Math, I know what a normal vector is
You just use the dot product on both of those variables, the hit has the normal, and the ray has the direction
What are you struggling with
🧐
the stairs problem ^ a few posts up
The normal in unity is exactly what you learn in uni
(Get the normal of the ground below the player, and use the cross product to get the slope)
Raycast intersects with triangular mesh at point and normal tells you what is the direction of the triangle facing to
I'm not confused about what it is
Great, then what is confusing you? Because I've explained what two things you care to dot product, the exact same two things you mentioned right at the start
Google raycast hit info and read the properties
ok, I'm going to do that
aw i love interact systems
Ok, I don't want to do a second raycast to get the normal when I am already doing that to get a bool
I want to keep the raycast2D I am already doing as is and access its normal
I know how to do that
but right now it is being casted as a bool per the tutorial
Raycast has overloaded method to get back the hit info
how do I get the true/false info from a raycast2D?
because I need to revise my existing code to only access that part elsewhere
if I keep it as a Raycast
Just google or your ide will tell you how the overload methods look like (signatures)
yes, I was just looking at it but I don't see a bool
Pretty sure you just use it in an if statement, or if that doesn't work just compare its collider with null
Your ide should show you
public return_type same_method()
public other_return_type same_method(int some_int)
ok I got it now
i can't drag sound audio mp3 into the unity why?
public AudioSource doorSound;
the struct
An AudioSource is a component
https://paste.ofcode.org/35aY9ACXbyXSUuafN5x2FMM
This code is supposed to change a shader material values over time and it works for the mesh renderer component but i also want to use it on a skinned mesh renderer and don't know how to do it. Can someone tell me how you can do this.
Are you looking for AudioClip?
i need if i open door i got sound of door
No, you should look at the method signatures of raycast
i can't drag my sound door in my unity idk why
They found what they were looking for, you're not thinking of the same thing. Physics2D doesn't have an out the same way Physics does
Forgot, mb
hey. any help?
I explained your issue.
An AudioSource is a component, are you looking for AudioClip?
yes
:D
public override void Update()
{
base.Update();
player.SetVelocity(player.moveSpeed * xInput, rb.velocity.y);
if (xInput != 0 && player.IsSlopeDetected() && player.IsSlopeDetected().normal != Vector2.up)
{
player.rb.velocity = new Vector2(xInput, xInput) * player.moveSpeed / Entity.SQRT_2;
}
}
PERFECT!
All I had to do was let a Physics2D.Raycast() method in my IsSlopeDetected() method return the RaycastHit2D type (instead of bool ,which is what the tutorial had me do before). I didn't have to change anything I already wrote because it reads implicitly as a bool.
Then I just accessed the normal property.
I still have the rigid body set to isKinematic when in idle state on stairs so it doesn't slip
You can store the hit info in some variable
oh you are right
I am calling it again
Im new to unity, can anybody help me fix these errors?
I'll do that
Don't cross-post
sorry
some if statements with a handful of prefabs
Hi, Im new to Unity and I am creating a basic cookie clicker game for a school project. My cookie counter is set to 0 and words perfectly fine, but when I click the cookie it does not register the clicks, and the counter does not increase either when clicking. Any help? >:D Please
!code
but also what is calling OnCookieClicked
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The OnCookieClicked method, in turn, calls another method named IncreaseCookie
public void OnCookieClicked()
{
IncreaseCookie();
}
public void IncreaseCookie()
{
CurrentCookieCount += 1 + CookiesPerClickUpgrade;
UpdateCookiesPerSecondUI();
}
that does not answer the question i asked
sorry english isnt my first language, what is your question?
what is calling your OnCookieClicked method
sorry, what do you mean by calling?
wdym? you just answered that OnCookieClicked calls IncreaseCookie. so clearly you know what calling a method is, right? so what calls OnCookieClicked
I have no idea, I chat gpted

it is against server rules to ask for help with AI generated code.
This code isnt ai generated
then what calls OnCookieClicked
I have no idea
the answer is probably nothing which would be the root of your issue. but you seriously need to go learn the basics. there are beginner courses pinned in this channel to help you get started
A method that calls another method that has two lines one of which is another method call does look like something a gpt will spew out 🤣
bro I have no idea want im doing I just want the damn cookie to click and number go up so I can get a decent grade for this assignment
what if ur teacher finds out its ai code
bro the code isnt ai
Well maybe you should have listened more in class?
bro we didnt even learn unity in class lock in lil bro
Then why is your assignment in Unity ?
if u just need a grade just follow a tutorial and get it done in like a day or two
Just make the cookie a UI button and slap your OnCookieClicked on there, bingo bango A+
so ummm guys, how to make the cookie click
so did you think i was asking what called OnCookieClicked for shits and giggles? because the answer is obviously that you need to call that somewhere
ummmm no swearing pls
ok but I still dont understand what you are saying
something needs to call OnCookieClicked or else it won't be called
and what happens when OnCookieClicked is not called?
Called = Activated. Something, somewhere, in code or a UI button element, ANYTHING, needs to make that code run
Because right now it's just a block of text that isn't doing anything
THANk you I was waiting for that
Until something CALLS it, and tells it to do what it's holding
does this not call it?
again, there are beginner c# courses pinned in this channel
This is a one time thing, I just need a simple clicker game to be created
I am sorry for this inconvience to you guys though
lol sure kid. but you likely won't be getting answers from most of the people who usually help around here if you aren't putting in the effort to learn wtf you are doing
I created a whole code, with all my effort? Although I may be uneducated im still trying my best
Slap a Debug.Log in some functions and see what is getting called and what isn't
Sitting around using chatgpt isnt effort, you need to go through the actual beginner steps and learn. If you're unsure how to use Debug.Log, as suggested to use above, then that's what you should be researching
bro this isnt chatgpt 😢
look into how to log to the console and log the method you call with the button
from there then you can probably get more help
I’m using the console and debug log to find what isn’t connecting
How to I move on from there
First thing you should do is check if the method is being called to confirm it's at least being called
from there I'd start logging your counter each time you add a value to it
Hey guys, i have a project due soon and i've been trying to figure out why my player keeps falling through the ground
Learn how to move and jump in Unity!
Source code: https://gist.github.com/bendux/5fab0c176855d4e37bf6a38bb071b4a4
SOCIAL
Discord: https://discord.gg/5anyX69wwu
itch.io: https://bendux.itch.io/
Twitter: https://twitter.com/bendux_studios
SUPPORT
Buy Me a Coffee: https://www.buymeacoffee.com/bendux
MUSIC
By the Fireplace by TrackTribe
H...
i followed this tutorial
i'm really new to unity btw
does your character have a collider and the platform/ground
Keep in mind that a rigidbody isn't a collider, you would need both
only the character has a collider
and a rigidbody
you need a collider on the platform
ok ty
how do i allign it to perfectly shape the tile
platform
the three dots next to edit collider click on it and adjust the collider
The platforms are on a tilemap, so you could use a tilemap collider
if i'm trying to make a one way platform can it still work with a tilemap collider?
can anyone help me with this, im trying to make it so the camera can move 360 around the character but it seems to get stuck like it hits a wall at a certain point
i have a video if you need to watch
obligatory: use cinemachine
@slender nymph You doubted me you pussy bitchass I'm the king lil bro dont ever try to not help me again
will look into that thanks
ummm okay man, dude was just trying to help
umm okay man, fuck that guy
he still tied to help when you were being rude
Good way to get banned, I guess 
or just blocked by anyone who actually helps in this server.
ummm actually there is more to life than unity
!warn 643616849296097290 no memes or insults. Next time follow a tutorial or some learning resources and you'll have saved the hours it took you.
nt2heat has been warned.
actually
is there a reason for why my one way platforms aren't working?
i can't jump through from the bottom
try making the surface arc 179
didn't work
btw this is how it looks like
i remember havin a problem like this but i forgot how i dealt with it lol
Have you assigned anything to inventory?
yes
Show the full error including the stack trace
NullReferenceException: Object reference not set to an instance of an object
UIInventory.Start () (at Assets/_Scripts/UI/UIInventory.cs:11)
the event still works though
im just getting that error
And line 11 is that line in Start?
Okay then you have another copy of the component in the scene where inventory was not assigned
See if same script on multiple gameobjects
oh shit thanks
feel dumb now
i got a question tho with events, what would the difference between "public Action OnItemUpdated" be vs "public event Action OnItemsUpdated" and what does assigning it to delegate {} do? just ensure its not null?
The event keyword makes it impossible to invoke the event from any other type of object. And it is not necessary to assign the empty delegate to it, you could just null check it (which you should be doing anyway)
so ?.Invoke to null check
Yes
what do you mean "any other type of object"
the event keyword also only exposes add/remove, meaning other scripts cannot just assign your delegate to null (removing all subscribers)
other scripts cannot invoke the event
hi
can i get some help for something
how do i instantiate a prefab so that it is always five units away from the player, but in the direction that the player is facing
get the player's position, add 5 units on your preferred axis and use that Vector3 as the position you pass for Instantiate. then get the direction from that position to the player to use for the direction it faces
this is a code channel
oh crap my bad
wouldnt that only instantiate along whatever axis i choose though
yes, if that is not what you want then you need to be specific
the direction the player is facing is gonna be transform.forward
Do unity support rust language?
ok thanks
no. unity uses c# for its scripting language

Nooo
Look like i have to other game engine
hello, so im trying to add multiple characters to my game rn, and ive set 2 buttons, one that would start the game with 1 character and a difretn button that would start the game with a difrent character, how would i make it so when the player clicks a button the sprite of the character and the move animation of the character changes to a difrent sprite and movement animation?
would i have to make a completely new scene with a difrent character prefab?
i would make another character prefab as a prefab variant. but you don't need a copy of the scene for that. just have some object that can be used in both scenes like a DDOL object, scriptable object, or static variable that tells your gameplay scene which player prefab to spawn
Good luck with that, no big game engine uses Rust as its scripting language.
Spain without s
a DDOL object?
DontDestroyOnLoad
ah i see
Question. How do I make it so when the game starts a amount of objects are disabled
put those objects into a list/array. on Start or Awake: optionally shuffle said list/array, get random number from 0 to the collection's length or max disabled objects, iterate through the collection and if the index is smaller than the number generated disable that object
i got a problem
I switched computer, my Unity Project is on a USB key.
I did this a ton of times the past months, no issues.
But now I got a bunch of errors, related to some missing references of assemblies.
when opening the error in VS nothing shows
is Unity bugging or something ?
well you could try c++ programming in unreal
library is probably corrupted
how can i reload without loosing stuff ?
URP seems to bug also, mat are now pink
you can delete the Library folder and restart Unity and VS and it should theoretically start working. but its' best to not copy your project using a USB like that, but use some sort of version control like git or Unity Version Control instead
I try but its lag
Sounds like the good old lesson on why you just use verison control
doesnt explain why it happened
Probably missing/corrupted packages
well rn im removing then re-importing the packages were there is errors, but i dont see how this would solved the issues
im not copying my project, im loading it on both computer from USB.
I could use version control, but connection is slow at work so i would lose time each time to resync
well that's probably worse. the issue is likely corrupted files 🤷♂️
regenerate your package cache using the instructions i gave you
Loading directly from usb would be horrible, you're limited to the speed of the usb. Also for version control you would only have to sync small changes, it wouldnt be the entire project everytime.
im trying, cant copy/move/delete anything from my explorer, weird
im rebooting my pc
after fixing the issue i'll give it a try
sounds like a read/write issue then. hope your drive isn't dying
i hope to
if it does, you will have learned a very important lesson about always using version control
how do i do this for an instantiated object
wait
never mind
all good
sorry
Instantiate returns a reference to the object that was instantiated. use that to assign its forward
im getting flashback of an project lost i had in UE two years ago :')
what is VirtualArtifacts/Primary/ ?
Some compiled binaries I think
ok
well deleting library folders and restarting the project fixed all isssues
very weird that everything got corrupetd
i'll try installing UVC just in case
Its not like it got "corrupted". You probably copy pasted everything including the library folder. Stuff in it is compiled specifically for the local environment you run the editor in, so it might fail to work properly on a different machine.
Consider using git/github. Its pretty easy to use and has some different options for GUIs. It's also commonly used in every other aspect in computer science, so you'll need to know it if you do anything other than game dev.
how do i destroy a prefab from a different script
i mean
an instantiated prefab
but not all of the instantiated prefabs
as said above, i did none copy/paste
project is on USB since october, from my MAIN pc and LAPTOP i am loading the project from the USB
so the files are not "changed" from that
maybe i disconnected the usb to soon ? idk, i always make sure unity & VS stoped
Well it's basically the same, as you keep the same files that were created uniquely for the other environment.
anyway, I now setup UVC in one of my main drive, will do that same back home
you need its ref, then use Destroy(the object here)
github has space limitations
i'll go with UVC for now
You really wont run into issues with it. There is git lfs if you really need it, but I doubt you have many assets that are in the GBs.
Either way at least u got some vc
Hi im NEW to coding and i thought i might just start by following a tutorial 1 for 1 and i did, this one https://youtu.be/1uW-GbHrtQc?si=KFbQGVzXYBzisfr6 i have followed it exactly but its not woking when the movement script gets dragged to the player file it only dose (pic 1) insted of what is show in the video at 1:40 . had VS Code set to C++ then changed it to C# and it still doesn’t work.
Walk, Run, Jump and Sprint! Easily customizable!
A very simple player movement script that will get you started on your 3d project. Code is pinned in comments.
3D, First person (easy change to third person).
Sub for more :)
1: https://screenshot.help
2. make sure that there are no compile errors in your console
3. and get your !IDE configured using the instructions linked by the bot below 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
im tryna work on an enemy that patrols between a set of points
but it is just standing there
and wont move
here is the setup in the inspector
are the patrol points actually placed at a different position ?
@slender nymph thank you soooo much for ur time and help it worked but idk how i think i didn’t have VS code set up properly
yes they are
these are the two points @hexed terrace
I can give you my simple movement script
I wouldn’t mind
Give me 10min until i finish my lunch
When you follow a tutorial, if it is working in the tutorial and not for you .. then you either did something wrong or missed something, go back over it
VSC being "set to" C++ or C# isn't relevant, will make no difference to whether it works or not.
here
yopu will need an character controller on a object
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{```
Use the `RequireComponent` attribute and it will auto add one for you, if there isn't one already
(Which is what the tutorial he's doing does)
My parents always taught me not to take code from strangers.
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player")
{
Debug.Log("Triggered");
Event.Invoke();
Audio.Play();
if (BreakOnActivate)
{
Destroy(gameObject, 0f);
}
}
}
so I just added this code to play some sfx
but the Audio wont come out, what should I do?
the debug.log showed well and the audio file is noting wrong
What GameObject is Audio on ?
You're playing it then destroying the gameobject straight away
oh
nah I hate myself
Thanks bro
We've all done it
carwash are these logs correct?
You tell me... did you just type them and then take a screen shot? Or did you run the game and test ?
i ran the gake
gamw
game
You can edit msgs.
now log out the target pos, not the index
how would i do that i get an error that patrolpoints dosent contain a definition for transform
would i use a serialize field?
then that's your problem, there is no target position assigned
well shouldnt my array handle that?
i have the transforms of my points in the array
Have you capitalised the T in transform in your code?
yes
Okay, just checking, you'd be surprised at how many times something like that can be the culprit.
it wouldnt be the first time for me, thats why i made sure
Do you get the Transform error when you try to debug 'patrolPoints[currentPointIndex].position' ?
Also, for future reference, don't screenshot code, it's a pia tbh.
!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.
Hey guys I have a question, I have this code and I cannot figure out where I'm getting this error. When I fire up the game if I shoot the medium monster first, things go as intended, but when I hit the hard monster I get thrown a NRE error on this script. If I shoot the hard monster first, it goes just fine, but then try to shoot the medium monster and the NRE gets thrown again.
https://paste.ofcode.org/EnMX5GGZfiVTA6JMQPkMCL
I'm kinda at a loss rn
i dont
Okay, what are you debugging when you get the Transform error?
i was making a mistake anyways here is he result
Try debugging your compareTags. On the surface I can't see any reason for the issue tbh, but could just be tired.
Also, I'm not 100% sure on this, but it may be better to deal with the collision/killing the monsters on the actual monsters themselves instead of referencing them through the bullet (if that makes sense?)
I was thinking of this but wasn't sure if the monsters could reference an instantiated object very well. I'll give it a whirl though
so do you have any idea what the problem is with it?
Yeah you should just be able to check if the monster has collided with a bullet and adjust the monsters health accordingly. Pretty much exactly the way you have done already but in reverse, and you would only need one 'Monster script' just with different max health levels.
I'm not sure tbh. Try wrapping your main If/Else inside the if(once==false) check. Not sure if that's the issue, but worth a try. lol.
if (once == false)
{
once = true;
StartCoroutine(Wait());
}
else if (transform.position != patrolPoints[currentPointIndex].position)
{
transform.position = Vector2.MoveTowards(transform.position, patrolPoints[currentPointIndex].position, speed*Time.deltaTime);
}
Maybe that?
after a little more testing I think it has to do with the script looking for either a medium or hard monster script when none exists anymore (because the monster with the script is now destroyed)
Ah, yeah, sorry, shoulda spotting that tbh. To get around that I would remove the 'find' at the start and just use the collision to grab the script(s)
sounds to me like you need to use more Debug.Assert
nope
not working
i think im gonna come back to it after sleep
Ah sorry. 😦
can you explain how to use the collision to grab the scripts? I'm still new to scripting and I've never retrieved components of other scripts outside of the start/awake methods with constructors
is there a way to make the value not taking to much space ?
how ?
You are using 2 floats here
Right
If you want to change how it looks, you will need to add a custom editor
And if you have just these 2 floats, i personaly dont reccomend
Use a header as a text and just add a singlecharacter as a value
Trying to remember this off the top of my head, so this may not be 100% correct. But......
Remove your two 'Find' Lines in Awake.
Then in your collision checks add this (change as required)
mediumMonster = collision.gameObject.GetComponent<mediumMonster>();
Example
[Header("Global added height...")]
Public float GH = 0f;
that might do the trick, ty
Np
Sometimes cheating unity inspector is better than making a whole custom inspector xd
perfect this worked like a charm thank you
Cool. 🙂 No probs.
How do you switch scenes but keep your original position when you switch back to the original scene?
Because I know that loadscene resets the scene back to it's original state
How do I keep my character's original place in scene A from when I switch to scene B?
In this tutorial, you’ll learn how to use data persistence to preserve information across different scenes by taking a color that the user selects in the Menu scene and applying it to the transporter units in the Main scene. By the end of this tutorial, you will be able to: Ensure data is preserved throughout an application session by using the ...
general case: from scene A->B->C->....->Z then go back from Z->Y->X.....->A, you need a stack
Store the position in a save. Or a better way would be to keep your player/managers in a root scene and load your gameplay scenes asynchronously.
Out of incapsulation point of view, can i destroy a gameObject this way?
This is a question for #↕️┃editor-extensions
I was thinking of moving the destroy logics to the item script, but then i would have to use IsFull() method from the Inventory, and i dont know if that is good either
ah ok mb
Since item is a mono behaviour, you should just be able to use .gameObject, I'm not sure .GameObject() exists
It's completely subjective which is better, but personally, I don't think it should be the item's responsibility to detect pick ups and add itself to inventories. I prefer to think of items as passive things in the world that are waiting to be picked up. I would separate the pick up behavior into its own script that does the OnTriggerEnter, adding to the inventory and destroying. Think of it as the interface between the "real" world and the abstract inventory world.
But having the inventory be responsible for destroying the item only when it actually has room for it is perfectly valid, it's what I'd do as well. The item doesn't know if it should destroy itself without knowledge from the inventory, so it shouldn't be responsible for destroying itself
i disagree. I would do it the other way around
i would make Inventory.TryAddItem(Item item);
I’d make it return a bool to let the thing trying to add item to inventory know that it cannot be added.
then item should be responsible for knowing if it should destroy itself, or just ignore and stay on the ground, or whatever
because only the Item knows what to do when it is personally added to inventory. It might need to invoke something when it is successfully added, or it might be in a pool
That's actually a much better pattern. This is probably what should be happening.
@bright oxide
Thank you very much, that does make sense
basically when im not looking at the weapon im referencing the outline that is false on the code, how i make it doesn't count as an error, the game works just fine with the bug, i just wanna remove the error message
handle the error. don’t ignore it lmao
it IS an error, because you are working with something expected to not be null. It is null, and you don’t have a case for it
make a case for the thing being null, and make a case for it
Do yourself a favor and turn on error pause. Also we cant see what line 35 is here.
You should have zero errors in your console. If you see them, fix them.
errors caused by thrown exceptions mean that your code is just..randomly getting murdered
which makes it a lot harder to reason about what your code is doing
You should do this instead:
if (hoveredWeapon.TryGetComponent(out Outline outline))
outline.enabled = true;
Or, even better: gunScript should reference an Outline component
I would do that if every gun had an outline on it
ok, how would i do so
use the VisualStudio rename feature to have it automatically rename gunScript everywhere it appears in code
I believe it is shift+ctrl+R, when you click on the name you want to change
you wrote GunScript. Just… add a reference to the component to the class
example:
[field: SerializeField] public Outline outline {get; private set; }
example2:
public Outline outline {get; private set; }
private void Awake() {
outline = GetComponent<Outline>();
}
oh, like an singleton
what? this has nothing to do with a singleton
a singleton is a class that enforces that at most 1 instance of it exists at a time, and provides access to that one instance
i mean the way its written
if that is how you wrote a singleton, then it is not a singleton
if you have a monobehaviour singleton, then its Awake needs to check to see if another instance of itself exists already, and if so, destroy what would be the a second instance. If it does not exist, that instance assigns itself as THE instance for the class
does that make sense?
uhum
GunScript just needs to hold a reference to a different object that is publicly accessible, but NOT publicly modifiable
which is why I wrote it like this
btw this needs to be on the update void right?
so i can just do this right?
my SceneManager.LoadScene isn't working. I have the names of the scenes correct but when I press E on the hubworld, it won't load the level I want it to
👍
GetKeyDown in OnTriggerEnter is basically never going to happen
unless you are spiderman
and to rename its ctrl + r, its ctrl + r
Input.GetKeyDown is true for exactly one frame
OnTriggerEnter is only even called during fixed update frames
Weird because it worked fine when reloading my Snowboard Game with a button (using LoadScene). I used getkeydown in ontriggerenter and it reset when I hit the key
doubt it
it's wrong for two reasons
Wait scratch that
- OnTriggerEnter is similar to FixedUpdate in that it runs in cadence with the physics update, which doesn't run every frame. It's very likely your key press will land on either side of a physics frame
I forgot I changed that code
- The timing required is basically impossible
Forget what I said about it working 
yep
So what could I do instead?
GetKey is true on any frame where the key is down
Depends what behavior you're looking for
you want to be able to press a button while inside the trigger?
Yes
Then keep track of when you're inside
with a bool
set it true in OnTriggerEnter, false in OnTriggerExit
then in Update you can listen for the input and check if you're inside as well
if (Input.GetKeyDown(...) && currentlyInsideTheThing) {
// do something
}```
you’d do the same thing with InputSystem, but it would instead invoke just the function of what to do when pressing down
instead of checking in update
yo i need help with referencing the rigidbody of another object and on collision doing something can someone can help me possibly through a vc??
no VC in this server. Ask your question here
i just asked
You need to provide details of your problem to get an answer. #854851968446365696
Explain what you tried and how it went wrong
Im currently making a Board of buttons and allready have the script to activate them, but now I am thinking of the best way to implement functionality, do I have to implement a new script for every button or how can I call different functions with one script?
Buttons have an onClick event in the inspector which you can assign to any function you want.
Button components can be set to call a specific method of a given component in the scene
okay so im writing a script about picking up an item and then on collision playing a sound but i dont know how to reference a different gameobject's rigidbody and using the fucktion on collisionenter i can provide a script
OnCollisionEnter provides a Collision parameter which contains a reference to the other object
It also has this which directly gives you the other object's Rigidbody https://docs.unity3d.com/ScriptReference/Collision-rigidbody.html
Anyone know on how to instantiate a Script instance attached to the same GameObject within a Script?
i want it to react to my picked object collision
i believe the collider has better direct access to the rigidbody, if I’m not mistaken
so when my held object touches something it makes a sound
the problem is i have the pick up script on my player
What do you mean by " instantiate a Script instance attached to the same GameObject"?
GameObject.AddComponent
No they are 3D buttons in the game not in the overlay
and i want to reference the object rigidbody which i did but i dont know how to like "connect it" to on collision enter
as in:
CircleCollider2D myCollider = gameObject.AddComponent<CircleCollider2D>();
sorry if im wrong im a beggienr
Use a UnityEvent
You don't need to reference anything in the inspector
#💻┃code-beginner message The link i shared has an example
follow it
how?
what does he need?
can you link the documentation?
ty
I have a script attached to a game object, now I have another script attached to that same game object and I want the other script to instantiate that same script in its code
to run a function from another code, you must, check if function is public
that still doesn’t make sense
Oh wait is this the code for what I'm trying to do
what are you actually trying to make your game do?
gameObject.GetComponent<SpriteAnimationScript>();
still not clear
What does "instantiate that same script" mean? What is the end result you're looking for?
this doesn't instantiate anything, it gets a reference to an existing thing.
ok, now you got the script that its atached to, but dont remember to do it like this
SpriteAnimationScript SpriteanimationYourNamwwhatever = gameObject.GetComponent<SpriteAnimationScript>();
Exactly, sorry for the wording
so what's the question?
Sounds like you already know the answer
I was trying to get a reference to an existing script attached to my gameobject for another script that is also attached to it to use
now that you have SpriteanimationYourNamwwhatever
you can do SpriteanimationYourNamwwhatever.{name of the function}(some args)
You answered your own question here #💻┃code-beginner message
this is correct
(except you don't need the gameObject part, it's extraneous)
oh, yeah
I don't?
Alright thanks
like it would do any difference
GetComponent is a method on both GameObject and Component.
It looks for a component on the game object or the component's game object
in a MonoBehaviour, GetComponent() calls gameObject.GetComponent()
Ahh okay okay I see I see thanks for the help!
Do i use a descriptive name for the Down Arrow Key when using GetInput?
wdym by "GetInput"?
If you are using GetKey you should use https://docs.unity3d.com/ScriptReference/KeyCode.DownArrow.html
GetButton doesn't care about specific keys on your keyboard
It uses buttons that are defined in the Input Manager
like "Fire"
GetButton corresponds to the axes in your Input Manager settings
GetButtons are presets..(automatic) GetKey would be a specific key.. (manual)
oh, those are names you can use to describe the axis
axis.. like up and down arrow ^
Having a weird issue: I'm using a script that uses a Level ScriptableObject to instantiate prefab lights etc. for a given level
This works perfectly, but I'm trying to do the exact same thing with a particle system prefab, and I'm getting "The Object you want to instantiate is null." when it is definitely not null. Its field is populated in the ScriptableObject and the there's nothing wrong with the asset itself (in fact, its an exact copy of an asset I'm already instantiating somewhere else, I just copied it to test)
Any ideas?
I guess you could put in "Up" and "Down" in the positive and negative name fields
or "Throttle" and "Brake"
Ah i see isee thanks
are you referencing the correct scriptable object asset?
Work the problem in reverse, checking every assumption along the way. Start with the error, what line is it on?
Yes, but even if I wasn't, why would it be null?
private void AddParticles(Level currentLevel)
{
Object.Instantiate(currentLevel.LevelParticlePrefab); < error here
}
because you might have an asset that doesn't have a particle system prefab assigned
or your code is doing something else that's causing the error
okay, so this will only throw that specific exception if LevelParticlePrefab is null
now verify that currentLevel is what you think it is
if you do this, you can click on the log entry to be taken to the asset
Debug.Log("I'm at: " + currentLevel, currentLevel);
It's definitely assigned in the inspector, and all else equal, the code runs fine, with the script accessing the correct Level SO
Okay, what is currentLevel?
well, it's throwing an exception, so something sure isn't equal
even after the fixes it still shows the error
What error
A given Level object with its properties read from a Level ScriptableObject
All other values are being read from the SO correctly, it only gives an error during this final step
Commenting that one line out, everything works as expected
That doesn't answer digi's question
consider checking what currentLevel is actually referring to
prove that it's the correct asset
It doesn't matter what you think your program is doing
here
if your weapon has no outline component, then outline will be null, and you'll get an error
note that this isn't using the GunScript.outline field at all..
It sounds to me like hoveredWeapon doesn't have an Outline on it.
line 35 establishes already that the object does NOT have an outline component. So line 39 will always give you a NullReferenceException
it sounds to me like it should be after the if (Physics.Raycast... bit
I'm 100% certain that its accessing the correct Level and Level SO, I already tested for that
and line 32 shouldn'tbe looking at hoveredWeapon. surely it should be looking at the thing you just hit
So did you do what I suggested?
Yes, but like I said, I already tested that
So you logged currentLevel before you tried to instantiate its particle system prefab, and when you clicked on the log entry, it took you to the correct asset in the Project window?
the currentLevel value isn't itself an asset, but the SO is
I'd do this @tawdry totem
Outline lastOutline;
void Update() {
if (lastOutline != null) {
lastOutline.enabled = false;
lastOutline = null;
}
// other stuff
if (Physics.Raycast(...)) {
if (hit.transform.TryGetComponent(out Outline newOutline)) {
lastOutline = newOutline;
newOutline.enabled = true;
}
}
}```
It works perfectly thanks !
So you're instantiating a Level asset at some point?
Or do you just mean you're passing a reference to a scriptable object asset into that method's currentLevel argument?
[SerializeField] Level myLevel;
void Foo() {
Bar(myLevel);
}
void Bar(Level theLevel) {
// ...
}
The LevelSO is the asset, so currentLevel is just an object in code that gets the values from that asset and uses them
replace all in the update method?
Show me your entire script. I need to see what you're doing.
Nevermind, I got it
If I had a nickel for every time someone said they were 100% sure of something that turned out to not be the case I'd have enough nickels to put in a sock and smack them until they checked it to make sure
Okay but I was right tho
You still need to check everything
I literally said I did already
You're not instilling confidence by ignoring what I'm asking you to do and saying you're "100% sure"
Thanks for the help though, I know what I did wrong, I had to fix a line in the Level constructor
I have seen no message from you confirming what currentLevel is other than you saying you were "100% sure" that everything was correct, in which case you wouldn't have an error
Level has a constructor?!?
sorry, not the actual constructor
if theres a bug then u cant be 100% sure that everything is correct
ah, okay.
you can be 100% sure that something is incorrect tho
(because ScriptableObject types should not be constructed directly)
it's not a ScriptableObject
Once we confirm the level is correct then we move on to seeing if the referenced prefab is correct and so on
so there's a different Level type that is a scriptable object
Correct
that would have been very useful information to have.
That's what debugging is, building a core of confirmed truths until you find the one that is different than your assumptions
and I presume you just weren't copying the particle system prefab reference over, then
also, this would have been a compile error if currentLevel was not a unity object
which suggests that you didn't try it...
and dropping a ton of assertions to try to trip up the first part of the chain that does not match assumptions
I noticed that but I tried debugging values from the currentLevel, which did confirm it was reading correctly
idk why ya'll are assuming I just said I was 100% certain it was reading correctly without testing anything
I don't ask questions without trying to debug I promise!
Because we cannot see your screen so when we ask for information you have to actually provide it to us
and, again, dozens of people a day come in here "100% sure" of things that are just patently untrue
(they also have generally already 'tried everything' and 'tried thousands of times')
(and "did it exactly like the tutorial")
I was under the false impression that Level was the level scriptable object
all he said is that the instances being accessed are the correct instances
that was the hangup
(which is why sharing code helps, too)
i'd have cottoned on pretty quickly then!
Yeah I would have shared more but it's a bit cumbersome and split between a few scripts, sorry
these are in separate scripts, the latter of which is an instantiation. i’d like to avoid using a public bool across the two scripts if that is possible
Why am i unable to move if the player is looking completely down? ``` float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 forward = playerCamera.transform.forward;
Vector3 right = playerCamera.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;
rb.velocity = new Vector3(desiredMoveDirection.x * playerSpeed, rb.velocity.y, desiredMoveDirection.z * playerSpeed);```
because playerCamera.transform.forward is straight down and therefore x and z will be 0. only y will have a value
references with instantiated game objects are incredibly inconvenient
instead of using the camera direction you should use the player body's orientation
I used to use that, but realized that rotating the player's body would cause camera jitter.
not if you do it correctly
i.e. rotate the Rigidbody and not the Transform
is it the same as rotating with transform or no?
If it was, I wouldn't be suggesting it an implying it's the correct thing to do instead of rotating via the Transform
No, i mean code wise.
is it not possible to use if statements in interfaces?
keyScript is null
You are not using an if statement in an interface here. It's in an object that implements an interface.
But yeah, what digi said
I see your right. Having a hard time understanding why. did I not reference the keyScript correctly?
Either there exists an object tagged Player that has no KeyScript on it, or the code you sent in the previous screenshot happens before Start
debug the variable after u assign it and see
^ Yes this would check both cases
if it returns null its not..
I see now. The KeyScript wasn't even attached to the player.
lol, that'll do it
transform.position += new Vector3(0, -0.2f, 0);
this changes my object position to -0.2 Y right?
by 0.2
not negative?
Sorry, -0.2
it doesnt change on mine for some reason
I coded it to change for every frame that I hold the down arrow key down
show code
private void Update()
{
characterDirection += Vector3.down * characterGravity * Time.deltaTime ;
if(characterController.isGrounded)
{
characterDirection = Vector3.down;
if(Input.GetButton("Jump") && !Input.GetKey(KeyCode.DownArrow))
{
characterDirection = Vector3.up * characterJumpForce;
}
if (Input.GetKey(KeyCode.DownArrow))
{
dinoAnimation.CancelInvoke();
dinoAnimation.AltAnimate();
transform.position += new Vector3(0, -0.2f, 0);
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
dinoAnimation.Animate();
characterDirection = Vector3.down;
}
}
else
{
if(Input.GetKey(KeyCode.DownArrow))
{
characterDirection = Vector3.down * characterDownForce;
}
}
characterController.Move(characterDirection * Time.deltaTime);
}
I just provided the entire update method lol
Why don't you just apply it to characterDirection
wdym?
That's your velocity that you apply to the character controller
if you just add the value to characterDirection it'll get applied to the character controller
instead of trying to teleport the object
manipulate this variable all you need prior to the Move function
add to it, subtract from it, w/e u need.. keeps it clean and easy
Ah but i actually need to just reposition my character to look like its still on the ground
This is the wrong way to do it altogether
i just need it to look like it stays on ground after pressing down key
I understand what the goal is, but how you're trying to do it won't work
WHy does the y keep resetting back to 0? ``` yaw = rb.rotation.y + Input.GetAxis("Mouse X") * mouseSensitivity;
if (!invertCamera)
{
pitch -= mouseSensitivity * Input.GetAxis("Mouse Y");
}
else
{
// Inverted Y
pitch += mouseSensitivity * Input.GetAxis("Mouse Y");
}
// Clamp pitch between lookAngle
pitch = Mathf.Clamp(pitch, -maxLookAngle, maxLookAngle);
rb.rotation = Quaternion.Euler(0, yaw, 0);
playerCamera.transform.localRotation = Quaternion.Euler(pitch, 0, 0);```
Is it because of the character controller?
no
this is wrong why are you doing it yaw = rb.rotation.y + Input.GetAxis("Mouse X") * mouseSensitivity;