#💻┃code-beginner
1 messages · Page 303 of 1
pretty sure Osteel was talking to someone else
Yes, that was clearly for the other person asking if they could ask questions 😸
Talking to that other person in another server. They are not asking anythikg related to unity, which is why they didn't continue asking
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float timer = 0.0f;
private int spawnInterval = 5;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
moveLeft.y = -7f;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
Instantiate(PipePair);
}
}
Ok so im at this stage of that Unity tutorial where it sadly stopped providing helpful tutorials about the code or the game and unity's functions etc etc and instead is just showing me how to write a report or whatever on what my game is gonna be, i dont care, the tutorials were good at teaching stuff but the good tutorials ended way too quickly, now its just random crap again
anyway so he gives me all the creative freedom to basically do whatever i want at this point to "learn" and i decided to do this
its basically a basic flappy bird game but the code gotten kinda complicated here lol
also check this out, it is making new obstacles properly but at this stage I want the obstacles to be able to move backwards on a loop, so far i couldnt make this to work yet
and also have another problem which is the fact that its instantiating 2 then 4 then 4 becomes 8 then 8 becomes 16 then 16 pipe obstacles become 32 etc etc. This is also another big problem which I dont understand so far why it happens or how to stop it.
pipes should not spawn pipes, that is why it is exponential
Hi, I'm kinda new to Unity, and I have an error in my code that I can't understand. I'm trying to access another object's velocity from a different object, but it says I can't access the rigidbody due to not having permissions to view it. However, the class and rigidbody are both public, so I don't know what's going on. Any help would be appreciated. Thanks!
Also I hope this is the right thread for this
well then how would you make an endless survival game?
this isnt supposed to be a multiple scenes type of game
i wanted to make the pipe platforms spawn somewhere between those extreme upper lower variables you see on top of my script
and i planned on using something similar to python's random.randint()
show the declaration of Boat in the Camera script
wdym
you just need to make a seperate gameobject which handles the spawning and remove it from your pipe script
i have to declare the boat in the camera script?
this is all the code up until that point
if you want to use there, yes. What did you think Boat. did?
i thought it accessed the gameobject that i declared in the boat script
no
your camera script knows nothing about that
even though it's public?
i thought that's what making it public did: allow everything to see it
I think you need to follow some basic C# tutorials
you should start with configuring your Visual Studio first. and then I'd highly recommend you watch this video. You seem to have a misunderstanding on how to get references to object
https://www.youtube.com/watch?v=dtv7mjj_iog
As a new dev, keeping references to game objects you need can be a little confusing. Learn how to store game objects for later use as well as allowing external scripts access to your goodies.
Instead of trying to find an object, shift your thought pattern a little and ask "should I already know where this object is?".
❤️ Become a Tarobro on ...
the issue is not the access modifier, which is public
you're right that it needs to be public, but that's not the problem here
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
heres the guide to configure your visual studio
and if you're really new to programming and Unity in general, start with a C# tutorial
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
then the beginner scripting course in Unity Learn
https://learn.unity.com/project/beginner-gameplay-scripting
the reason why we're directing you to tutorials is because you have a misunderstanding of some of the fundamentals, so it'll be hard for you to understand the help that's given at this point
and all these links are pinned in this channel for future reference
Thanks!
is photon pun outdated? i’ve been following a tutorial on it and don’t want to get too far into it with something not “useful”
alternatively, what is a multiplayer game service you would recommend and where would i get that?
might want to ask in #archived-networking instead
check out the pins there too
okie :)
ok, why does that make a difference tho, thats weird
it's not weird at all. Think about it.
you have a pipe running that Update/Spawn loop. it spawns a new pipe so now you have 2 pipes running the same loop, etc, etc
then the same thing will happen if i make a nested object inside of another object i think
so do i still need to get the old gameobject?
or use the parent?
yes, your spawner should be completely separate from your pipes
PipeSpawner is empty
ok, is the Pipe Pair okay?
as you can see here I still have the old pipe prefab object attached inside of that reference
you don't need a prefab there at all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair; // should I remove this?
private float timer = 0.0f;
private int spawnInterval = 5;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
moveLeft.y = -7f;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
Instantiate(PipePair);
}
}
Line 10 public GameObject PipePair; // should I remove this?
did you not understand what I said? You need to move the whole spawning code to a new script and put that on a separate object. It should not be in a script attached to a pipe
its not attached to a pipe at all
in fact
right now it works perfectly
well almost
Its no longer spawning exponentially
if it is not attached to a pipe what is it supposed to be moving?
it is attached to the child pipe object containing 2 pipes, the thing is, its not doing anything right now because I haven't given it any logic for what I wanna do with it but im not sure if i should keep it or not, so basically my next step is to ensure that all these pipes move on the position.x axis in a negative way multiplied by speed and time.delta time and then destroy them after a while once they get off the screen
This script should be attached to the PipeSpawner object. you will then need another script to attach to the pipe objects to make them move
well here's the thing
I tried that just now
and I got the same exponential duplication problem
so I attached the public GameObject to child object again and it got away
so this is what was causing the problem
anyway is there a way that a script can reference the object it is using without needing to use these serealized fields to communicate to a gameobject from the hierarchy?
if this script is in my inspector of PipeSpawner
then it makes sense that I could use PipeSpawner and push that shit back and forth and create the illusion that they are moving
in fact PipeSpawner is a name i might need to change rn
yes but if you can directly reference the objects via the inspector you should
Look your setup is very simple
Pipespawner - has pipeposition script which spawns PipePair
-> PipePair - has a script which moves the pipes
Hello, I am a new beginner to unity, and I made some UI
now, I don't know how do I check when something is clicked
I tried using ai, but it didn't help ```csharp
using UnityEngine;
public class ClickableNextImage : MonoBehaviour
{
// Update is called once per frame
void Update()
{
// Check if the mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
// Cast a ray from the mouse position into the scene
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
// Check if the ray hits the object named 'nextImage'
if (hit.collider != null && hit.collider.gameObject.name == "NextImage")
{
// Handle the click event
OnNextImageClick();
}
}
}
void OnNextImageClick()
{
// This method will be called when the 'nextImage' is clicked
Debug.Log("Next image clicked!");
// You can put any code here that you want to execute when the 'nextImage' is clicked
}
}
I am very confused, and I would really apreciate some help
(I put the script inside of the 'NextImage' object)
Are your 'clickables' images or buttons?
they are just normal images
Okay, Make them buttons (it's far simpler and easier), remove all the raycasting stuff from your code (you don't need it if you use buttons)
then add an button, other components cant be turned into a button
Yes you can add a button component
But it is a lot simpler to just create a new button if honest.
yo guys why are these clone objects spawning in the middle of the screen instead of copying the position of their prototype original object position which they are cloning after?
Thank you!, now, is there any VCs here? because I feel like talking is much easier then texting
thats the most idiotic thing ive ever seen in my life
I don't believe so. Go make all your buttons and come back. Happy to help 🙂
No probs. Okay, I'm going to assume you haven't done any of what I'm about to say. 🙂
Create a new empty GameObject in your game Hierarchy (reset it's transform) and add your ClickableNextImage to it.
ClickableNextImage script I meant
can we dm call?, I am getting uncomftarbal that I can't vitualize it, if no, please tell me strait ahead
I can't talk at the moment (literally, got a cold and no voice. :-/) Give me a moment though.
Kk
Why are these clone objects spawning in the middle of the screen? They are cloning after an object that is standing outside the camera!!!
(video incoming)
and...... im talking about these shenanigans
( video still loading )
( almost there )
^ this is the video im talking about
Well where should they go?
look at the first object lol
they should be sitting outside like that, also how do i change their position?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float timer = 0.0f;
private int spawnInterval = 2;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
Instantiate(PipePair);
}
void OnInstantiate()
{
PipePair.AddComponent<LeftMove>();
}
}
I try to add xyz but throws an error after I try to create positio
wtf
please read the Instantiate documentation to learn how you can set the position of the object you instantiate
you'll also learn how you can get a reference to the object you just spawned
Instantiate returns the object it creates. You can use modify the position that way right after it's spawned.
Instantiate also has an overload that accepts a position and rotation.
Just DM'd you 🙂
So you can do Instantiate(prefab, position, Quaternion.Identity) if you want it to spawn at a specified position with an upright rotation.
I try to stick a script on them right after these clones get spawned but this apparently is as useful as a screen door on a submarine
Well first off, this is never called.
Not really sure why you're doing that tbh, why not just have the script on the Prefab?
Secondly, you're targeting the prefab, not the spawned instance.
ok good point
Thirdly, why not just have that script on the prefab to start with?
Also, when you instantiate, you should be doing GameObject newPipePair = Instantiate etc.etc.
I named my spawned instance the same name as the prefab
And then if you need to do anything else, do it to newPipePair
ok will the script also get cloned if I do it that way?
There is no reference to the spawned instance in that script.
You never name the spawned instance (see my message above)
Whatever is on the prefab will get cloned through Instantiate.
A prefab is literally a collection of everything that the object needs to function, so if you spawn it, it spawns everything attached to it.
sounds like I gotta make a new prefab
You can edit/add/remove things from a prefab, just double click it in your project view.
this is my image, which contains the following children. How do I, in the script, make Player(1) and it's children not be rendered?
I have tried set active, get component and a few other fixes, furthermore when I toggle the eye icon in hierarchy view in editor, the image has it's rendered turned off only in editor, not in game view? Please help.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float timer = 0.0f;
private int spawnInterval = 2;
private float rotation = 0;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
GameObject instantiatedObject = Instantiate(PipePair, Vector3(1.8, -5, -0.2), rotation);
}
}
i fixed the script inheritance part
but why is this throwing error?
on Vector3
or Vector2 too
"new Vector3"
Also, you missed the 'f' s after the numbers. You need to tell the code that decimals are explicitly Floats
good point
doubles are cooler anyway
lol.
I think VS is just trolling me at this point
read the error
Rotation is a Quaternion, not a float.
tf is a quaternion?
It's a complex number that represents a rotation
or, should i say how do i turn it to 'normal' rotation?
If you want it to match the rotation of the spawner, just do transform.rotation
Dont worry about it.
Quaternion.Euler(x, y, z)
Creates a Quaternion out of the angles you'd likely be familiar with
or if you want no rotation do Quaternion.Identity
https://docs.unity3d.com/Manual/class-Quaternion.html
https://unity.huh.how/quaternions
If you want to learn more
Quaternion.Identity will get you far enough.
Quaternions are evil though. lol.
lol.
wtf is a w
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Exactly this
You don't need to know to use them properly
I genuinely believe it's named w because Witchcraft
This is true though. The ability to take a vector, multiply it by a quaternion, and get the vector back rotated by that quaternion is fucking nuts.
I think its clearly named after Walter White
Yeah, thankfully the Unity/c# gods put in 'translaters' so you don't have to deal with them directly.
w is the letter in the alphabet directly before x?
then why is it not listed before X in the constructor? HMMM?
There you go being all sensible and logical. lol.
Sounds like a conspiracy.
honestly, legacy. it's the same reason that the a in rgba is at the end
That one is less bad just because the letters are kinda all over the place. Pretty sure RGB is just related to cone excitation, and a came later from alpha in math.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class pipepositions : MonoBehaviour
{
public float upperExtreme = 3.19f;
public float lowerExtreme = -3.68f;
public GameObject PipePair;
private float timer = 0.0f;
private int spawnInterval = 2;
// Start is called before the first frame update
void Start()
{
}
void Update()
{
Vector2 moveLeft = transform.position;
timer += Time.deltaTime;
Debug.Log(timer);
if (timer >= spawnInterval)
{
SpawnItem();
timer -= spawnInterval;
}
}
void SpawnItem()
{
GameObject instantiatedObject = Instantiate(PipePair, new Vector3(1.8f, -5, -0.2f), transform.rotation);
}
}
by the way I changed the GameObject instantiatedObject = Instantiate(PipePair, new Vector3(1.8f, -5, -0.2f), transform.rotation);
There's no funny squiggly line here
Sorry what is your goal?
I want those pipes to start from all the way out of the screen and slowly creep in like the morning sun, not just appear in the middle of the screen out of nowhere
The pipes have a script to move left I assume?
they gotta come in the scene slowly every time
The player themselves stays still?
will get that fixed later, anyway here's the move left script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftMove : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left* Time.deltaTime * 10);
}
}
void SpawnItem()
{
GameObject instantiatedObject = Instantiate(PipePair, new Vector3(1.8f, -5, -0.2f), transform.rotation);
}
I think this has no effect probably
No this is working fine.
You have 2 problems.
- Your pipes are not spawning in the correct location.
- Your pipes are not moving to the left.
Right?
im making a fps character and when the player looks around sometimes the camera will freeze for a second then jolt forward im not sure what it is thats wrong ive stripped my character to just its movement and camera and im still having the issue heres the code for the camera https://hatebin.com/lfrwwqckna i can provide more info if needed
you're saying "jolt forward", meaning it only affects it when you're moving with the player? It has nothing to do with the rotation?
i dont know how to describe it exactly but it feels like when spinning it skips forwards
it happens when not moving
too
so it has to do with rotation?
i think so
it could have to do with variable framerate affecting the sensitivity because of multiplication with Time.deltaTime
You could Debug.Log the deltaTime and see if the jolt corresponds to frame-drops.
or just remove the multiplication with Time.deltaTime and see if the jolting stops.
I am making a python game, only with inputs and prints, and I wanted to make it visual, here is the py code
This game is a RPG with multiple creatures, a market with items, a armory with swords and armor, and 2 secret creatures, one gives you an ending.
you can chose to play hard and normal mode too
{
while (context.performed)
{
Debug.Log("Flying " + context.phase);
}
}```
is "while" somehow not allowed in unity input system? i used it then it straight up just froze lul
yeah it just fucking died
Well, yeah, that's an infinite while loop
Of course it died
so what now i must put that in a fixed update or something?
if i intend it to be "as long as the fly button is held it will fly forever"
Well, no? Just don't use the while loop
The Fly method will be called if it's subscribed to the action
Just remove the while
i replaced the while with an if
(since it is a "hold" interaction)
but now it does only one hop again, fml
This action is subscribed on performed, right?
yeah
There is thus no need for the if (context.performed), as it will always return true if the method is called on performed
brain not computing
would it not trigger while it's cancelled/started if I don't specify if (context.performed)?
If the method is subscribed to the action when the action performed, there's no need to check if it's performed, as it will always be true
ah i see
The same as there is no need to check for started or canceled when called on started or canceled respectively
Performed is called once when the button is pressed, so it will hop just once.
If you want it to fly continuously, you'll have to use started.
wasn't it started -> performed -> cancelled?
I see, yes, I am sorry, I messed up
startedis called when the input startscanceledis called when the input endsperformedis called when the input is in the process and the value is changed
So subscribing a method to your action in performed will call the method continuously
If your method isn't called continuously, your action type might be a Button
i'm in a bit of a loss
i have playerInputActions.MechControl.Jump.performed += Jump; in awake, which is a button interaction
but in public void Jump where i didn't specify it needs to be context.performed it triggers thrice (hence jumped three times simultaneously)
but in the same time i also have playerInputActions.MechControl.Fly.performed += Fly in awake, but this one responded correctly (only triggers once)
im running into issues creating dictionaries. I was working on an inventory system and was trying to use dictionaries. After looking up online, I found an example and just copied and pasted it as it was in the working online resource but I get an immediate error saying openWith.Add(); doesnt exist in current context. also for some reason using namespace std doesnt work either since during my debugging I decided to add that just in case (its system.generic anyway according to the resource so it shouldnt have mattered anyway), but Im thinking something internally might have messed it up. Because im using ScriptableObjects, I have inherited on other files as ItemDefinition instead of MonoBehaviour, and I was thinking that might be it, but not sure. https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-8.0#definition
What is the action's type?
nvm trying again
using namespace std....
Unity's version of C# does not support file-scoped namespaces. You also cannot call non-static methods outside of a method.
If it's a Button, you won't be able to continuously detect the value change
i changed it to value now
but i'm sure i did something wrong since it's still not continuously going up
ty!
File-scoped namespaces are just available from the 10.0th version of C#, which is at least 6.0th version of .NET and not yet supported by Unity
So it was a Button before? Could I see your action and how it's subscribed?
it was a button, but switching to value didn't change anything either
It must change it
Have you saved it?
Alright, now, please, show me how you subscribe it
{
playerRigidbody = GetComponent<Rigidbody>();
playerInput = GetComponent<PlayerInput>();
playerInputActions = new PlayerInputActions();
playerInputActions.MechControl.Enable();
playerInputActions.MechControl.Jump.performed += Jump;
playerInputActions.MechControl.Move.performed += Move;
playerInputActions.MechControl.Fly.performed += Fly;
playerStatsInstance = GetComponent<PlayerStats>();
}
public void Jump(InputAction.CallbackContext context)
{ if (context.performed)
{
if (isGrounded == true)
{
Debug.Log("Jumping while grounded " + context.phase);
playerRigidbody.AddForce(Vector3.up * 5f, ForceMode.Impulse);
}
else if (isGrounded == false)
{
Debug.Log("Jumping Mid-air " + context.phase);
playerRigidbody.AddForce(Vector3.up * 3f, ForceMode.Impulse);
}
}
}
public void Fly(InputAction.CallbackContext context)
{
Debug.Log("Flying " + context.phase);
playerRigidbody.AddForce(Vector3.up * 3f, ForceMode.Force);
}
And Fly method is called just once?
Are you sure the value is being changed?
If it's not, the performed will be called just once
So if the value is (1, 0) -> (1, 0) -> (1, 0) -> (0, 0), the performed is called twice
i'm not sure if i understand
besides even if that's true, that's being called twice rather than being called continuously
if i am understanding correctly that is
The performed is called in Update, assuming the value was changed
private void Update()
{
if (value != _prevValue)
{
Fly();
_prevValue = value;
}
}
why not just Fly() right after it is assigned
What do you mean?
i probably should just put a boolean isFlying = true while it is performed then isFlying = false while cancelled or sth
then put an if argument in a fixedUpdate where if isFlying is true then it flies
mb, didnt realize it is new input system
this is frustrating
for some reason jump doesn't need playerInputActions.MechControl.Jump.performed += Jump; to function
but flying does, would straight up not respond without it
even if both are now button with no state check
guys why am i getting this error with my code?
using UnityEngine;
using UnityEngine.UI;
public class WaterProgress : MonoBehaviour
{
private Slider slider;
private ParticleSystem particleSys;
public float fillSpeed = 0.5f;
private float targetProgress = 0;
private void Awake()
{
slider = gameObject.GetComponent<Slider>();
particleSys = GameObject.Find("ProgressParticles").GetComponent<ParticleSystem>();
}
void Update()
{
if (slider.value < targetProgress)
{
slider.value += fillSpeed * Time.deltaTime;
if (!particleSys.isPlaying)
particleSys.Play();
}
else
{
particleSys.Stop();
}
// Check if the slider value has reached 1
if (slider.value >= 1f)
{
// Reset the slider value back to 0
slider.value = 0f;
// Optionally, you can reset the target progress as well
targetProgress = 0f;
}
}
// This method starts the progress
public void StartProgress()
{
IncrementProgress(1f);
}
// Determines target incremental progress
public void IncrementProgress(float newProgress)
{
targetProgress = slider.value + newProgress;
}
}
Anyone know why gravity doesn't work? 🤔
hi guys i litterally started coding an hour ago could someone help me with these simple codes? I only want it to move once but once i press any of these it just dosent stop going to the directions.
Bro you made it only move with the W key, change the keys as you want
Besides all key checks being the W key, you do not reset the velocity when no key is being pressed.
why would it stop, you set velocity, try adding force
Hey all,
I can't seem to figure this out, would anyone be able to point me in the right direction as to why my 'waveSpawnInterval' WaitForSeconds isn't delaying the next wave in my spawner please?
https://hastebin.com/share/sayidukede.csharp
At the moment, the next wave of enemies spawn as soon as the 'previous' wave has completed doing it's thing. At the minute, the waveSpawnInterval is set to 10 for testing. 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
have you still not learned how to add Debug.Logs' to your code to see what it is doing?
Yeah I have done, but it wasn't any help, it's like it's ignoring the yield. 😕
Show your entire code, not just that fragment
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
bro what is wrong with this code?
why is it red
yes, install them in a non Unity project/solution and then copy the dll's to your unity project inside a Plugins folder
can anyone help me with this error?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class NewBehaviourScript : MonoBehaviour
{
private PlayerInput playerInput;
private PlayerInput.OnFootActions onFoot;
private PlayerMotor motor;
// Start is called before the first frame update
void Awake()
{
playerInput = new PlayerInput();
onFoot = playerInput.onFoot;
motor = GetComponent<PlayerMotor>();
}
// Update is called once per frame
void FixedUpdate()
{
motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
}
private void OnEnable()
{
onFoot.Enable();
}
private void OnDisable()
{
onFoot.Disable();
}
}
Hello, how can i activate this in Visual Studio code? it's says the diferent possibilities of code
Not sure what you mean. Do you want to configure your !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
It's underlined in red, it's configured.
Nothing's wrong with this code
why am i getting a null error thing then
Then I have no idea what they mean
this
Please, show the 20th line
Because something is null
Did you read the resource you were linked?
alright
yeah
and i couldnt find a variable that was undefined or unused
Then you should know why it's null
let me check this code again
!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.
Because it goes through everything over multiple pages
Oh holy shi i did not even notice lol thanks for the advice
https://paste.ofcode.org/F5YQECY7M4wgBmhiiBfGZB
Hi, I tried to do gravity, but for some reason it doesn't work, I think it has to do with being grounded or something...
You're right that the code you've shared is simple. If you're really coding for an hour, please, consider using tutorials e.g. !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
well i dont know why but it works now
thanks alot! i will totally use that
Coding stuff without understanding what you're doing doesn't really make too much sense, it is therefore much better to use tutorials. Good luck!
anyway i have a seperate question now. I have a particle system attached to my slider bar and I want the particles to stay at the end of it and fade when it reaches the end and resets, but right now it does this:
How can I
- make the particles stay at the end
- make the particles show up instantly when clicking again
for the second one can't you just instantiate the particle system again
anyways i just came here to ask my own question
i've got a blend tree and i want to set the x and y values of my 2d free form movement blend tree to inputgetaxisraw horizontal and vertical
how could i do this smoothly
The particles are attached to the end of your scrollbar. Consider not moving your scrollbar at the start?
Not moving it at the start? What do you mean by that sorry?
So smoothly moving the object using horizontal and vertical input axes? Just set it in the Update and don't forget to multiply by Time.deltaTime
nonono
i have a whole rigidbody system already
but i have a model that needs animations
and im using the blendtree technology
to do it
I mean, fix your scrollbar at the end at the end of the movement.
I see, I'm sorry, I haven't used blend trees before, so I cannot help you out
Yes
well it's not really a blendtree issue im having
Does it make an big diffrence if i use the normal 3d and the tutorial is made in URP?
im having a code issue
If so, I have answered you already in my first response
If that's an object, which position is to be set, consider doing it in the Update
oh ok yeah that works, but i still do have the problem of the particles not showing when i click again
pretend there's a slider and i want to smoothly set it to my getaxisraw value, how would i do it
i don't want to move an object
i want to set a slider
Do you know what GetAxisRaw value is?
yeah its the value of a certain axis right?
a and d is 1 and -1 right?
Yes. GetAxisRaw returns -1, 1 or 0 for Left, Right and no key pressed respectively.
How do you plan on smoothly seeting the slider to this value?
Do you perhaps want to smoothly move the slider's value in the input direction?
yeah like if i press a the slider should smootly move from 0 to -1
I see, as I have mentioned before, consider using the Update method
The same way as setting the object's position
so if i get this right
slider.value = input.getaxisraw(Horizontal) * time.deltatime?
float inputDir = Input.GetAxisRaw("Horizontal");
_slider.value += inputDir * sliderSpeed * Time.deltaTime;
Yes
Oh, no
Not with the =, use += instead
alr im gonna try
wait wait wait hold on
input dir is the horizontal axis
and assuming the horizontal axis is 1
wouldn't the slider just straight up go to 1 without any smoothing?
Assuming the inputDir is 1, the slider's value will be increased by 1 * sliderSpeed in 1 second.
that is not what my goal is
i want it to increase to 1 in some amount
Assuming the sliderSpeed is .1, it will take the slider 10 seconds to go from 0 to 1
interesting
Does anyone know the reason for the particles not working after the first click for a while?
Dividing the result by 100 will make you able to assign the sliderSpeed to the precise amount of seconds for the slider's value to be changed from 0 to 1
well theres an issue
for simplification i have set it to change the value of a float
and the value is not changing
What does it mean?
that is what i have done
what does what mean
This line of code changes the slider's value from 0 to 1 in 10 seconds when the D key is pressed, assuming the animatory is the property assigning the slider.value to value
no i did
the float works
but there's an another issue
there's no cap to it
and that it won't return back to 0
okay so basically its a float i have used to control the slider value
why, apart from what is obviously not your code, do I see no attempts to debug in your code?
Is it a property?
im just using a slider example since you haven't used blend trees
what do you mean by that
sorry i don't know what property means
Please, show the animatory
Does changing the animatory change the slider's value?
yes
Alright, got it, you assign it in the Update
yes
your thing works but it doesn't go back to 0 when i let go
Why should it go back to 0 when you let go?
isn't horizontal axis 0 when there's no key pressed?
Yes
that's why it should go back to zero
It's not usually how the sliders work, but let's suppose you have a special one
what?
interesting
alright wait let me tell you my reasoning behind this
Interesting? I said that sliders don't go back to 0 when no key is being pressed
Yeah, tell me
well we gotta make one that does
this slider is being used to control the animation my player is currently using
the animatorx. if it is 0 then the player will idle, if it is 1 then he will walk left
and same for the animator y
if it's 1 he will walk forward
-1 he will walk backwards
so it is crucial it goes back to 0
if it doesn't then the player will keep walking regardless of no keys being pressed
Is it supposed to smoothly go back to 0?
yep
yeah i want to configure that, the image is from a video i don't have that
Sure it does
You'll have to calculate the distance, that's the best way on my opinion
are youbeing sarcastic?
No, it's not sarcasm. You should normalize the axis gotten
well it really does cause when i press A it smooths to -1 and then if i were to press D fast enough it snaps to 0
then it smooths to 1
Alright, let's return back to setting the slider's value to 0 when no key is pressed
what is your slider's range?
is 0 its start?
well the x value can go as less as -1 and max to 1
the y however
-1 and 2
since there is running involved
Oh, alright, so 0 is the middle of your slider?
yes
i've tried lerping before
but it would do some weird stuff when it tried to go back to zero
somehow even going to a value called E?
sorry brb my mom calling me down
E is just a part of the scientific number notation(used to represent small numbers usually). It doesn't mean that there's an issue with it, as most numbers can be represented like that.
Can't understand that error message. They should really stop translating them to other languages...😅
but it shouldn't be E it should be 0...
It probably means that it's very close to 0. Don't know the context, just saying.
yeah but the thing is it's suppose to go to zero but gets stuck at E
Share the relevant code.
Why do you think it's supposed to go to 0?
well uh
it's long gone now
but basically the whole thing i was trying to do is make a slider follow the horizontal axis
and smoothly go to the value
do you have any other way that could work
instead of lerping it like i did
When you lerp incorrectly it would often result in a number with E.
so you're telling me i did it incorrectly?
Because you never actually reach the target value.
Everything following the E would be the exponent so if you're operating with floats, the value could be some arbitrary small number (negative exponent) - zero is near impossible to acquire unless working with constants or assigned directly.
Most likely. I didn't see the code, but it sounds like it
how about i recreate it and send it?
Sure
if you use the lerp as moveToward (by giving it constant value) it will get closer and closer but won't reach the value
maybe that was what you did
why not use moveTowards instead?
sorry what is movetoawrds
if you give lerp a constant value it wont work right
the value of the lerp usualy must change
Yes, that's incorrect lerping
use MoveToward instead
sure
those statements are pointless as you do not capture the return value
uh what sorry
I don't think that does anything as Lerp is supposed to return a value that you'd assign to some variable.
you pass values INTO the Lerp but you do not get the Lerped value back. Try reading the documentation
Neither does that
this is getting a bit overwhelming
animatory = ...
no, lerp is start, end not current, end
and blendspeed must be * Time.deltaTime
thats why I said use moveTowards and not lerp
Example:cs speed = Mathf.Lerp(original, target, progress);
why lerp?
okay so
the x value works correcty
but the y value doesn't
nvm it does
i forgot to save
okay movetowards works
thank you very much
sorry for bothering all of you
im not even joking this literally gave me a headache all night
guys im having trouble with vscode right now i think?
I'm trying to make variables and they don't show up in the intellisense/autocomplete and unity says they dont exist
do u have the needed using statement?
Why does the "SelectByClicking" Become an error
because it is outside the scope of the class
Found out
Why is it rotating so weirdly?
public class BallVisual : MonoBehaviour
{
public float rotationSpeed;
private Vector2 moveInput;
private Vector3 moveVector;
public float maxRollingSpeed = 100f;
public float acceleration = 10f;
private float currentRollingSpeed = 0f;
private bool isRotating = false;
[SerializeField] private Transform sphere;
void Update()
{
if (moveInput.magnitude != 0)
{
if (!isRotating)
{
StartCoroutine(AccelerateRotation());
}
}
else
{
StopCoroutine(AccelerateRotation());
currentRollingSpeed = 0f;
isRotating = false;
}
sphere.Rotate(Vector3.right, currentRollingSpeed * Time.deltaTime);
}
IEnumerator AccelerateRotation()
{
isRotating = true;
while (currentRollingSpeed < maxRollingSpeed)
{
currentRollingSpeed += acceleration * Time.deltaTime;
yield return null;
}
currentRollingSpeed = maxRollingSpeed;
}
void FixedUpdate()
{
RotateInDirectionOfInput();
}
private void RotateInDirectionOfInput()
{
moveInput = InputManager.Instance.moveInput;
moveVector = new Vector3(moveInput.x, 0, moveInput.y);
if (moveVector != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(moveVector, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
}```
Why..
do u have a class called UnitMovement ?
Have you tried locking the rotation on the gun?
No
!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
whats taht?
oh
i have using unity engine and unityengine.ui
isn't the values too high?!
TMP_Text requires the TMPro; using statement
Gun?
well thats why... ur IDE is telling u that class doesn't exist .. so its impossible to grab it from any game object
then you are not doing it correctly or fully
@lethal bolt the stick is just showing us where the ball is going towards
OH
it's only weird when changing directions
It's quite simple really, if you were doing it correctly and fully it would work therefore. qed, you are not
nothing other than follow the steps shown
theres not an alternative.. we'd just suggest going back and trying it again. each and every step
But the UnitMovement is an script.
when its successfully setup where it says Miscellaneous Files will say Assembly-CSharp
is the class name also UnitMovement ?
But you said you did not have a class called UnitMovement though? #💻┃code-beginner message
public class UnitMovement : MonoBehaviour {
well thats why.. ur class name should probably match ur scripts filename..
then how do you expect to reference something called UnitMovement?
unit.GetComponent<Script>()
guys how to detect click in text mesh pro using c#
Thanks!
It'll provide immediate satisfaction but the actual solution would be to change the class name to something relevant.
i want to create a property system in my wild west game if a user clicks on the purchase button he should get the property
i agree, its much easier to see ur filename MyScript.cs and know that the class is named MyScript w/o having to open it up and look
I changed it to UnitMovement insted of script
I am sorry, urgent stuff happened so I couldn't continue sending the solution I wanted.
You should calculate the offset between the current and desired positions.
I am writing from the phone, so I hope there are no miscalculations. Slider's value is smoothly moved to 0 when no key is being held.
float inputDir = Input.GetAxisRaw("Horizontal");
float offset = slider.minValue + (slider.maxValue - slider.minValue) * .5f * (inputDir + 1) - slider.value;
slider.value += MathF.Sign(offset) * speed * 100f * Time.deltaTime;
You can hold the proprieties in some singleton static class and access them from the button script.
If you want these to change something dynamically in player you can use delegates that you call on changing that variable linked to function inside other scripts.
im new don't know the meaning of any of these singletons ,delegates
Google singleton implementation
singleton is like a gamemanager for example.. only a single instance of it exists.. so its easy to access via anywhere thru-out ur code
You can hold some global variables in it to pass to next scenes, quite convinient
https://gamedevbeginner.com/singletons-in-unity-the-right-way/ a good beginner source to familiarize
both are worth learning.. singleton more than delegates for now
yeah delegates can be left for later.
so meaning it can't be typed twice ? like int x; x=2;
It means only one instance of it exists ever.
well there wont be two versions of it anywher
like u could have an enemy class and spawn it 10 times. (each version is its own instance)
a singleton would only ever exist once.. and a singleton is more of the entire class..
a static variable is similar
Well in unity its a static instance inside the class.
So singleton is mostly about class
Add a collider and either poll using raycast, use the OnMouseOver callback https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html or use the pointer click callback https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Button.OnPointerClick.html
any idea how i can set this to read/write enabled true?
btw do scripts run in the background if the object is cull my game is open world and it will have probably 100+ scripts
if object is gone it wont run any scripts.
in the import settings iirc
collider on button ?
beware that if you link any functions (new unity input system per example) you will have to unlink them on destruct.
how do i get to this screen?
selecting the FBX in the project panel
If it's a button just use the button event system from the inspector. I had thought you were using some of the other tmpro ui object (text and whatnot)
ty @rocky canyon
so i built my game and although it runs 150+ fps (it feels like) in the editor, in the actual build it starts with a lot of framedrops and then it goes to like 5fps and lags out comepletely
i removed all grass and flowers in case that was the culprite
but i still have the issue
the game is very small i dont think it should have issues
Start by profiling your game properly. That way you can find out what part of the game is slowing it down the most
Hey, I have little problem - I changed Tile type to custom, extended TileBase and now colliders don't work, like they don't exists.
ill watch a tutorial on that
Okay - next question - I already changed collider type to sprite but it made another problem - game is lagging as hell.
Is there any option to set tile data globally without using tilebase?
my player slides too much and if i make the drag higher the player falls to slow im not using colliders for collisions but a script that changes the velocity when on the ground and turning gravety off mybe thats a problem the drag is 1 and in another project the player doesnt slide that much
Hello! (I'm new to Unity)
I'm making a game for a school final project and I've been trying to work on this piece of code for a while.
It's a doodle jump style game and I have a box following my character as it moves upwards through the game. I want this box to collide and destroy my platforms once hitting them so that when my character falls down the level it doesn't hit one of the platforms.
so which part are you having trouble with?
I've tried lots of different code off of the internet, and none of them are destroying my platforms.
I'm really unsure what I'm supposed to attach my script to really.
have you written any code on your own? any prior programming experience?
you could start by googling "how to detect collision between objects unity"
then go from there
The programming experience I have is based around school exams, so sadly it's not very useful to game creation. I've mainly used Python too, so my knowledge of C# has been off of creating this game and a small amount of previous knowledge.
you at least understand variables, data types, functions, if statements and for loops?
That's the problem, Ive tried tutorials, forumns etc... and none seen to work.
Let me try another tutorial and copy and paste my code and I can see if you can spot anything wrong with it?
Yes I do.
you're not special. code just doesn't stop working for you
it's not working because you probably don't understand what you're doing
In this tutorial we discuss adding colliders on our objects so that we can detect collision within our script.
SUBSCRIBE: https://bit.ly/2Js78lE
In this video, you will learn:
0:55 - Choosing the right collider for your environment
1:05 - How a collider works
1:30 - 2D and 3D colliders to use
2:05 - Adding a Circle Collider 2D
3:35...
try this one
Well yes as I mentioned above I am new to Unity, this is my first project ever on it, and I've been trying to find code related online but are not working and I'm following the steps exactly.
Will do, thanks.
and in case you haven't come across this, there's a beginner scripting course from Unity
https://learn.unity.com/project/beginner-gameplay-scripting
and this is a site that will help address most common issues
https://unity.huh.how/
Oh awesome, thanks man :)
the 321 Animation UI gameobject has an animation with an animation event, in that event i wanna run a method but the method is in the script on the Game Manager, what is the best way to tell 321 Animation about the script that the Game Manager has?
Hello, im making a building system but i encountered a problem. How can i make a gameobject only visual and not have any scripts or rigidbodies enabled. Should i create a "enabled" bool value inside every object and disable it when they are placed?
Maybe have the prefab with disabled components (kinematic for rb)?
Isnt that the same with disabling it when placed and enabled when the game starts? I want to enable the components back when the game is started
or have a separate prefab just for the building visuals where it's just the mesh and the material that probably makes it transparent (since that's common for building mechanics)
then when the building is placed it spawns the real one with the working components on it
Do you guys use euler integration for movement? Or is it recommended to go the verlet route?
Pretty much but without you needing to disable everything after placing
Okay i will just disable all components when placing and reenable again after starting the game, thanks
@sour yew what's this Setup method you're talking about?
hey guys. i have this script:
public class ToggleInventoryCanvas : MonoBehaviour
{
public GameObject inventoryCanvas;
// Start is called before the first frame update
void Start()
{
inventoryCanvas.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
inventoryCanvas.SetActive(true);
Debug.Log("AAA");
}
}
}```
but when i press TAB, it doesnt make the canvas appear. can smb help me out? thx
sorry. I meant Start method in this class
it's fine its fixed
Does it log AAA?
Is this script ON the inventory canvas?
if Start method is empty, it does, but nothing happens to canvas. if Start method isnt empty, nothing happens at all
Is the script on the inventory canvas?
Can it be disabling itself?
are you certain you aren't perhaps ignoring an error in the console?
or if this is still a child of the object being disabled, then of course it won't log anything when tab is pressed because it is still being disabled too
It does log it if Start is empty because he doesn't disable the object
I think the issue is already resolved in #💻┃unity-talk
anyone?
animation events will only call methods on the same object. so you need a method on that object that will listen for the event and call the relevant method on that other object
so there is no way around it, i have to give it a script
yes because the animation event cannot call a method on a completely separate object
yep. as i now understand, its indeed disabling itself.
Does anyone know what would caused the player to not be able to hit enemies?
I have a Collider on the Enemy, a polygon collider on the sword animation for the player, the polygon collider is a trigger, and the knight enemy is not invincible. What else should I look at?
- Either of them should have the
Rigidbody - The
OnCollisionEnterorOnTriggerEntershould be used if the object with the script hasisTriggerdisabled or enabled respectively
you've not really provided enough context to actually know what isn't working, but i'm just going to assume you are not getting a physics message like OnCollisionEnter or OnTriggerEnter so go through this: https://unity.huh.how/physics-messages
Yes I'm using OnTriggerEnter2D
They both do
then go through that link
ok. when the game starts, theres no canvas, when i press TAB, it appears, but when i press the TAB again, it doesnt go away. i was thinking about smth like this:
public class ToggleInventoryCanvas : MonoBehaviour
{
public GameObject inventoryCanvas;
public bool isIntentoryCanvasEnabled = false;
// Start is called before the first frame update
void Start()
{
inventoryCanvas.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
isIntentoryCanvasEnabled = !isIntentoryCanvasEnabled;
inventoryCanvas.SetActive(isIntentoryCanvasEnabled);
Debug.Log("AAA");
}
}
}
it works. TAB enables and disables the canvas. but the last thing im worried about is accessing field var directly. shouldnt i be using setter?
Why are these fields even public to begin with?
the bool isn't necessary at all btw, you can just access the activeSelf property on the inventoryCanvas gameObject
idk. everyone makes the fields public in unity for some reason. idk why theres no incapsulation in the tutorials haha
can u explain?
I go back and forth with people on this. But I only recommend using a getter / setter if you need to. I.e. if you need to do something more than a basic set and get. Such as if null, do a findobjectoftype or something. I do not recommend using them if you do not need to.
because many poorly thought out tutorials don't know that you can use the SerializeField attribute to expose a non-public field to the inspector
Tutorials are dumb, if you see something dumb you correct it (unless you watch it till the end and it does have a use, but bad design either way)
...SetActive(!...activeSelf)
inventoryCanvas.SetActive( !inventoryCanvas.activeSelf );
read the docs for the property i just told you about
I use activeInHierarchy to check active state
Note, the ! (not) prior to active self
It's wrong in their case
so what should i use then? make fields private and use setters/getters? or keep them public but also serialize them?
make them private and also serialize them
use properties to expose those private fields to other objects
{
if (Input.GetButtonDown("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else
{
moveDirection.y = -gravityForce * Time.deltaTime;
}
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
}```
Why doesn't gravity work?
One returns local, the other the global active state. They didn't specify what they want so I just commented
It was specified on the code block shared above. They're enabling the object, so it doesn't make sense to check its activeness in the Hierarchy
You mean serialized private fields?
What?
public fields are serialized by default if the type is serializable
Also idk what you'd need setters and getters for here since you probably don't need to access these fields outside of that script
Oh I just realized what happened lol mb
When choosing the access modifier for a field, use
privateif it should just be accessed within the classprotectedif it should also be accessed in the derived classespublicif it should also be accessed in all the other classes and serialized in theInspector[SerializeField] privateif it should be serialized and just accessed within the class[SerializeField] protectedif it should be serialized and accessed within the class and its derived classes[HideInInspector] publicif it should be accessed from anywhere, but not serialized
public fields are serialized by default , no? You would need to do [HideInInspector] to not see it
public is serialized by default, no need to add [SerializeField]
You're right, it was a huge type. Corrected.
Yeah now it makes sense
In context of serialization, this would be more appropriate:
https://docs.unity3d.com/ScriptReference/NonSerialized.html
I see
hey so for level design purposes I need to know how much distance my character travels per second. I use a 3D vector and a character controller to move my character and I debugged the vector I used, the max value obtained on 1 axis being 10, now I want to know how to convert this information to actual distance/second and idk how
Vector.magnitude returns the length of the vector
is it better to do everything in a single script whenever possible (such as statuses, cooldowns combined with control script as one), or it is better to do everything separately?
I like to keep it easy to read and do different behaviour in different scripts. I think it is generally seen as better to do so
ok I understand but how does it translate to distance traveled?
per second I mean
You basically want to know the velocity, should be easy if you had Physics in school.
You dont need an inventory system in your character movement for example, it's just 100000 lines of code and noone including you knows what is where at some point
- Time.fixedDeltaTime
Depends on how you did your movement. If you move by a vector * speed * Time.fixedDeltaTime, then (vector * speed * Time.fixedDeltaTime).magnitude should return the value per second (correct me if I'm wrong)
That's per fixed delta time, not per second.
Divide the distance traversed by the time elapsed and you get velocity
yeah but idk how do I measure the distance traversed
Well, it's basic math
I'm not familiar with the Character Controller that comes with unity, but you can just attach a script to your player, save the old position, and get the distance to the new position and divide it by time
I mean it's kinda the same what you move, if you do _Controller.Move(_Speed * Time.fixedDeltaTime * _MoveVector), with _MoveVector being normalized, then you move "_Speed" units per second
If the distance is 10 km and the time is 5 hours, the velocity is, obviously, 10 / 5 = 2 km/h
What do you do if you aren't receiving either message? They're both Dynamic body types, they both have rigidbody's, I've verified my OnTriggerEnter2D and OnTriggerExit2D are correct, there's a high likelihood my functions are correctly formatted because they work for the enemy, my Physics 2D is correct and they should only be able to attack the enemy hitbox (I have it set as "PlayerHitbox"), I'm not using a transform.position, and I'm not sure Continuous collision will matter as they aren't moving that fast, and there are no errors.
What else is there, I've looked over most of this stuff and it seems to be all correct?
obviously but I know neither the distance or velocity, only the time
What's the time?
Is one a trigger collider?
the link i sent goes through all of the necessary steps
They both are
worst part is that my character has acceleration too, so I need to reach maximum velocity before I start to measure the distance
anyways thanks for the help yall, gave me some cool ideas
private Vector2 m_prevPos;
private void Start()
{
m_prevPos = transform.position;
}
private void Update()
{
Vector2 currPos = transform.position;
float distance = (currPos - m_prevPos).magnitude;
float velocity = distance / Time.deltaTime; // Now just debug it or whatever
m_prevPos = currPos;
}```
Well, how do you reach the maximum velocity before measuring the distance, if, in the solution suggested, you cannot calculate it without knowing the distance?
Yes, thats why I dont let them collide using Physics 2D
You indeed can
Yeah I send the link in
I'm not sure what to do then, as i'm fairly sure everything on the website boxfriend sent is correct
how can I make the texture look high quality? it always comes out blurred like this
ok so let me explain as clear as I can.
My formula goes something like
speed * direction *time. deltaTime - deceleration vector (which is just the vector in the previous frame /5)
I know all these values and can measure them over a period of time. but as far as I know the physics in my game updates 60 times a second, so in the end I have no idea how does all this convert itself to distance
This is how I set up a controller yesterday. currentSpeed is the units/per second I move (horizontally)
// Check if running
_IsRunning = IA_Controller.FPS.Run.ReadValue<float>() != 0f;
// Calculate the current speed
float currentSpeed = (_IsRunning) ? _Speed * _RunMult : _Speed;
currentSpeed += _SpeedBoostAmount;
// Set the movement Vector
Vector3 moveVector = (_InputVector.x * transform.right + _InputVector.y * transform.forward).normalized;
// Set the gravity Vector
Vector3 gravityVector = transform.up * _YVelocity;
// Move the character controller
_Controller.Move(currentSpeed * Time.fixedDeltaTime * moveVector + gravityVector);
one way to do this is just debug the value itself, wait for it to reach max value, and then just do a checkpoint there, and another one second later, then get the distance between them which is what I'm gonna do
@modest dust thanks for the suggestion
Works aswell
Well, you don't need Time.deltaTime for the velocity
neither do you need the distance nor time in your case
Just multiply the distance with the speed and you get the static velocity
You need to use Time.fixedDeltaTime if you want stable 60 fps
Also you need to check your fixed timesteps, I think the default is 50fps
I thought that using time.deltaTime would make the character run at the same speed whether I have 60 or 600 fps
from my tests so far that checks out too
Already did so
Just the interval in seconds from last to current frame
If you call it in FixedUpdate, it retuns fixedDeltaTime tho
Looks great, but you can calculate the moveVector and the currentSpeed is an easier way
Vector3 moveVector = (_InputVector * (transform.right + transform.forward)).normalized;
currentSpeed = _Speed * (_IsRunning ? _RunMult : 1) + _SpeedBoostAmount;
"deltaTime inside MonoBehaviour.OnGUI is not reliable, because Unity might call it multiple times per frame."
Thx
Hey guys, i have some scrolling set up on my game screen, but i want it to work when my mouse is anywhere, not just over the buttons/gameobjects in my scene.
you can see in the video it scrolls when my mouse is over the gameobjects, but not the background
Use a parent object with raycast hitbox
Using Time.deltaTime or Time.fixedDeltaTime depends on whether you're in the Update or FixedUpdate respectively
Well apparently Time.deltaTime returns Time.fixedDeltaTime when used in FixedUpdate
Just learnt that here
what does that mean
UI Elements have raycast padding. Boxes that check if your mouse is in them and behave accordingly. If you want to enable the full screen to drag, you can just put a big UI element such as a panel with transparent color as parent to all other UI elements
You're right, I just checked it out and that's really so, I haven't known it a minute ago. Thank you
Np, me too
I thought the Update's deltaTime being returned when using in the FixedUpdate
Yeah me too
So it makes no difference whether to use fixedDeltaTime or deltaTime in the FixedUpdate
Yep
Only question is when to use Update or FixedUpdate. For movement I do everything in FixedUpdate, for input reading I use Update and if I need to check values every second, I just use an IEnumerator
And LateUpdate for the camera movement
Well yea, only I use cinemachine so I don't code camera movement
It's such a bliss
Free camera behaviour, one of the best packages imo
Works great with POV using a little workaround I came up with
I, honestly, hate using Cinemachine. I always love to code everything on my own and doing stuff with Cinemachine just makes it more complicated for me
Well I do code some stuff, such as camera speed and changing active virtual cameras
You'd assign a value to the fixed delta time if you want the occurrence to change - relative to the physics step. Other than that delta time would change per frame accordingly to where it's used (physics and regular frame as far as I'm aware).
And a bunch of bugs when used wrong, which is how it's used by me
Well then use it right xD
Everything will produce a bunch of bugs when used wrong that is true
I added a raycast component to my empty content gameobject which parents all of my content and buttons but it still doesnt scroll when im not over the buttons
Try adding a new gameobject UI > Panel
Size it up to fit screen with width and height (probably 1920x1080)
Yes, so using them in the FixedUpdate, other than Update, will result in exactly the same behavior
Well, you want it to be the raycast target? Then use the Graphic component with raycastTarget enabled
thank youuu idk why it worked but it did
Because it has Graphic, which the Image on the Panel is derived from
btw careful with disabling Imagecomponents, it has a raycast target
Personally, I'd only use delta time unless I'm needing to read the fixed value of the physics delta time in Update or changing the value of fixed delta time - delta time is read only whereas you can make assignments to fixed delta time.
Well fixed delta time scales with Time.timescale. So if you want to control stuff with one simple value it's easier to implement
Yes, you can only assign the deltaTime with the Application.targetFrameRate
(which still won't give you the desired frame rate when set to 10k)
Nearly everything scales with time scale (excluding unscaled members) but modifying the fixedDeltaTime property would exclusively change how often the physics step occurs.
mmh. Wait i think i may have solved it let me check..
What're the settings of the scroll area?
yup i had to change the size of scroll area
i didnt realise cause the tutorial i was watching skipped that
I'm using Graphics.DrawMesh to draw the meshes of my chunks, but I want to make it so it doesn't draw the chunks that are outside of the camera, how do I do that?
do I just assume the camera is a square and check if the camera bounds and the chunk bounds intersect or not?
What you are after is called frustum culling. There is a utility function to get the planes for a given camera https://docs.unity3d.com/ScriptReference/GeometryUtility.CalculateFrustumPlanes.html. You would then do a intersection check with them.
I think that is for 3D?
It should work for a ortho cam as well
Then again I have not done 2d so I dont really know
{
if (Input.GetButtonDown("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else if (characterController.isGrounded)
{
moveDirection.y = gravityForce * Time.deltaTime;
}
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
}```
Anyone know how to do gravity after the character jumps??
First of all, you can delete the characterController.isGrounded.
But then it won't let me jump for some reason
hello i wwant to make some sprites for my game and i dont know which apps to use
You have 2 grounded checks?
Grounded and characterController.isGrounded
Then you permanentely add gravity, unless you are grounded
Yes, my mistake, I deleted it
So that's right
You also have to reset y velocity to 0 if you are grounded, and the y velocity is below 0
{
if (Input.GetButtonDown("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
}
}```
bcs if you set it to 0 when grounded, you couldnt jump lol
You could use piskel for pixel art
https://www.piskelapp.com
Online and app
Piskel, free online sprite editor. A simple web-based tool for Spriting and Pixel art. Create pixel art, game sprites and animated GIFs. Free and open-source.
alr thanks il see it
Paint.NET is free image and photo editing software for computers that run Windows.
Official page, it's better than MS paint or paint 3D
(unless you want to view 3D stuff)
@hot palm Something like that?
{
if (Input.GetButtonDown("Jump") && canMove)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else if (moveDirection.y < 0)
{
moveDirection.y = 0f; // Reset Y velocity when going down and grounded
}
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
}```
Nice was going to comment xD
Well why use canMove
Is it for pausing player movement?
Or for checking if he can walk on xz plane?
Oh, i need it, it's related to animations
Aight
No, but ignore it, it doesn't bother you, the log works
Now there is no gravity at all 🥲
Is your ground check working properly?
No because when the game starts the character just floats
Add gravity outside this if statement and see if it works
Or do you see the moveDirection.y going down or not
You can check debug inspector if it's a private vector3
How my controller works
// Calculate y velocity
if (!_IsGrounded)
{
// Add negative y velocity
_YVelocity += _Gravity * Time.fixedDeltaTime;
}
else if (_YVelocity < 0.0f)
{
// Reset y velocity
_YVelocity = 0.0f;
// Reset jumps
_JumpsAvailable = _MaxJumps;
_CanJump = true;
}
I just changed this line:
if (characterController.isGrounded)
to this:
if (Grounded)
Now there is gravity but when I jump, there is no gravity
How do you check if the controller is grounded?
{
float raycastDistance = 0.1f; // Adjust this value based on your game's scale
return Physics.Raycast(transform.position, -Vector3.up, raycastDistance);
}```
Hm just copy paste your !code in the player move script to a website here and send the link
📃 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 think we're missing something important
Yup, but except for the part of the jump
Well firstly please for the love of god use [SerializeField] private and not public
all the [SerializeField]??
whats wrong with public? 😵💫
Just invites you to cook some spaghetti code
I don't think there's anything wrong with them using public
All fields only used in the own class/script should be private
Nuhuh 🗣️
Well you can do what you want
you cannot blame the quality of ingredients when a bad chef cooks with them
But ppl working with you will thank you
I don't think it matters, I just need the jump code
Yeah just what I saw
Yes, putting [SerializeField] private instead of public won't fix the issue, whatever it is, as I haven't read it yet
So for now the code is:
{
if (Input.GetButtonDown("Jump") && canMove)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else if (moveDirection.y < 0)
{
moveDirection.y = 0f; // Reset Y velocity when going down and grounded
}
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
}```
The problem is that there is no gravity after the character has jumped and it floats
use debug logs
see if the code is executed
bcs I don't see any apparent reason it shouldn't
he does
moveDirection.y -= gravityForce * Time.deltaTime;
``` does?
I get a notification when I jump
Well, of course there is no gravity if you don't seem to change the Grounded boolean
- if y velocity is changed
Ok, you're right, it's not responding
True
Bcs you never call the boolean
There is gravity! But not when I jump
Because it's being applied when not grounded
Just do this before the if statement
isGrounded = Physics.Raycast(transform.position, -Vector3.up, raycastDistance);
You never call IsGrounded(), do you?
Where's the mask?
This is a function he uses
This is his code
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -transform.up, out hit, 1f))
{
return true;
}
else
{
return false;
}
}
}```
Does this look correct?
I am not sure why this return false
If the transform.position is higher than 1 above the ground, it never collides with it
transform's y is 0 btw
Does the code provided refer to your own issue?
Local or World?
world
Well just do it in one line
_IsGrounded = Physics.SphereCast(transform.position, _GroundCheckRadius, -transform.up, out RaycastHit _, _GroundCheckRange);
This is what I use
Gotcha, let me try this
It's going to return false if the Player doesn't have the Collider and the distance from its center to the ground is smaller than 1
yeah
{
return Physics.Raycast(transform.position, -Vector3.up, raycastDistance);
}
private void Update()
{
Grounded = IsGrounded();
if (Grounded)
{
if (Input.GetButtonDown("Jump") && canMove)
{
moveDirection.y = jumpPower;
Debug.Log("Jumping!");
}
else if (moveDirection.y < 0)
{
moveDirection.y = 0f; // Reset Y velocity when going down and grounded
}
}
else
{
moveDirection.y -= gravityForce * Time.deltaTime;
Debug.Log("Hmmmm");
}
}```
something like that?
Yeah
yes or no? 😂
But you can just do it in the line
LayerMask is not necessary if you want to walk on everything
+with a collider
It's necessary if your player has a collider
I didn't forget, and it still doesn't work. No gravity at all.
You obviously did
Depends, if you start below the player it never collides
this is also returning false ;-;
They start in the middle of the player though.
Try playing around with the values
This line yes
you need to learn how to debug, you have 2 unlogged paths in that code
Just talking about in general
The code they provided works. You should provide more details about how you're using it
i have a bullet script and even though i am trying to make it dissapear when colliding with an object it just phases through. ill link code here: https://gdl.space/tuqulugoqu.cs
Because the Bullet is a trigger
You should do an OnTriggerEnter instead of OnCollision
Start at the bottom then
ok ill try
But I started from the bottom 💀
It does not return true when grounded then?
Okay, so y value = 0, Its false
But for any y just a bit greater (0.00001), Its true
then do 0.2f or something
What value are you talking about?
No, simply when the game starts the character floats
So obviously there will be no ground
The transforms y position
The players transform
which is at y = 0, initially
What is the radius?
0.3f
And what are you trying to detect?
Just a plane with meshCollider
can someone who is quite good with unity dm me? please tell me if that's against the rules to ask
set both colliders to is trigger and still doesnt work https://gdl.space/zelodexawa.cs
Only one should be a trigger
not exactly against rules but doubtful anyone will take such a commitment
you're better off stating your issue and someone may help if they know how
i tried that aswell
Kk
you can cntrl+ f and search for my name
does one of em have a rigid body?
neither?
I tried getting help in this chat in the past
there you go. you need atleast 1 to have a rigidbody component for collision to be possible
ok ill try that
is there is post area for 'help' here?
Okay solution: Dont subtract gravity (-9.81f) from your y velocity 😂
I mean just about everyhere where depends if it's code or graphics-wise
it's code wize
still doesnt work do i have to use gravity
I think you are better off reading into unity documentation
@hot palm 👑
Thank you!
how can i stop these from spawning under the main camera?
I'd say overthink why they're spawning there to begin with. You can tell them to spawn between 2 specific heights
I spent the last 15 hours working on a project, and I know the basics now, but I have several issues,
I would love if someone would take some time to Help me figure up the solution for thsi code (I made the base, then put it serveral times in chat gpt (I started learning Unity TODAY.))
sorry for the chunk of text
if someone is willing to help me, here is the code
you keep saying I need help but not explained the actual problem.
Something like
private float _spawnAtX = 20f;
private float _maxHeight = 10f;
private float _minHeight = -10f;
yourGameObject.transform.position = new Vector2(_spawnAtX, Random.Range(_minHeight, _maxHeight));
First of all I would recommend making a new script for each class
hello i made a renderer place him behind the button in my canvas but the game still think he is infront of and i cant click the button any idea why?
Order in hierarchy is important
Parent
- Background
- Button
You would want it like this
it
Yeh wrong order
oh thanks
That's the thing, I am VERY new, I tried figuring out the bugs that it throws at me, but there is
no more bugs,
The main problem is that When I click 'Next' after I go into the part when I need to enter 1,2 or 3 to progress
in the creature fight, I can't choose anything
send the !code properly by using links
📃 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.
This is a very specific problem and I recommend redoing all your code to make it readable for yourself and others
Or try to send your code and have luck with someone trying to solve it
(using a website and paste website link here)