#💻┃code-beginner
1 messages · Page 102 of 1
!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.
caps
Your grass condition is impossible. You're running that code if WorldTiles does not contain that point, but then you check if it does. It cannot both contain and not contain that point
Don't put your code in an impossible condition
sould i make it n == 1 or wat
I have no idea what this has to do with what I said
so how do i make it possible
You need to think about what conditions need to be true to spawn a grass tile
And don't make impossible conditions
the argument i put into the function is non zero, however after the equation motion * time.deltatime, it returns 0,0,0.
why?
could you give a example
Yes. Don't make a condition where WorldTiles does not contain the point x,y but also does contain the point x,y
you logged both motion and Time.deltaTime (and the result of the multiplication) in that exact function?
either you didn't pass a non-zero vector, the Vector's magnitude is so incredibly small that it just looks like 0,0,0 when printed, or your time scale is 0
no but ill do that
hmmm it doesnt return 0,0,0 anymore
just extremely small numbers
i'll up the amplitude, see if i get results
my code works now! thank you all for the help :>
It was indeted wong 😢
Everytime I run my build script for dedicated server it changes the settings in the build settings to dedicated server and I have to switch it back to client, any way to no have that happen?
How does one fix camera stuttering/jittering?
By making sure the camera correctly tracks the target . . .
are you moving using rigidbody
yes the player has a rigidbody
track the player in late update and see if it helps
it would probably help to post your code for the camera movement and how its situated in your hierarchy.
it seems slightly worse, although i may have implemented it incorrectly
transform.position = cameraPosition.position;``` this is the camera follow script
{
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
camHolder.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
transform.rotation = Quaternion.Euler(0, yRotation, 0);
}``` and this is the Look script
the camera and player are separated
im assumming cameraPosition is a reference to your player object ?
yes
what is up with people have two different variables as multipliers for their mouse input? i swear this is like the fourth or fifth time i've seen that. is it from a tutorial? or is there some other reason you have both a sensitivity (aka a multiplier) and a multiplier?
Camera movement should always occur after the target's movement. You're trying to set the camera position to the target's position at the same time the target is trying to move to that position . . .
i sampled this from some random tutorial a while ago
how would i achieve that?
obligatory "use cinemachine"
but if you must do your own camera controls for whatever reason, you typically want to move your camera in LateUpdate if it is following something that moves in Update
putting the follow script in LateUpdate exarcerbates the issue
If the target object is moved using physics (in FixedUpdate), assigning the position — which doesn't use physics — will cause stuttering . . .
moving includes rotating
Honestly, it's much easier to use Cinemachine yo avoid all of this. It works great for camera control and is the new de-facto solution . . .
alright thank you both, i'll use cinemachine
if you are interested in solving this issue yourself though, you can give this a read https://kinematicsoup.com/news/2016/8/9/rrypp5tkubynjwxhxjzd42s3o034o8
but it's definitely easier (and will be better anyway) to just use cinemachine
You have to check a bunch of stuff. How the target moves determines where the follow/tracking code goes which could be LateUpdate or FixedUpdate, and if you need to apply interpolation . . .
A shortcut is placing an empty child GameObject on the target and tracking that instead . . .
ok
how to do a responsive movement like in valorant using add force. Any forcemode I use doesnt seem to make it feel like what it's supposed to (move when a key is held, and stop immediately after not pressing)```cs
if(!IsGrounded) rb.AddForce(new Vector3(Input.GetAxisRaw("Horizontal"), 0 , Input.GetAxisRaw("Vertical")) * speed, forceMode); // in FixedUpdate
Hey guys. I create this code https://paste.ofcode.org/38Cq4gXmKVYmTFZActvHcZ2 to shoot in all directions. It works when the boss is standing still but when he is moving the direction the bullet is going mess up.. why?
not sure add force is what you want if you are moving a character aside from jumping, have you tried modifying the velocity instead? that should give you immediate stopping while using your GetAxisRaw
!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.
why doesnt my airtime variable seem to be doing anything?
https://hatebin.com/oulyykoheq
what is its value?
lemme try velocity, havent tried it. I wanted addforce to make other forces add qith the movement force (like if you got hit by cannon while running, you can still quite control how you will be thrown (since you can no longer when you are not grounded))
1 currently
are you sure
yes
problem with this one is that, you wont move at all when speed is low enough (on majority of forcemode)
then you need to be specific about what you are expecting to happen versus what is actually happening
so depending one my airtime variable, i want my player to stay up in the air for that amount of time (like if airtime was 1, they would be up in the air for 1 second) however currently, my airtime variable doesnt seem to be working as even when i set it to some large number like 40, my player still stays in the amount for a relatively short amount of time.
show the rest of the code and the inspector for the object
do you want the full script?
yes
okay and just to confirm, you are intentionally setting gravityScale to 0 only after your airTimeCounter is greater than airTime?
so you want more gravity for the duration of your airTimeCounter? 🤔
wdym
i mean that gravity scale being 0 is less gravity. so only after your airTimeCounter has reached the value of airTime do you reduce gravity
yeah thats right
Anyone?
are you sure about that
because right now you have normal (or what i assume is normal) gravity for the duration of the airTime which means you fall faster for that duration
judging from this i think i mightve goofed
i thought i only go back to my original gravity once my player IsGrounder no?
sure but you never go to 0 gravity until after you pass that airTime threshold
oh yeah
so should i set my gravity to 0 during the duration of my counter and only set it back to it's og amount when it reaches my airTime value?
yes
i still have to tweak some stuff but im glad i found the problem thank you!! :)
!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.
Could anyone help me with smoothing on a slider? 😅
This implementation is not working at all. I don't really know what I'm doing in Mathf.SmoothDamp -
public class ExperienceView : MonoBehaviour
{
[SerializeField] private Slider _experienceSlider;
private float _currentVelocity;
private int? _xpUpdateAmount;
private void OnEnable()
{
ExperienceService.Instance.OnXPGained += UpdateXPSlider;
}
private void OnDisable()
{
ExperienceService.Instance.OnXPGained -= UpdateXPSlider;
}
private void Update()
{
HandlePotentialXPUpdate();
}
private void HandlePotentialXPUpdate()
{
if (_xpUpdateAmount is null) return;
// !! THIS PART !!
_experienceSlider.value = Mathf.SmoothDamp
(
_experienceSlider.value,
(float)_xpUpdateAmount,
ref _currentVelocity,
10f
);
if ((int)_experienceSlider.value == _xpUpdateAmount) _xpUpdateAmount = null;
}
private void UpdateXPSlider(int newXPAmount)
{
_xpUpdateAmount = newXPAmount;
}
there is a slider ui built into unity
also why is there a question mark after int at the start
don't multiply your mouse input by deltaTime
i am trying to make the sway variable give the camera a little sway when it moves on the x axis.
however,
inside the camsway function
when i lerp the sway variable to 0, it gives me a very quick climb down to 0
resulting in the camera shaking
unless youre not talking to me
yes, don't do that
don't multiply your mouse input by deltaTime
yes, because you should not be multiplying your mouse input by delta time.
reduce your sensitivity by a factor of 100
ok
Yes I'm using Unity's Slider, and the question mark is to make it nullable.
I guess my question is really about the last two parameters of
_experienceSlider.value = Mathf.SmoothDamp
(
_experienceSlider.value,
(float)_xpUpdateAmount,
ref _currentVelocity,
10f
);
you currently have smoothdamp set to take 10 seconds to go from the current value to the end value. but you're also just assigning the current value to the end value every time you change the value
anyways uhh could i have help with my sway problem
what debugging steps have you done
you're also just assigning the current value to the end value every time you change the value
isn't that intended?
if that is the intention then why are you using SmoothDamp
too smoothly transition from one value in the slider to another
because _xpUpdateAmount is already equal to _experienceSlider.value
ah wait, i think i misread what you are subscribing to
Mm, perhaps I've got some kind of misconception.
What I think I'm doing is this:
- I start with the current value of the slider
- I intend to increase it until
_xpUpdateAmountis reached - that intermediate step is what I intend to assign to
_experienceSlider.value
you also need to describe what exactly isn't working. because so far all you've said is that "This implementation is not working at all" which doesn't really say what is wrong
That's fair, sorry!
I've changed 10f to 1f (one second?) and it incorrectly does this: it slowly updates the slider value, but either it stops too early, or it doesn't use the correct target value (for example 40% is more like 10%)
have you printed out the values of the variables you are using or used breakpoints to inspect them to see what is going on?
No, but I feel like SmoothDamp isn't really what I'm looking for. I'll try a simple Lerp.
do you manually do gravity if you want to use character controller?
if you want to jump, yes. if you don't care about jumping then you can use SimpleMove which applies gravity but ignores any movement along the Y axis
i always manually change gravity for a player character
there are lots of times where you want to make sure gravity is just right. like no gravity when standing on a slope, or higher gravity when falling then jumping up
mb i never used it i didnt realise it was complicated
I am trying to instantiate an object facing the player with a rotation that is lined up. It spawns in the right place but for the Quaternion it won't line to the player's rotation. I've tried the player's rotation which spawns it at an opposite rotation and the Quaternion Inverse which also didn't work.
Hey Together i'm using Netcode für GameObjects and can't Find anything helpful about the following Error. I'm getting it after using the Update() to move something the whole time. Can someone Tell me more?
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 120, but that trigger was not received within within 1 second(s).
Probably want to ask in #archived-networking
Networking is definitely not a beginner issue either way 😸
Ty
Uv is an array of vectors per vertex that determine what point in the texture should be sampled at/around each vertex.
Uv mapping if you heard about it.
Yes
so all uv points are 2d
Yes
I see ty
how do i make the slider for my float in the inspector have a step of 1
just make it an Int if you're gonna use slider with that increment ?
you'd probably have to make a custom propdrawer
why is isGrounded always true?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;
public class PlayerMovement : MonoBehaviour
{
public GameObject player;
private Rigidbody2D rb;
private Animator animator;
private SpriteRenderer spriteRenderer;
private PlayerControls playerControls;
public float moveSpeed = 10f;
private float horizontalInput;
public float jumpForce = 10f;
bool isGrounded = true;
public bool canFlipX = true;
public int jumps = 0;
private void Awake()
{
playerControls = new PlayerControls();
}
void Start()
{
player = this.gameObject;
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Update()
{
isGrounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f);
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
Debug.Log(isGrounded);
Vector2 movementInput = playerControls.Movement.Walking.ReadValue<Vector2>();
}
public void Move(InputAction.CallbackContext context)
{
horizontalInput = context.ReadValue<Vector2>().x;
rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
}
public void Jump(InputAction.CallbackContext context)
{
if (context.performed && jumps < 2)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumps++;
}
else if (isGrounded)
{
jumps = 0; // Reset jumps when grounded
}
}
}
You don't use a layermask, so maybe hitting its own collider?
how would i implement that?
One of the overloads of Raycast uses a Layermask.
Make a Layermaks variable and set it in the inspector to whatever layer the ground is on, then use that
how do i apply that layer mask on the ground
All objects have a layer. It is near the top of the Inspector right under the name
The layermask that you pass into the raycast is just the layers you want it to interact with
You DON'T want it to interact with the player, and probably not default or other things like that
now isGrounded is always false?
Show what you did
Also, you are starting the raycast from the center of the object and going down .1f
Ok good. The issue is probably that the raycast simply doesn't reach
You can make an empty object and make it a child of the player, then move it to the feet. Use that as the origin of the raycast
that fixed it thankyou!
tysm 🙏
does anyone know how to code random side to side movement in c# like gelli fields, but it doesnlt move towards food
https://docs.unity3d.com/ScriptReference/Random.html
Use this to get a random value from a negative to positive value of your choice, then use that to shift the x position
I dunno gelli fields is or what "doesn't move towards food" means in this context though
Hi all i need some help with 2 problems i got.
-
I have some "pets" in my game. They are on their own scene and they basically just walk around in an fenced off area. I want them each to drop say a 💩 (turd) every hour or so (but not all at once).
How can i make them drop that turd that will be a button in the game so when the player clicks on it they will get a small reward of coins, gems or pet food. Im stuck y'all. I tried google with no luck. -
In my main game where the player does their main gameplay which is kill monsters. I have a panel that pops up when the player levels up to tell them they have leveled up and to give them a rewards. Thats all working great. But i want to gameplay in the background to pause/freeze while they are in the level up popup. I have tried setting timescale to 0 while the panel is open and back to 1 when the panel closes but the background gameplay still doesnt pause. Also i tried making a public enum GameState. I added move and pause to it. Then in my start i i said currentState = GameState.move;
Then when the panel opens i made the GameState to pause.
But that also doesnt seem to pause the game.
The only time it pauses is if i click on the GameState button on my script in the inspector. Like only if i click that button to choose what state i want. But it doesnt matter what state i choose the game still keeps running in the background.
thx
I ended up with this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomMovement : MonoBehaviour
{
public float speed = 5f;
public float changeDirectionInterval = 2f;
private float nextDirectionChangeTime;
private Vector3 targetDirection;
void Start()
{
ChangeDirection();
}
void Update()
{
// Move the object in the current direction
transform.Translate(targetDirection * speed * Time.deltaTime);
// Check if it's time to change direction
if (Time.time >= nextDirectionChangeTime)
{
ChangeDirection();
}
}
void ChangeDirection()
{
// Generate a random direction (side-to-side movement)
float randomX = Random.Range(-1f, 1f);
Vector2.x = Vector2.x + randomX;
}
}
but there is an error:
Assets\Scripts\SlimeMovement.cs(34,21): error CS0120: An object reference is required for the non-static field, method, or property 'Vector2.x'
What is Vector2.x?
I don't see a variable called that
And I recommend not naming variables the same things as existing stuff like Types
It is supposed to change the x by -1 to 1 based on a random variable
I meant to use Vector2 to do that, I am very new
Well Vector2 is a type.
So you would make a variable that IS a vector2:
Vector2 newDirection;
newDirection = new Vector2(randomX, 0);
Something like that
ok, thx, ill try that
Also, the error says SlimeMovement, but the class says RandomMovement.
The file name and class name need to be the same
can someone please explain to me what coroutines are and why I should use them like I'm 5 years old
I can't find any resources that make sense
A coroutine is a method. It is a special kind of method that can start and stop.
When you use the special word yield, it will stop, and let other code run
Normally methods will run until they complete, and the computer can't do anything else until it DOES complete
ok
so like you start a coroutine and then you could have it stop until a value is correct and then run again?
You could
Usually you would stop it for an amount of time
yield return null will wait for one frame
yield return new WaitForSeconds(10) will wait for 10 seconds
There are many things you can yield though
No prob.
It goes deeper for sure. But I just wanted to keep it simple like you wanted
I appreciate that
Im writing a gun system right now and I have to use them for the first time
help how can i fix this
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
body.velocity = new Vector2(body.velocity.x, speed);
isGrounded = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
isGrounded = true;
}
}
this feels a little slow
I feel a delay when I touch the ground, it takes a little while for isGrounded to be true
https://hatebin.com/fcnnfdnkln
i feel like i might be being a major dum dum, but i cant find out why the camera is always defaulting to being turned at a 0,0,0 rotation whenever i start the game
even if i change it itll switch it to 0,0,0
will locking the cursor cause that?
oh i see, its from line 42 updating its rotation to it nvm
To retain initial inspector changes, you could do something like..cs void Start() { //locking the cursor to not be visible Cursor.lockState = CursorLockMode.Locked; var initAngle = transform.localEulerAngles; mouseX = initAngle.x; mouseY = initAngle.y; }
In ChangeCircle, line 35, you wrote Input.something but you are using the new input system, and that is not compatible under your current settings
If you go to something like Edit > Player there is a "current input mode" or something like that where you can select "both"
Does the Start method run when instantiating an object or is it only when clicking play?
I was just testing an battle royale circle
It runs when you instantiate yes
Ok. Well. The issue is just what I said.
There are two types of input in unity. Your project is set to one, that code uses the other
hey im coding a simple turret shooting 3d game. Im currently having trouble with enemy collider detection so that the application quits when colliding with the player. This is the function im using in the enemy script.
void OnCollisionEnter(Collision collision)
{
// Check if the collision is with the player (tagged "Player")
if (collision.gameObject.CompareTag("Player"))
{
// Quit the application to stop the game
Application.Quit();
}
}
Currently both player and enemy have colliders (enemy has rigidbody too so i can freeze its rotation as I dont want it to fall over when moving towards the player). The player is tagged appropriately. Not sure whats wrong, ive added a debug as the first thing in the collisionenter function but it didnt even hit that. Ping me if you can help :D
What object is this script on?
I assume the Enemy?
yep
Application.Quit doesn't work in the Editor by the way, but it not showing the debug means the issue is something else
Go through this to see if anything explains it
https://unity.huh.how/physics-messages
If not, come back
yea the only other thing i tried was increasing the collider size of the enemy every so slightly outside of the mesh/capsule itself, although im sure that wasnt the problem. And ok, i will take a look ty
it just ended up bringing me to https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html
Code wise, I can't tell somethings wrong.
It goes page by page. At the bottom is a "I'm still not getting messages" prompt to continue.
I would guess this is a better place to start in it though
https://unity.huh.how/physics-messages/collision-matrix-3d
Maybe something with the rigidbody
While in edit-mode you just need to toggle the boolean to stop the game from playing
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
it is weird, I know 
🤔 do you really want to close the entire application when the enemy collides? that'd be quite tedious for the user to launch it again
how to get a point infront of a gameobject that also accounted it rotation
transform.forward
neat,ty
do people just enable a hitbox in the animation during attacks or what?
wrong axis what for the other two?
2D? Use transform.right for horizontal and transform.up if vertical
All of it is here
https://docs.unity3d.com/ScriptReference/Transform.html
yea sorry for ping i was looking and over look it
yes. I know I can add a more complicated way with menu scenes and whatever, but I just want to focus on why the collision isnt even being detected
my code isnt working to enable/disable a collider
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerAttack : MonoBehaviour
{
private Animator animator;
private PlayerControls playerControls;
[SerializeField] private Collider2D hitbox;
private void Awake()
{
playerControls = new PlayerControls();
}
private void Start()
{
animator = GetComponent<Animator>();
playerControls.Attack.Attack.performed += Attack;
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
private void Attack(InputAction.CallbackContext ctx)
{
if (ctx.performed)
{
animator.SetTrigger("Attacking");
}
}
public void EnableHitbox()
{
hitbox.enabled = true;
}
public void DisableHitbox()
{
hitbox.enabled = false;
}
}
No worries!
what debugging steps have you taken? the link you were shown above has like every possible cause for why it doesnt work
this isnt even working:
void OnCollisionEnter(Collision collision)
{
Debug.Log("HELLOOOOOOOOOOOOOOOOOO");
// Check if the collision is with the player (tagged "Player")
if (collision.gameObject.CompareTag("Player"))
{
// Quit the application to stop the game
Application.Quit();
}
}
how are you calling EnableHitbox
Object says none there
I fixed that but it didnt change anything
you should def select the animator on the object while you inspect that animator event
so you can link the method properly
also make sure there aren't any transition issues like leaving clip early
Application.Quit only works in a build. You want to disable playmode if you want it to also work in the editor.
When you say "fixed that". What do you mean specifically?
I made it not empty
sorry
By putting what in it? That's what I wanted to know 😸
ty, ill look into that, but the fact that the debug isnt even working is the first issue im trying to fix
Sorry i put the playerAttack script in there
Ah well for OnCollisionEnter to work at least one object needs to have a rigid body on it.
The script asset? Or an object with the script?
I'm not super well versed with animation events, but I assume you need the latter
The script asset
You have to select the object that has the animator
This will help guide you through the debug process https://unity.huh.how/physics-messages
Yeah, that would not work
I cant put the player in there though
I sent them that earlier. I think they've been working through it
Well, hopefully
Does the player have an animator and that script?
its not even showing that now
yea. Ive been trying. This link: https://unity.huh.how/physics-messages/collision-matrix-3d
gave me that graph, that showed a collision message would be sent with rigidbodies on both the collider and OTHER. So i added the rigidbody to the player since it didnt have it, so both now have it, and it still doesnt trigger anything
Are the rigidbodies kinimatic or dynamic?
ive yet to change any default settings when adding the rigidbody component to any game object
Well, it looks to be select in the dropdown..
I'm not sure sorry.
Animations are one of my weakest subjects
What about the collider
Neither collider is a trigger, right? I would assume not if you aren't falling through the ground
Yep, ok
well find those conflicts and remedy them
since im still just learning, i did try messing around with those at first.
the trigger i mean
but ended up with it off
I did and still not working
you did what ? what's not working
Can you try including the layer of the object you want to collide?
I deleted those functions and it is still not enabling the functions
In the "Include Layers" dropdown
sry, what do you mean layer
show what the dropdown shows for the animation event, the gameobject with the script has to be selected
oh ok. Sry but what item from the drop down should I be choosing? Currently its NONE
or NOTHING, for include layers
AND exclude layer
I am not currently in my workstation, so I just made a suggestion.
you definitely do not need to change those
ok. now put a Debug.Log inside EnableHit
and make sure that clip is being hit
fix the transitions too make sure they don't skip the event
I got it by changing it to GameObject and enabling that so thankyou
is there a way to determine if a sprite is fully transparent? Like literally empty
ok I just changed it to the player instead and it seemed to work. How do I go about quitting the game tho? Someone mentioned something about disabling playmode, not sure what that means. I just want the project to stop and the user to have to hit play again to start the game again
// Check if the collision is with the player (tagged "Player")
if (collision.gameObject.CompareTag("Enemy"))
{
Debug.Log("XXXXXXXXXXTESTXXXXXXXXXXXXXXX");
Application.Quit();
}
This doesnt work. And I looked into
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif}
which is what someone else mentioned, but it didnt format correctly and I think the # are read as comments
It does format correctly, and no it doesn't read it as comments, it grays out the part that doesn't compile in that setup
What do you mean it didn't format correctly?
and the player doesn't play the game in the Unity editor so Application.Quit just closes the game
and when I ran it it mentioned something about comment or something
#endif} is wrong. The } must be on the next line.
Or not be there at all
after you remove the bracket, you should be able to auto format it with your ide. the code itself should still be indented
it worked, ty !
Yea definitely configure your !ide, your ide should've told you about that error
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 looking for another beginner to work with on the upcoming IGDB beginners jam. If you are interested or want more info please dm.
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
u wnna collab or u telling me to go somewhere or is that supposed to do a command or something?
there is a bot message right there for you to read
ohh
why is that a rule
ima just tryna find someone for a game jam thats a stupid rule
private void Update()
{
body.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, body.velocity.y);
if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
body.velocity = new Vector2(body.velocity.x, speed);
isGrounded = false;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
isGrounded = true;
}
}
this feels a little slow
I feel a delay when I touch the ground, it takes a little while for isGrounded to be true
i dont know if this is the issue but creating two new vector2s every single frame is probably slowing your game down a lot
definitely not.
im not sure if you need to say new Vector2 or if you can just go body.velocity.x, speed rather than new Vector2(body.velocity.x, speed
OnCollisionEnter2D runs on a fixed time step because it's physics based. that might be why
not sure how much of a delay you feel though
also definitely not, that would result in an error
k im beginner also i just thought id see if i could figure it out since its good too learn
you would have to press the space bar within less than 0.02 seconds of landing for it to not register from that
im pretty sure atleast. again, im a beginner but from what i understand that is how it would work
!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.
!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.
i did simple script, but it doesnt do anything.
https://hatebin.com/qmuikkgvnl
private void Update()
{
if (countdown <= 0f) // If the timer reached 0
{
if(gameEnd==false) // If the game is still going
{
StartCoroutine(SpawnWave()); // Start spawning the waves
}
}
countdown -= Time.deltaTime;
}
IEnumerator SpawnWave()
{
for(int i = 0; i < Waves.Length; i++) // Goes throu all the waves
{
activeNumber = Waves[i]; // "Budget" of the active wave
activeMin = Min[i]; // The minimum spawn value for this wave
activeMax = Max[i]; // The maximum spawn value for this wave
while (activeNumber > 0)
{
int random = Random.Range(activeMin, activeMax); // Gets a random number between the min and max spawn value for this Wave
if (random > activeNumber) // Checks if there is still enough wave budget for this spawn
{
int newrandom = Random.Range(1, activeNumber); // If there isnt enough "budget" it gets a new spawn value within "budget"
random = newrandom;
}
SpawnEnemy(random); // The final spawn value corresponds to the serial number of one of the enemies and spawns it
yield return new WaitForSeconds(3f); // Time between 2 spawns
activeNumber = activeNumber - random; // Reducing the "budget" by the spawned enemy's value
}
yield return new WaitForSeconds(5f); //Time between 2 waves
}
gameEnd = true;
Debug.Log("You Won!");
}
}
``` Guys, this code worked until I commented it, now the time betwen spawns and time between waves doestn work well. They all spawn within like 0,001 sec from the last one.
yea thats about accurate, 0.02 seconds seems like a short time but usually in games people will jump when they think they are about to land. If it doesnt work, they have to press space again. it might take them 0.2 seconds to press it again, then its suddenly a lot worse.
what do you expect it to do? it is changing the public floats (clearly as shown in your screenshot). i assume it is also modifying the local copy of the localScale you have, but this vector3 is not associated with the transform.
i want it to change local scale
if (countdown <= 0f) then you start a coroutine. I dont see any code which sets cooldown to a positive value, it just keeps going negative. so every frame, you are starting a coroutine. At 100fps, that is 100 coroutines a second
Thanks. Its strange tho because it worked before without having that
then assign the value to the transform.localScale, the Vector3 localScale that you have isnt modifying the transform
if it worked before, then you must've either not had this code running in update, or you had the countdown set to a positive number at some point
oh thx
Hmmm strange. Strange. But thanks for help
did you move the line gameEnd=true; ?
If it was at the top of the coroutine then it would work as you expected
how can I edit a pre existing prefab? I created an enemy prefab and then continued working on it after trying to implement a score TextmeshproUGUI. Only problem is when I try to drag the text object here, it doesnt let me add it
you cannot add scene objects to prefabs
You need to pass references at instantiation
althought the structure looks bad, Enemy shouldn't have references to your UI score text
sry how do I do that ?
you instantiate the Enemy, and then assign the referecens via code
that's not really helpful. I get that as programmers we're all for "critical thinking", but that "via code" is just a useless statement.
I thought that if I was able to publicize variables, I could just drag and drop them in the unity inspector, but it seems I can't do that with prefabs. Imma just look for a way to reference the textmeshgui through start() i guess
yes you can
you just can't drag&drop scene objects to prefabs
and as I said, you shouldn't have reference to your UI score text inside Enemy script
instead you should have some kind of UI manager, and when the enemy dies, access that UI manager in your enemy Die() function, and change the text
For scores and the like, maybe look at using a Singleton?
you should make UIManager (singleton) or ScoreManager (singleton)
and when enemy dies access that singleton and increase score, change text, call an event whatever
new to this, never heard of singleton before

They're incredibly useful.
Dunno if this is the 'right' way tbh, but it does explain them very well.
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
ty RCE, much better help than just a google emoji
tbh, I typed 'Unity Singleton' into google and that was the first result. 😕
people are lazy nowadays 🤷
Speaking of which.......lol.
I'm having a bit of an issue that I don't really understand. Posting in here cause I'm 99% certain it's to do with the code and no the actual Animation 'segment'.
For some reason, only the backwards and right strafe animations play, and I can't seem to figure out why (Using a Blend Tree), and yes, I know it's horrible code. lol.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@north scroll Lookout for tutorials and resources in the pinned messages. https://unity.huh.how/references
hello iam making a topdown player controller and this moving script doesnt work
i have rigidbody on kinematic
💀
set it dynamic
it must be dynamic if you want object to move
i read that moveposition is best for kinematic
Not using MovePosition it doesn't (Literally just tried it myself to see if that was the issue on my topdown controller. lol.
@prime lodge Could do with seeing all the code if honest.
!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.
that is not true
sorry didnt know
SetParticles does not work via script. Did you have similar problems to set particles through script?
I have checked, particle array passes to SetParticles correctly
var ripplePSInstance = _pool.Get();
yield return null;
_rippleParticleSystems.Add(ripplePSInstance);
ripplePSInstance.transform.position = Vector3.zero;
ripplePSInstance.SetParticles(_ripples, rippleCount);
ripplePSInstance.Stop();
ripplePSInstance.gameObject.SetActive(true);
ripplePSInstance.Play();
how do i change rotation?????
well for starters, rotation is a quaternion so assigning any axis to 180 is incorrect. you probably want to assign the eulerAngles instead.
then there's this https://unity.huh.how/compiler-errors/cs1612
like this?
yes, that is better. but of course you're now setting a different axis to 180
2nd one is y
x, y, z
just hover over the Euler text
it'll show you what what is
I'm getting a constant error in the Console but I don't want to see it anymore. How can I mute individual errors?
you could fix the error
can anyone please help, its a very simple script
It's a store asset and it works perfectly fine, just getting thousands of errors, all the same, that I don't understand because I didn't write the script. It works fine so I don't care to fix it
don't rely on physics messages for ground checks. use queries like raycasts, overlapcircle, etc instead
Hi, I'm having a problem with my code and it's driving me crazy
im trying to add +1 to the money every 1 second but for some reason its not working
can you please guide me how I can implement it?
well there's no way to suppress specific error messages
Alright, thanks.
where is that log coming from? also are you sure you are even modifying the correct object? because you create brand new instances of those objects in your coroutine and since they are local variables that you don't appear to be passing to anything else, nothing else has references to the objects you modify
How do I raycast forward from a transform but with an offset of precisely X degrees towards the right?
Can someone help me figure out that direction ?
The log is coming from the GameManager Script, The first script creates many copies of an gameobject and all of them are supposed to add 1 to the GameManager script
ah wait, i see the issue. you're creating brand new instances of those objects for each iteration of your loop
i create a new instances for a gameobject called Machine and the machine is supposed to add +1 to the money in the GameManager script
machine is not a gameobject
and you're adding to the money field of Player not gamemanager
Player is also not a GameObject or even a component
but again, you're creating a brand new instance of Player for each iteration of the loop
the Player class is on the gamemanager script
that makes absolutely no difference to what i have said
public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
{
return Quaternion.Euler(angles) * (point - pivot) + pivot;
}
I usually use something like this where I'm grabbing a point in the direction, then rotating that point and making a new direction out of it. I know you can also use Quaternion.AngleAxis to make a new rotation.
even if i moved the Player player = new Player(); out of the Coroutine another issue will come
ah yes, another issue. that's super descriptive
:/
well you're probably starting the coroutine multiple times. of course you're not providing the full code so that's just a guess 🤷♂️
:)
do you understand what your code is doing? because it really seems like you're just throwing shit around randomly and hoping it works
'-'
this shit hurts
but yea
i think so
do you?
then you should go through some beginner courses to learn what you are doing. and learn how to reference other objects.
because you're still just creating completely separate instances of the Player object that have nothing at all to do with your GameManager or even each other
on top of that you're still creating a new Player instance every single frame inside of Update for some unknowable reason
i forgot to delete this line lol
i dont know what iam doing wrong but colliders on my character just doesnt work can somebody help me
iam struggling for like an hour
and the tile map has tilemap collider
he just goes right the the hill
Does any one know why this is happening? This is my code
https://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html
If the rigidbody is kinematic then any collisions won't affect the rigidbody itself and will only affect any other dynamic colliders.
PlayerRigidbody.MovePosition(PlayerRigidbody.position + DirectionInput * PlayerSpeed * Time.fixedDeltaTime);```
so how do i make a kinematic character stop when he collides with something
is the issue that your player isn't being stopped by other colliders?
its dynamic though
well it's a good thing that wasn't a reply to you then, isn't it?
no on collision as you see the object keeps on going in the opposite collision direction
oh. sorry!
are you referring to the other player object?
because you need drag to slow an object down over time
yup. so increase linear and angular drag?
its not my code, it belongs to a friend. I cant try it out and see.
I thought it was because he was using moveposition instead of rb.velocity. thanks for the help!
Tell your friend to try it out
No problem. But my question still stands, is moveposition reccomended over velocity? I thought it causes issues with collisions
The docs suggest move position for kinematic rigid bodies
So i was right. he should use velocity since its dynamic
Hi. I wrote a script: "NoteRead", which allows you to read notes. This script takes the text from another script: "Note". With just the text, everything was fine, and everything worked fine. When I decided to add another font (notes for a change), when I open the sheet, I get an error. I tried to inherit the script: "NoteRead" from the script "Note", but nothing helped. Line: 29
Mistake: ArgumentException: GetComponent requires that the requested component 'FontData' derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponent[T] () (at <c2d036c16ca64e0eb93703a3b13e733a>:0)
NoteRead.Update () (at Assets/Scenes/General/Скрипты/NtCpRead.cs:29)
!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.
whatever FontData is, it is not a component
And then what should I write in place of "FontData"?
We wouldn't be able to tell you. You ought to tell us what that line is supposed to do.
How can I update the state of properties in a script, from an "Editor" script. When I use "serializedObject.ApplyModifiedProperties();" It works but errors the following:
How can I do the same thign without the error?
#↕️┃editor-extensions you might want to ask there
This line should give font data from the "Note" script to the "NoteRead)" script (in which this line is located)
but what is FontData?
Why did you try to acquire some random font data component that isn't a component type? Does this type even have a font field/property? Where did you get this code from? Is your ide configured?
is FontData a scriptable object, non-monobehaviour class or what is it
Font, size, etc. - font information
I'm assuming the stuff on the left hand side of the assignment operation is simply made up and thus the line makes very little sense.
for starters, don't use the legacy text, use TextMeshPro
But you can't customize the font in it.
yes you can
I found out FontData when I clicked on copy by text (the screenshot I sent) and used it on the script. Besides the font, I want to change the size of the text, etc.
So the component type is Text. Look up the docs for Text and see the available method/properties for accessing whatever you're needing to access.
Sorry, I didn't know about that channel.
so you need to get the Text component
so you can access all the Text fields
change text, font size etc
but you really shouldn't use Text, use TextMeshPro instead
hey im working on a checkpoint system but when i die the boxclider of the checkpoint comes back so i have a invisble box i cant walk trough. + he destroys also my empty game object instead of the cube (spawnpoint) so he also destroy ever single other spawnpoint
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Thank you. It was necessary to write not "FontData" in the component, but "Text", and then separate it from it. Let me kiss you
I kiss you too
no thank you
hello
im having a problem with classes.
basically i have a class called "HomeData" inside of another class called "HomeManager".
this i the "HomeData" class:
[Serializable]
public class HomeData
{
public string HomeSize = "Default";
public string Floor = "Default";
public string Roof = "Default";
public string WallTexture = "Default";
}
the problem is when i do "new HomeData()" it just = "HomeManager+HomeData" for some reason but i want it to be all the data inside of home data so like (HomeSize = Default, Floor = Default) and so on
Just the collider returns or the entire spawn point object?
Not certain how you're respawning but if it's a reload of the scene, everything should return to normal.
Why does it come back? You'll need to tell us. The code provided simply destroys whatever triggered it.
i got a question, why when i change my canvas to screen spcae - camera and try to move a ui element it just goes thousands of positions away from where i told it to
idk why its come back thats the problem
i only having that script
because it is related to the camera
not overlay
how do i make it not go thousands away
This is the coding channel, you ought to ask your question in #💻┃unity-talk if it isn't related to coding. Delete this and repost there if it isn't related to code.
dont make it camera
i want post processing on it
i meant i told it where to go in code
Without code, people can't really help you unless it's simply a logical error and a simple one at that.
difficultiesTexts.LeanMove(new Vector2(960, 90 * difficultiesList.IndexOf(selected) + 540), 0.4f).setEaseInOutCirc(); theres the code for when i make it move, and it works perfectly fine when im using screen space - overlay but i want to add post processing to my ui and when i use screen spcae - camera the ui element just disappears
i am making a difficulty selection screen
what is LeanMove
no idea how this function works so can't really help
you could easiyl do it with DOTween tho
with DOAnchorPosition
so Unity says that I cant use && in this example. how else should I tell it to check for both?
https://hastebin.com/share/ekehegaxen.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it just smoothly moves an object to a place in a specified amount of time and you can add easing to it
you can't use && in a float assignment. but if you were comparing on the left side of the && operator i'm sure it would work 😉
Did you ever destroy the spawn point's collider?
does it modify transform.position?
for UI elements you need to move it by anchoredPosition
it modifies rectTransform.position
idk if thats the same
also make sure that your !IDE is configured so you don't make basic syntax mistakes like this
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
its inside the script so yes
but its weird coz it works perfectly fine with screen space - overlay
I'm assuming that you aren't and the box collider is a trigger type so collision cannot be made. You're probably showing us the wrong script.
thx
I'm also assuming check point and spawn point are the same
thats the only script i use dalphat
The spawn point collider isn't ever destroyed
and how can i make that inside my code
You probably aren't wanting to destroy the object. This object is also responsible for returning your player to a recent position
Looks like a feature request with conflicts of your current system which folks won't normally write/code. But an optional simple solution would be to disable the collider component.
so i need to disable the boxcolider
I'm not certain since it would seem you're referencing a list of game objects (supposedly check points) as well
It would depend on your setup
can i send you my project so you can check on it?
Just ask your question here with more info and people will consider giving suggestions
https://pastebin.com/YGC4UaNY i have an empty video1 object with this script attached to it. the children of the object are canvas with rawimage and videoplayer object with video. by the way, the two videoplayer Video1 and Vide2 are turned off by default because I don't want their audio to be played at the same time. I want video1 and video2 to be played alternately, but the problem is that after 2 videos nothing happens, not even debug messages from my code are displayed, only a black screen. please help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hey im working on a checkpoint system but when i die the boxclider of the checkpoint comes back so i have a invisble box i cant walk trough. + he destroys also my empty game object instead of the cube (spawnpoint) so he also destroy ever single other spawnpoint it also destroys my pickupgun script so when i walk inside the boxcolider of the gun to pickit up the game thinks its a spawnpoint when i fell of the map the game this to uncheck the istrigger .
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i think i messed up:
You've got a lot of random stuff in your spawn manager.. Maybe have a script on the check points and simply let this spawn manager be responsible for respawning - decouple some of the random code. //Spawn Manager Player (Game Object) Respawn Position (Vector 3) Previous Previous Check Point (Check Point script)`````` //Check Point Spawn Manager (Spawn Manager Script) On Trigger Enter Respawn Position equal to this position Respawn Enable Previous Check Point Respawn Previous Check Point equal to this Check Point Disable this component (the Check Point Script)Assuming you're allowing backtracking to previous checkpoints. Stuff done in trigger is an implied interaction on the Spawn Manager reference.
need help)
Life if humans used #↕️┃editor-extensions
public Vector2 boxSize;
why can I not see the box size?
white outline in the editor (the green lines are the box collider)
You need to draw a gizmos
got it ty
Can anyone help in #↕️┃editor-extensions I've been trying this for upwards of 2 hours now
don't crosspost (yes, going into another channel to try redirecting people to your question counts as crossposting).
you just have to be patient. if someone who knows the answer to your question sees it and wants to help then they will
Sorry I'm just really frustrated right now cuz there's like nothing clear online for such a basic problem.
You've uncovered the great conspiracy
json is string in ram byte stream in disk
how do you loop through a string?
though i think you should create the underlining class in c#
When is OnDrawGizmos called
You are gonna have to give more context to what you are trying to do with json. In unity, most people convert a json file to c# class using unitys built in Json utility class or newtonsoft.
I'm just trying to convert it to a dictionary so I can loop over it
create the class, dont use the dictionary
huh
Creating a class will be cleaner and easier to access the key names than a dictionary.
I mean sure but how do I do it
Do you not know what a class is?
I'm new to unity
but kinda
yeah
My json looks like this:
{
"PeriodicTable": [
{
"Atomic Number": "1",
"Element": "H",
"Name": "Hydrogen",
"Group": "1",
"Atomic Mass": "1.00797",
"Protons": "1",
"Neutrons": "0",
"Electrons": "1",
"State of Matter": "Gas",
"Valence Electrons": "1",
"Period": "1"
},
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
public TextAsset jsonData;
[System.Serializable]
public class JsonLoader{
public int AtomicNumber;
public string Symbol;
public string Name;
public int Group;
public float AtomicMass;
public int Protons;
public int Neutrons;
public int Electrons;
public string StateOfMatter;
public int ValenceElectrons;
public int Period;
}
void Start()
{
}
}
and that's my script
idk where to go from here i alr tried everything
json 101
[]=array
{}=object (the class)
So like a dictionary?
so you have an array of JsonLoader class, and the field name is peridodictable
the issue is idk what JsonLoader is exactly all i know is it has all my variables i need
and i don't know how to use that information to convert my json into a usable dictionary / array / whatever
btw you can rename the class to other eg Atom, more easy to read
[System.Serializable]
public class Chemistry{
public Atom[] periodictable;
}
```The parser will automatic create the class you passed into generic parameter (ie the name inside <> ) for you
well now what
You need to go to YouTube and type in convert json to class in unity
And learn
I wonder how you get the json if you dont know json...
can just treat it as text and make your own parser if you want
note that you aren't going to be writing and reading json yourself
you're just going to tell JsonUtility "please turn this object into JSON" or "please turn this JSON into an object"
what's the best practice for handling when an animation is candled and unable to call the method at the end, ex. an attack get's canceled that needs an end attack method to be called
interupt the animation and change state
Why I can't call the same method in Awake() and Start() ?
what same method?
GameController.instance.UpdateLife(health);
What is the error?
Maybe it hasnt been initialized in Awake yet
Its good practice to do intialization in Awake, and anything that relies on other classes in Start
But would like to know why it dont work
Hmm interesting
Awake probably runs before GameController.instance is set
what method is called when a object is instantiated
Awake
thank you, and sorry for not looking at the messages above
IEnumerator Gunfire(int FireNoteIndex)
{
Debug.Log("Gun");
gameObject.GetComponent<SpriteRenderer>().sprite = AttackSprites[0];
yield return null;
}```
So I just made my IDLE animations speed goes to 0 and run this Coroutine.
I checked the Coroutine Started but the Sprite doesn't change to AttackSprites[0] and remained to animation Sprites.
what should I do to change the sprite?
Why is this a coroutine? This has no delays or anything in it
will be
double check that AttackSprites[0] is indeed a different Sprite
If this coroutine runs at all, then this object's renderer's sprite does change to AttackSprites[0]. That is a guaranteed fact of reality. If what you're seeing isn't what you expect, then either:
A) This code isn't running on the object you think it is
B) AttackSprites[0] is not what you think it is
C) It is changed to something else after this runs
that is you assuming, not checking the actual code/data
I think C is highly accurate at this problem
are you sure you are not overriding the sprite anywhere else?
because if these logs are true, then it has changed the sprite to wakamo_attack_1_0
and if it show that is is not wakamo_attack_1_0 then something else changed it somewhere
use a debugger
put a breakpoint after changing the sprite
and see if it has the correct sprite
if yes, then you are overriding it somewhere else
or we are looking at 2 different game objects
or this
that code is only for the gameObject Wakamo
just do what you have been told
wait I need to find how to do in vsc
debug.log the GetInstanceId() in both cases to make sure they are the same objet
im making a vr game and i want that whenever the button is pressed, the door opens. how?
i kinda just started lol
open the door via animation, move it by code, whatever you want
make interaction system for the buttons
so you can interact with it
and link the Interact() of this particular button to open the door
https://www.w3schools.com/cs/index.php
Then !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok then geez
Just giving you some helpful resources to get started. Sorry if it came off short. Wish you the best 😸
good luck on that long journey, dont give up 😄
oh damn ok thx
!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.
Hi all, okay, so I'm trying to hide objects in a hierarchy by firing a ray from the camera (Camera is always a fixed view looking at the player character, so anything in between the two should turn off)
The issue I'm having is turning the objects back on, the way I've got it at the moment, the object that should be 'inactive' is flashing on and off, and I'm not sure how to fix it. Could anyone take a look please and point me in the right direction?
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, objectToHideLayerMask))
{
Debug.Log("Hit Something that should be hidden now");
GameObject objectHit = hit.transform.gameObject;
objectToHide = objectHit.transform.parent.gameObject;
objectToHide.SetActive(false);
}
else
{
if (objectToHide != null)
{
objectToHide.SetActive(true);
objectToHide = null;
}
}
Ah crap, of course you can't. 😕
you might want to for example only disable the renderer
but keep the collider on (as trigger so you cant collide with it)
so the object won't be visible
tbh I did think that, but it would be massively inefficiant (the hierarchy is floors of a building with a crapton of items in each floor.
why would that be inefficiant
it doesn't make any difference if you disable the entire object or just the renderer
Because I would have to disable/enable every single mesh renderer.
the object is still phyiscally there
you are already disabling/enabling the entire objects tho?
so instead, just disable/enable the renderers
objectToHide.GetComponent<MeshRenderer>().enabled = false;
assuming the renderer is attached to objectToHide
Yeah with one 'operation', disabling the renderers for every object would be different.
no
There's a renderer for the actual buildings floor. But the floors are populated with lots of other seperate objects (chairs/lamps/furniture etc etc).
Each with their own renderer.
objectToHide is to hide the floor. The furniture objects are children of the floor object.
When you disable the parent object, it goes through and disables each child already. This would be more efficient since it only deals with one component on each object
the colliders are lost, though, and that's an issue
I would suggest redesigning this a little.
you should have a Floor class
that stores all the props
and just disable the props
List<Prop> floorProps
then just iterate over them and do whatever you need on disable/enable
Create a collider that encompasses the region. Use that to decide whether or not you want to activate the floor. The collider should not be part of the floor itself.
So it'd look like this
- Floor
- Occlusion Collider <-- raycast against this
- Contents
turn off Contents as needed
You could write a little editor script to grow the collider to fit everything on the floor, or just hand-author it
yea your Floor should be preferably just an empty game object with a Floor class maybe with an additonal UnityEvents OnTurnedOn, OnTurnedOff, list of props etc so you have much more controll, and content/collider sepearte childs
This assumes you want to disable entire floors at a time.
I’ve got a small problem, I’m trying to make it so when the player walks into a “pod” the player movement cancels and the camera switches to the pod. Those both work but I made it so you could move the pod after and the player gets left behind.
My plan is to make the player speed a variable I can match to the pod’s when canMove= false, but I can’t figure that out
why not just parent the player to the pod?
You shouldn't try to make the player's movement exactly match the vehicle's, yes.
that'd be a never-ending treadmill of problems
that sounds like a fun challange 😄
what if the player gets stuck on something and the vehicle doesn't, or vice-versa?
it sounds like you want the player to enter the vehicle and then pilot the vehicle around
Probably not the best way to do it tbh, but this may get you started.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
that is not what i told you to do
brain issue
sorry
than I'll make breakpoint at yield
ok the code works so the sprite got changed and returned to idle sprite after 1 frame
so who changed damn sprite?
the animator?
I used this first time, so there are no hidden codes that changes sprites
(at least I wrote)
so
- I made Animator speed to 0.0f (to disable IDLE animations, seems no methods to stop the Animator)
- and Changed to Other Sprite
- and It changed to IDLE animation Sprite after 1 frame
- there is no additional my Components written by me except this and there is no code that changes sprite except this line.
but why??
does anyone knows how to solve this?
If the animator writes to a property in any of its states, it will constantly write to that property
One option is to set the property in LateUpdate
Update runs before animators. LateUpdate runs after.
Setting the layer weight to zero might work? I do not remember.
(but you can't set the weight of the default layer)
Yes, disabling the animator would stop it from doing anything.
I just started unity and this is my first time coding and i was wondering what the bracets mean in code
Braces group multiple statements into a single block statement.
they define something called Scope. That is the period of the code that the varaibles defined with in are alive
A statement is, intuitively, a single line of code.
(that is not the technical definition, but good enough for the moment)
what happens if i leave out the braces?
A block statement has its own scope, as Steve said. Variables you declare inside of it stop existing once you leave it.
Basically tells Unity that what is inside them belongs to the 'private void Start()' 'chunk' of code.
bruh I always walks a lot altough I have shortcut
Thanks I'll have to try disable and enable after the works end
In this case, you will get an error.
oh okay
and what about this
why are there braces throughout everything
rather than just two defining start and finish
You aren't allowed to declare a method without a body. You have to use { braces } to define a method body.
Hence the error.
Because they're different blocks
Because if, else if and else are essentially completely seperate from each other.
if statements do not require this. They just apply to whatever the next statement is.
because Scope can have many levels, in this case they are defining a Scope for the if statement
A block statement groups many statements into one big statement.
Without braces, you'd only ever be able to put a single statement after an if / else if/ etc.
The braces contain all the code inside them and basically turn them into one line. if statements apply only to the next line, if that line is a block, then it applies to everything in the braces
which would be very limiting
Its for some other language styles, C# do like that
There will also be a pair of braces that define the entire method's body
they're just not in your screenshot
yeah i know
and a pair of braces that start and end the class you declared the method inside of
If it helps, try to thing that anything inside the { } is 'written' on a post-it note of it's own. It's seperate from everything else, but you can cross reference.
Exactly this yeah
Look at the code I posted, will need a little tweaking as I use an interaction script between the player and the vehicle, but it should point you in the right direction.
Neat, thanks. I’m still very new to coding but I thought the best way to learn is make a little goal and achieve it
Learn things along the way
Plus then I have a bunch of placeholder code for common stuff I can cannibalize later
guys I'm actually gonna cry ok so my game is a 2d platformer and whenever the player dies it resets the scene (I didn't know how to make respawn points in the middle of development) the problem was that my audio reset so to fix this I made a don't destroy on load script but that also came with some problems for instance if I changed scenes the audio would still play creating more background music and them over lapping if you have any suggestions or things to help ping me pls!!
If resetting the scene is just a hack because you didn't want to just reset the level, then why are you trying to fix the audio reset as a result if you know you're going to change the restart functionality later?
Look up singletons. In Awake() check if a static variable of type 'YourSoundScript' is already assigned. If it is, Destroy(this.gameObject), if it is not, set the variable = this;
hi, my actions.toRun.preformed never happens. does anyone know why that is?
here is where MyInput() is called
you are only suppose to subscribe to your events once usually in awake or start
ahhhh
That's not how you set up the new input system. You need to subscribe to the events only once, for example in Awake() and not every frame like you are doing right now. I suggest checking out the Setup Guide for it.
thank you for the input i'll fix it as noted
hold
OK
ANYWAYS, i put the event subscribers in the start function and it still doesnt register the input of ToRun.
can anyone tell me why that is
oh you didnt have to
okay so i have got this class public class GameSettings : MonoBehaviour { public static Difficulty difficulty { get; set; } } and i want to right a script that changed the difficulty and this is what ive got GameObject.FindGameObjectWithTag("Settings").GetComponent<GameSettings>().difficulty = Difficulty.easy;
and for the difficulties i have an enum which contains the difficulties
but it doesnt seem to be able to change the difficulty in gamesettings
is it bc its static
if so is there a way i can fix it without making it non static
yes
yes, use a ddol manager or store it in prefs
PlayerPrefs.
this shouldn't work if it is actually static.
GameSettings.difficulty = Difficulty.easy;
should be all that is needed
alr
thank you
also do i need the difficulty varibiable to have the { get; set; }
And you could also use FindObjectOfType<GameSettings>().someVariable instead of looking for a GO and then looking for the component.
you don't
what does it even do
a property is basically a method that runs when you Set a variable or Get a variable, for example:
public int Health
{
get { return health; }
set
{
health = value;
if (health <= 0) PlayerDies();
}
}
private int health;```
Everytime you call Health -= 1; it checks if the health is below 0 and if it is it called PlayerDies();
why is there two private int health?
that makes sense thanks for that
One is public the other is private. You use the private one inside the class and expose public one for the rest of scripts
there actually aren't 2 int health's
ohhh yeah ive just realised ones public ones priv
It's the same as having a method called
public void ChangeHealth(int value)
{
health = value;
if (health <= 0) PlayerDies();
}```but neater.
also one has a capital H. case is important
alr thanks guys
ive got this car to move around by the player and a camera to follow it, but how can i make the camera align when the car turns? attached code is the camera's script
thinking that the camera has to have an orbit around the car to always be aligned, but need some help with coding that
Are you using Cinemachine?
no, its just a script on the main camera
Use Cinemachine. It already has various camera options to follow, orbit rotation etc., no need to reinvent the wheel
any tutorial i can follow to set it up?
Check pinned messages in #🎥┃cinemachine
they're all 3 years old
and don't apply to the current api
The JsonUtility API hasn't changed in forever, so doubt that
Are you using JsonUtility or something else?
If I recall correclty JsonUtility has some limitations and doesn't fully export complex objects
it's good for small things though
Some? More like a ton
Yeah it's pretty limited, but for what they're trying to do it's sufficient
It doesn't even have to be complex objects. Try serializing an array
Don't use JsonUtility, use Newtonsoft/JSON.NET
someone said it in the comments
som like json 3.0 to json 4.0 or sum shit
Is there any way to access the UpdateString of this component?
what is this component
Localize String Event
oh language stuff
yeah
I am trying to invoke a ManaRegeneration() method in the update function in an interval of manaRegenCooldown.
Expected Behaviour:
It increases the entityMana value every manaRegenCooldown seconds
Actual behaviour:
it waits manaRegenCooldown seconds and then increases the value every frame.
Here is the code:
[Header("Mana Stats")]
public float entityMana;
public float maxMana;
public float manaRegenCooldown;
void Update()
{
Invoke("ManaRegeneration", manaRegenCooldown);
}
void ManaRegeneration()
{
if (entityMana < maxMana)
entityMana += 10;
if (entityMana > maxMana)
entityMana = maxMana;
}```
The features you'll be using are basic and won't be affected by the version change if it's even a thing.
If it didn't work, you did something wrong
i got it to work
finally
can i ask people to identify what is wrong with my code in this chat
As long as you share it according to !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.
what is a backquote
I'll check it, thanks mate
It is to the left of the 1 key on my keyboard
Same key as the tilde
i found it im jsut chaning something quickly
horizontalInput = Input.GetAxis("Horizontal"); //leftright
playerRB.velocity = new Vector3(playerRB.velocity.x, 0.0f, playerRB.velocity.z);
transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed); //moves player
verticalInput = Input.GetAxis("Vertical");//updown
if (Input.GetAxis("Vertical") != 0.0f)
{
playerRB.velocity = new Vector3(playerRB.velocity.x, 0.0f, playerRB.velocity.z);
} else
{
if (Input.GetAxis("Vertical") == 0.0f)
{
playerRB.AddForce(Vector3.up * (0 - 5), ForceMode.Impulse);
}
}
transform.Translate(Vector3.up * verticalInput * Time.deltaTime * speed); //moves player
}
}
Basically, I want to have a downard force constantly applying to an object which the player can move up,down,left,right (including up and left at same time and stuff like that), but I dont know how to change gravity on rigidbody without chaning mass (I do not want to change mass if possible). Solution was to not use gravity and instead use a constant downward impulse force that only applies if player is not moving upwards (i might change this so it will still apply but less force if player moves upwards). However if i click vertical force once the downard force stops applying (this is my issue). What is wrong in my code for the downard force to only work at start
this is in void update
Changing mass doesn't affect gravity at all
I was chanign something else it wasnt mass sorry let me check again
You also seem to be mixing Rigidbody motion with transform.Translate, which is a recipe for failure
Not only that but you're assigning y velocity to 0 every frame and then also trying to do jumping with forces
All in all it's kind of a mess at the moment
You're essentially mixing 3 different movement strategies in a way where they'll all clash with each other
I'd consider looking into coroutines
I tried it with coroutines as well, same result
does it have to do with calling it in Update?
Yes this was a problem as gravity was affecting the object in a way that it was glitching out a bit when i tried to move upwards and is reason that i could not move upwards and sideways i think
What is an alternative
I want to make something move around the radius of a circle based on mouse input i.e right mouse move right left mouse move left how do I do this? I’m sssuming some type of sin cos
Im going to turn gravity off and stop the new assignment to velocty in every frame
Just use one thing. Eliminate all transform movement, or eliminate all rigidbody movement (I recommend the former)
why is rigidbody movement better than transform
Transform is simply teleporting from place to place. This causes lots of issues with collisions and other stuff
Rigidbody interpolates between the positions
Well, you can also just check normally in update if want to do that (via time comparison), but otherwise you'd run the coroutine once in Start() or some calling method and let it passively work
So using a coroutine in Start() means that it will run all the time?
yep, you do a while loop in the coroutine and it'll wake up every so often, do its job, then sleep
but make sure you're yielding correctly else you'll freeze unity
Thank you. If i may ask how can I do smooth rigidbody movement in a way which is not like impulse but similar to the flow of transformtranslate (without teleporting).
u could always manipulate its velocity
Rigidbody movement includes AddForce, velocity =, and MovePosition.
You probably want to try both velocity setting and MovePosition to see which you like best
ok thank you
does anyone know what this error means? ArgumentNullException: Value cannot be null. Parameter name: _unity_self UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <347e3e2bef8c4deb82c9790c6e198135>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <27a779fc555e412cad6318e4bfb44443>:0) UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.Panel.UpdateBindings () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <d30253adcd2a48faba9ee2264e211f5a>:0) UnityEditor.RetainedMode.UpdateSchedulers () (at <27a779fc555e412cad6318e4bfb44443>:0) i know it says ArgumentNullException and i know that that means theres a null value that cant be null but i dont know what value it it and when i double click on the error nothing happens
alr
UnityEditor.UIElements usually gives it away
yep thats fixed it now thanks
sometimes resetting the layout will also fix it.. but nothing beats a good ole restart
Wow, this just helped me out. Literally no reason why my on mouse hover shouldnt have been working for all prefabs I had it on. A simple restart fixed it. Should know better by now
Hi! I cannot for the life of me figure out how to remove a component from a gameobject. The component is an interface script IAbility. Any ideas? This is the script I've tried but isn't working> void RemoveAbilityScript(IAbility ability) { if (!CanRemoveScripts) { return; } if (ability == null) { return; } string abilityName = ability.ToString(); var componentToRemove = GetComponent(abilityName); Destroy(componentToRemove); }
a coroutine maybe unnecessary, If all you want is it to repeat try the InvokeRepeating method instead inside the start method
Not sure why you need to pass a parameter, when you can do GetComponent<IAbility>() to get the first component implementing this interface
I have three IAbility scripts on a single gamobject at a time, so that's why I need to be specific
Okay so you need to remove one of the concrete components that implements the interface
You can make a generic method for this, with a type constraint
Maybe I could do GetComponents<IAbility>() and choose the one in that list because I know which one i need?
Nevermind that wouldn't work because I can't control the order
void RemoveAbility<T>() where T : IAbility
Then GetComponent<T>() in it, and destroy that
Ok let my try that
After that, you can call the method and pass the component type to remove, and with the type constraint, it'll produce a compiler error if you pass a type that does not implement the interface
the GetComponent<T>() calls an error "Cannot convert T to UnityEngine.object
Show your updated code
{
Destroy(GetComponent<T>());
}
``` And here is where I assign the variable to be removed: ```
public void AssignAbility(IAbility newAbility, int abilityNum, Ability abilityForList)
{
abilities[abilityNum] = abilityForList;
switch (abilityNum)
{
case 0:
RemoveAbility<ability1>();
ability1 = newAbility;
break;
case 1:
RemoveAbility<ability2>();
ability2 = newAbility;
break;
case 2:
RemoveAbility<ability3>();
ability3 = newAbility;
break;
}
}```
But that also calls an error because ability1 cannot be found
Yeah generic types don't work like that, you cannot treat the things you pass in the <> as variables
So you cannot use generic types in this context
Ok, so what would I do? I've tried Type.GetType(ability1.ToString()); But it returns null so it doesn't work
Revert to the old code, get all the components that implements that interface, loop through them, and do an equality check
Weird thing for abilities to be attached to game object though, usually they're simple classes stored in a list
Can't you just call Destroy(ability);
usually you use generics to avoid these types of switch statements
I wouldn't suggest doing them if you're not well verse in them and just stick to comparisons for now
If I do it says "Cannot convert IAbility to UnityEngine.object"
how about making IAbility a base class or creating a new base class for your abilities
and then using that as a parameter
How is a better way to do a better ability system?
or, you add a method called DestroyMe() in your interface that you can then call.
Oh that's promising
But it's maybe hard to convert all of the abilities because it's rooted in many other scipts... I haven't been focusing on very cean code
like he mentioned.. u could just use classes and have a Manager type master class that holds a list of what abilities you have..
using MonoBehaviours adds a lot of overhead. If you don't need Update(), Start(), etc. there is no real reason for them to be that.
ohhh I see
I'll try to convert the current system
Thank you for the help
whats the data type for a 3d object? like if i want to change a gameobjects 3d object
how would i do attacks i have a animation for it and have it set up to attack when you press left click but how do i have it do stuff to enemies when you attack them like how do i calculate that you are hitting them
wdym by its 3d object
there are many ways, you could use physics queries at specific points of the animation using animation events or you could rely on ontrigger/collisionenter
take a look at the component you want to change. its name will typically be the type you use
if i try to settrigger a trigger that isnt there will there be a error
correction, you get a warning not an error
as for whether there's a method to check if a parameter exists, i don't know off hand but you can check the !docs
any idea why im getting this
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List1[T] inEdges, System.Collections.Generic.List1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp (System.Boolean force) (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.WakeUp () (at <f94752164e14499c83c250d9839d9e96>:0)
UnityEditor.Graphs.Graph.OnEnable () (at <f94752164e14499c83c250d9839d9e96>:0)
editor error, likely due to having the animator open. you can ignore it
ah ok i thought it was smth with my code lol
If the error location starts with Unity anything (like yours starts with UnityEditor), it won't be your code
ah ok
why is this not working i get the hit1 but not hit2
Collider[] hitEnemies = Physics.OverlapSphere(transform.position, 2f, enemyLayer);
Debug.Log("Hit1");
foreach (Collider enemy in hitEnemies)
{
/*EnemyHealth enemyHealth = enemy.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
enemyHealth.TakeDamage(punchForce);
}*/
Debug.Log("Hit2");
enemy.GetComponent<Animator>().SetTrigger("Hurt");
}
im hitting a enemy
apparently not
note that just because Hit1 prints, does not mean you are actually hitting anything
go through this to figure out why your OverlapSphere is not actually detecting anything: https://unity.huh.how/physics-queries
I created a base class for an item and insert that before the default time in Script Execution Order. Will that execution order affect the inherited classes?
[DefaultExecutionOrder(-10000)]
public class ItemBase : ScriptableObject
{ }
// Will it affect?
public class ItemInherited : ItemBase
{ }
// Both shown in the list inside Script Execution Order
it should, yes
also the attribute does not add them to the list in the script execution order settings
good evening all,
I've been throwing my head at the wall of 3d for a long time but looking to make the switch from 3d to 2d, I'm trying to avoid entering tutorial hell (again), any good written documents (not including the unity docs as im not sure how they piece together) about movement etc
there should be no differences pretty much
I will admit i had a google but it just threw a mishmash of yt tutorials and uh, yeah i've watched too many lol
guys this piece of code wont lag and executated every frame? I mean if it was executed only one time void Update() { if (Gun.GetComponent<Gun>().ammo <= 0 && !gun.GetBool("OutOfAmmo")) { gun.SetBool("OutOfAmmo", true); shootEmpty.Play(); } }
GetComponent every frame 😬
It probably won't but reference-cache those components instead of acquiring them every frame. If guns are changed, update them when the gun changes.
I know, but i'm hoping to go into it from scratch.
I over scoped for my first few games, published a few but they were abslutely clusters and i followed a lot of tutorials (didn't learn much) So my knowledge is fairly scatter brained across a lot of random things
if the other conditions are true
so how i should solve it?
what exactly is the problem you're experiencing ?
Void lateupdate could work for that?
Hello. Can someone tell me pls if I can use the IgnoreCollision method to make the ray ignore objects with a specific tag. An example is below.
public class RaycastLearn : MonoBehaviour
{
public string[] tagsToIgnore = { "Base", "Wall" };
public GameObject[] objectsToIgnore;
void Update()
{
Vector3 rayOrigin = transform.position;
Vector3 rayDirection = transform.forward;
RaycastHit hit;
foreach (string tagToIgnore in tagsToIgnore)
{
objectsToIgnore = GameObject.FindGameObjectsWithTag(tagToIgnore);
}
foreach (GameObject objToIgnore in objectsToIgnore)
{
Physics.IgnoreCollision(gameObject.GetComponent<Collider>(), objToIgnore.GetComponent<Collider>());
}
if (Physics.Raycast(rayOrigin, rayDirection, out hit, Mathf.Infinity))
{
Debug.Log("Hit object: " + hit.collider.gameObject.name);
}
Debug.DrawRay(rayOrigin, rayDirection * 10f, Color.green);
}
}
I think i shown in what i just said lol, I'm essentially starting with next to no coding experience so hopng for a website or tutorial thats actually...good(?) to help explain things and how they fit like a jigsaw
these codes too? first code: ``` void Update()
{
if (Input.GetKeyUp(KeyCode.E) && !objectAnimator.GetBool("Flushing"))
{
objectAnimator = gameObject.GetComponent<Animator>();
ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit, interactDistance) && hit.collider.gameObject == gameObject)
{
InteractWithObject();
}
}
else if (objectAnimator.GetBool("Flushing"))
{
objectAnimator.SetBool("Flushing", false);
}
if (!toiletExplodes.active)
{
audi.Stop();
}
}``` second code: ``` void Update()
{
if (Input.GetMouseButtonDown(0)) {
Invoke("IsShootingTrigger", 0.1f);
}
}```
It seems that my fears came true xd, every frame is executed this
you mean this ? objectAnimator = gameObject.GetComponent<Animator>(); ?
uh yeah whats the point of doing this at runtime
if the component is already on THIS object
welp i was trying to make a flushing animation on a toilet,simply that
but thats for #🏃┃animation
is there a way i can change the RectTransform.right value in code by itself
I wanted to do that to make sure it works and then I would have to drag the animator into the script
what are you trying to do