#💻┃code-beginner
1 messages · Page 130 of 1
Showing something in the inspector isn't the only purpose of using 'public'. Read about encapsulation
showing them in the inspector and using them in other programs and classes*
public fields are serialized by default in the inspector, other than that it's just about the access
but what's the point of making things private if they don't affect anything?
I'd like to check if a list contains every value in either an array or another list using just an if-statement. What would be a good way to do this?
encapsulation.
it's just faster to make everything public
gotta read it
And more prone to bugs that are very complicated to solve
Read about ensapsulation, it's worth it. Most fields should be private (or protected/internal)
do you know what is hash table
searched in the unity docs but found no results
Encapsulation isn't a unity thing.
i haven't studied oop yet tho
in the learn.unity pathway there wasn't oop
there actually is, but just one chapter iirc
Just search for "C# Encapsulation" or simply "Encapsulation"
Unity uses C#, which is an object-oriented programming language. So literally everytime you program in Unity you're using oop
whats confusing about it? I would suggest learning basics of programming before getting into unity.
I would spoonfeed you code but that probably wont be healthy for you either. And I assume you're asking here because you wanna learn rather than just getting spoonfed code that could be provided to you by chatgpt or elsewhere 😄
ik that script are classes and every component is a class too
yea would highly recommend learning the language (which includes oop) before game dev. It's gonna end up saving you so much time and headache haha
i come from python, there i learned about oop, i also did a full course with classes too, but since i hadn't used them ever since i forgot about them
i see
i did a course about it which included classes, but since i never used them in 2 months i forgot how to even make one
I looked it up an kinda understand I think? Is it like a mix between hashset and dictionary?
(already posted this yesterday, but maybe someone can help me today ;) )
Yo! I have a problem. I have created an empty game object (a pivot) as a parent of a Camera. When I'm not in play mode if I rotate the pivot the camera rotate around it like supposed, but when I'm in play mode it doesn't work anymore. The camera rotate around itself. I don't understand why. I didn't find any solutions on the internet. Can you help please?
Edit : Someone told me to remove "* Time.deltaTime" so now this isn't in the code naymore
i cannot remember stuff without using them at least a bit, in fact i hate latin and can't remember anything
hash table is data structure, it is just a name to desrcibe something that can offer you a O(1) lookup for given key
dictionary is hash table (or hashmap)
Well, in Unity you will have the chance to use oop a lot
but where is the pathway chapter with classes? i finished it but never used them
btw the name is not important
I dont know, I just took a C# course before getting into Unity. I didnt use Unity learn, short tutorials were enough for me as I already knew C#
Just researching about what I want to do before actually doing it works for me
it took me 2 months to do the pathway since i am 16 yo, so it's been 2 months since i have even read about a class
i wanted to do a full course so that i could know about a lot of topics if i needed to use them
is this script on the pivot or the camera?
also keep Time.deltaTime or else the camera will rotate faster for the person with higher FPS than a person with a lower FPS.... unless that's what you want.
On the pivot
Someone told me that's not the case because the mouse Delta is already in Time.deltaTime
Well, thats not a bad idea, but I recommend you to also research yourself, don't just stick to Unity learn
ohh yea new input system, yea idk much about it so it probably is lol my bad
np
And something I didn't mention. When I'm in play mode and I manually rotate the pivot, the camera rotate on itself instead of rotating around the pivot
what do you mean whern you say "camera rotates around itself instead"
ah
if i need i can do it, obviously there are a LOT of things i don't know about unity yet, so if i ever needed them i can still look them up on yt
I'm not on "center" mode. I'm on "pivot"
make sure your script is on the pivot gameobject
because only way the camera would rotate locally is if the script was on the camera itself
or maybe you have a script on the pivot AND the camera 
Hi, I am trying to make a cyborg futuristic hacking game.
I have this OperatingSystem script which goes onto cyborgs with a serialized list of Applications
public class OperatingSystem : MonoBehaviour {
private Root root;
[SerializeField] private List<Application> applications;
private void Start() {
root = new Root();
applications.Add(new TerminalApplication(this));
}
}```
Here is my application class. It is not a MonoBehaviour but all its fields are serialized ( as far as I understand ).
```cs
[Serializable]
public abstract class Application {
[SerializeField] private string name;
[SerializeField] private bool adminPerms;
[SerializeField] private OperatingSystem os;
public Application(string name, OperatingSystem os = null) {
this.name = name;
this.os = os;
if (os != null) { adminPerms = true; }
}
Here is the TerminalApplication class which inherits from Application.
[Serializable]
public class TerminalApplication : Application {
public TerminalApplication(OperatingSystem os) : base("TERMINAL", os) {}
}```
It should show the list of applications in the inspector as far as I understand, but it is not showing (as seen in the screenshot). What might be wrong?
That's not the case
hmm interesting
I don't understand at all x)
I saw one person having the same problem on the Internet, but nobody answered the solution
remembering that chatgpt exits makes me sad cause most people just go there and get the code
yea its not a healthy approach to learning to code imo either since coding is more about problem solving yourself haha
ohh i see the issue
no way
you're modifying the camera's position
trueeee
not about rotation but when you move the camera
you need to move pivot
hey guys, I'm designing my game's UI and I wonder which is the lowest screen resolution I should design for? I've been working on 800x400 portrait (yes, it's forced to be portrait) provided by unity, but when arranging some stuff they simply don't fit into the screen (with other game components) or they are too small for larger screen resolutions. I already know about canvas scaler and configured it to my needs, but the problem persists so I wonder if people actually uses 800x400 phones
hey guys how can I reference a public variable in a different script (attached to a different game object if this helps) I've already referenced the script and that works fine for calling methods from the other script, but I can't for the life of me figure out how to reference a variable
I set the camera behind the character. This prevent the camera from "rotating" around the pivot because in reality it's not rotating but moving around ?
This is the problem ?
if the variable is public it is the same as calling a method
shouldnt the camera already be offset from the pivot?
and then you can just move the pivot on the exact player's position without offset
im not sure how to compute the time dialation seconds
Yes, that's a good idea
Thanks! It was simple my bad x)
if referenceing a method is
script.method();
then referencing a variable is
script.variable;
no worries haha
yeah but it is still giving me a null reference
if (Input.GetKeyDown(KeyCode.Space) && hardGameManager.phaseNumber > 0)
{
phaseWalls = true;
phaseVisual.gameObject.SetActive(true);
hardGameManager.phaseNumber -- ;
on which line?
the if line
it doesn't like hardGameManager.phaseNumber
which is script variable with public variable from that script
then hardGameManager is null, so you're not referencing it correctly
am I supposed to use the assigned variable to the script or the actual name of the script here?
I thought it was the assigned variable that I declared in start
hardGameManager = GameObject.Find("Game Manager Hard Mode").GetComponent<HardModeGameManager>();
do you even check to see if that line works?
imma dm you in a lil while after a work call to help you understand without spoonfeeding 😄
omg, thanks soo much
currently watching a tutorial on saving data using json, but they say they'll be using the BinaryFormatter, however someone here yesterday said that isn't wise as it was depreciated or something. What else could be used then?
Unity serialization doesn't support inheritance. Use this instead: https://docs.unity3d.com/ScriptReference/SerializeReference.html
I took some time and red you message again and came up with this, it actually works!
i made it myself
awesome
im suprised it actually works
but im happy
and now i dont really know what else to add
https://hatebin.com/krsdqjzsbd
unity states that at line 32 there is an empty statement
line 31 has a ; after while :D
right
i have sprinting, crawling, crouching, what else is an good feature
thanks! issue is solved
i wanna try to add things myself to see what i have learned
i'm trying to do wall jumping :)
also i think you just need to use if instead of while there since Update is essentially a loop itself 
i'm 99% sure it won't work tho
i can see the basic picture of what you wanna do
makes sense
the one in start certainly does as I've been able to call methods from that script just fine. I'm getting the null reference error specifcally on that line (the if conditional). It is not a compilation error, it only kicks it out when I press the space bar during test. I certainly don't see any errors with syntax but I'm also pretty new
null ref is a runtime error not a compilation error. it means something is null. so on this line
if (Input.GetKeyDown(KeyCode.Space) && hardGameManager.phaseNumber > 0)
the only thing that could be null is the hardGameManager variable
hmmmm is adding some hand movement to the game an good idea just for the player to not be an capsule
some capsule hands 🙂
xd
im going to try to make an item pick up feature and try to learn something new
https://hatebin.com/uwdbpyjgqm
if the bool isOnWall is true and i try to jump no force is applied (in the inspector i set the values to be -5x and 5y)
Rigidbody.velocity += new Vector3(0, wallDrag, 0);
This runs every frame, so the amount the velocity changes per second will depend on your framerate.
currently working on a saving and loading system, I guess I can put the save function in the on application quit method?
Consider using AddForce -- and doing it in FixedUpdate, too.
That's a reasonable choice, yes. I would also save at other times, like when you switch levels, or every few minutes
Application.quitting won't fire if the game crashes or gets forcibly closed
switch levels sounds good, not sure how I would get it to recognise that the scene has been switched though
SceneManager.activeSceneChanged
that event fires when the active scene changes (unsurprisingly)
You could also just save the game when you decide to load a new scene
shrimple as that
since you'll presumably have code whose job is to load levels
note that this isn't why your jump is working
at the moment I lierally just have a button that switches scenes and that's it, got no custom loading stuff yet
Although, maybe other parts of your code are changing your velocity so quickly that you can't get off the ground at all
i did both, but the wall jump thing is still not working
add some Debug.Log statements to find out exactly what is going on
also, if you're now in FixedUpdate, you will need to change how you get input
specifically, GetKeyUp is flaky in FixedUpdate
because it only returns true for one frame
you might get two frames before another physics update happens
what's the difference between fixed and regular?
sp getkeydown
Same issue.
Update runs once per frame
FixedUpdate runs right before the physics update
which normally happens 50 times per second
What you can do is check input in Update, then use the input in FixedUpdate
bool wantsJump = false;
void Update() {
if (Input.GetKeyUp(KeyCode.Space))
wantsJump = true;
}
void FixedUpdate() {
if (wantsJump) {
wantsJump = false;
// do a jump
}
}
like so
what is the best and most efficient way to learn c#?
@swift crag using debug.log, it prints something to the console, but it adds no force
lots of practice
I learnt it back at secondary school, which was a good way to point me in the right direction, but from scratch I'm not really sure what the best way would be
I've got an absolutely huge handbook that I've written which contains all the things I've learnt though
oh, I seem to have an issue. When you quit the application by pressing the play button again is it suppose to clear out this inventory?
the json? yea unless you store it in a file
well in this case the inventory should already have stuff in it
since I'm aiming to save it when the application closes
but does putting it there mean the object already has its data wiped before it can save or something?
uh, that is dangerous business
in what way
on application quit, several things might be null
same thing happens in OnDestroy
unless I save every time an item is picked up perhaps?
just save in between or when you click the quit or exit to menu button :O
openning and writing files is expensive shit
don't have any kind of auto save system at the moment
you should save often, but not too often (:
tighten bolt. do not overtighten. do not undertighten.
does that method fire after objects are destroyed by the scene unload?
i've never thought about that
you also don’t want to save if the player expects it to not be saved
I'm only ever saving data that isn't on scene objects anyway
maybe make a save button too on top of periodical saves if player chooses to keep on autosave
well this is only meant to be a uni project, it's scale is absolutely tiny. I suppose saving on scene change might work, but it's only played for a couple of seconds in total
i’m not exactly sure. but it is dangerous
especially if you force quit or something
this is my issue
or stop the process, or crash
Yeah I figured it wouldn't be wise, just didn't know of when else itll be appropriate
find a trigger where it makes sense to save
something that happens not super frequently
scene change might be useful, but I also don't want them to pick something up then quit and lose it
or a button the player can press
most modern games have manual save, autosave, and a button to turn off autosave
I mean, this is literally all I have at the moment. You walk over the boxes and it adds stuff to an inventory which carries over to the next scene, this isn't going to have a save slot system
guys please
then just add a temporary button for testing, and add a proper save trigger later
see if your rigidbody has continuous collision detection mode. it should
since the user should be able to leave at any point, they could potentially pick up one thing then leave the game which is valid
best way I could describe it is a pokemon go type thing where you can just load it up, pick something up then shut it off
in discrete collision detection mode, you will be clipping into the wall every time you move
but I assume that just stores it all on a database somewhere else, not locally
i think it'll be a good idea at this point to not use velocity for movement but just move using AddForce
a mixture of both is gonna be pretty inconsistent to use and will result in more issues down the line
i use both when I want to make .velocity methods override added forces
also why is everything red
i mean i would still use .velocity to clamp the speed or to make it stop moving when no input is pressed to avoid sliding
but other than that, i'd use AddForce for everything else related to player movement 
https://hatebin.com/zghpcroddo
changed it to addforce
AddForce impulse mode directly modifies velocity instantly btw
it’s just something you need to be aware of
AddForce (force mode) adds a force vector to be added in at start of similation.
Changing velocity changes velocity as of right now
doesnt set it though, just adds force instantly :o
now i cannot jump anymore lol
AddForce in impulse mode directly changes your velocity from one line of code to the next. and does not change totalForces
maybe 3D is smarter
because you're doing AddForce(horizontalInput, Rigibody.velocity.y, 0) so you're constantly applying force on the y axis
that's probably not the only issue but should be an issue
your jump method should probably set rigidbody.velocity = new Vector2(rigidbody.velocity.x, jump speed);
you can do it with AddForce
that code is fine, try changing the number, increase it
i changed everything to addforce
and Rigidbody.AddForce(new Vector3(0, jumpForce, 0), ForceMode.Impulse);
i think that's the issue... you arent making a new Vector3
setting y velocity makes your jump a specific height from start position, every time, even off of a falling platform.
AddForce impulse mode will make your jump just add force from your starting velocity, so jumping from falling platform can still have a downward velocity
depends on what you want. both are valid
if the json here is just {}, even though the serialisable tag is on the slot that the container is a type of, is that just down to the fact that the item itself can't be properly serialised?
i prefer set velocity, which is more cartoony, and simpler for the player to know where they will end up
AddForce maintains reference frame, and conserves momentum
horizontalInput = Input.GetAxis("Horizontal");
Rigidbody.AddForce(new Vector3(horizontalInput * horizontalSpeed, 0, 0),ForceMode.Impulse);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
Rigidbody.AddForce(new Vector3(0, jumpForce, 0),ForceMode.Impulse);
isGrounded = false;
}
@dire torrent
looks fine and yea loop's point is valid, if you want to air jump that's gonna be a bit iffy
that will work, but in 2D, you should use Vector2
is your rigidbody in dynamic mode?
put a debug.log and see if the code is getting called
the wall jump works only once
use Debug.Log when you call AddForce to know if it is getting called at all
because it could be adding the force followed by something blocks it, OR it just never tries to add the force at all
i suppose another solution would be to just reset y velocity whenever jump is pressed and then add force if wanting to do that 
and make sure your rigidbody is in continuous collision detection mode
default is discrete, which is wrong
i think the issue is that i add a -5 force on the x axis on the wall jump
even if the wall is on the left
but idk how to make it so that it's +-5 depending on the direction of the movement
strange, I can serialise the whole class but not the list in the class. So when serialising, can you not just directly pass in a list? Does it have to be a class with a list in it?
you need to detect the wall
how?
raycast perhaps?
what?
well to detect the wall the first one I'd try would be a raycast to the left or right that juts out a short distance, and if it intersects the wall, which could have a tag on it, it knows it's on the wall
or a collider perhaps
i need to see a tutorial on what raycast is
I watched Game Dev Beginner's one on it recently, was pretty good
I would use .Cast on your collider
In 2D, raycast has a very similar cost to casting your whole box collider
A raycast is like shooting a laser into your scene.
The laser stops when it hits a collider.
It's part of a small set of physics queries that are all extremely useful
i checked unity's tutorial on raycast
i never raycast. I always use Cast on my colliders, because it gives me more complete info
so i have to create a ray on collision with a wall, whose origin is the player and check which is the nearest wall?
and the moment you shoot 2 raycasts for one collider, it straight up costs more than .Cast
Hey, I'm a bit unsure about something about C#: If I use a using clausule when using unmanaged resources (in my case StreamWriter), there's no need to make the class IDisposable, right?
it's a bit confusing lol
there are a few ways to cast.
ContactFilter2D contactFilter = // make a contact filter that only shows terrain with walls
List<RaycastHit2D> hits = new();
int hitCount = playerCollider.Cast(Vector2.left, contactFilter, hits);
then check hits for valid hits
can't also i do transform.position - collider.transform.position and check wether it's positive or negative?
there are several ways to make that better, but that is the general idea
using automatically calls dispose when the scope closes
you can also call playerCollider.GetContacts, which gives you all the contacts for the player collder. Then sift through them to check for a wall
what happens then when you call collider.Cast instead of just raycast?
can i do this?
collider.Cast checks moving the whole shape
The thing is that I saw a class in an asset which uses StreamWriter inside an using clausule as well, but the class does implement IDisposable with an empty Dispose method. So there's no point on doing that, right?
so would that essentially perform multiple raycasts across the whole collider to the lefT?
but that would be Idisposable for the class not for the Streamwriter?
like sending out a ghost of yourself
if you shoot a raycast, it’s like a laser, which would have gone straight though and missed both green shapes
does that also exist in 3D or is it just 2d?
sounds like it would be
Yes, I saw that as the class uses StreamWriter, it implements IDisposable. But I dont understand why
because he is making the class itself disposable, that has nothing to do with the StreamWriter
goodness me my project is already becoming a mess
Thank you, then it seems that it's just a mistake of the asset creator. He made the class IDisposable because he thought he had to do it when using StreamWriter, so that was confusing me
you use some idisposable class doesnt mean your class have to be idisposable
Thanks, thats what I was asking basically
implenting IDisposible does give you more fine grained control over garbage collection, perhaps he was just giving you the option to use it
So there's actually a point on making an empty Dispose method?
yes
what do you mean
you must implement the dispose method even if the method body is empty
Then I guess it makes the garbage collector delete the class instance when the using clausule ends. Am I wrong?
on collision i did transform.position.x - collision.gameobject.position.y to check the direction of the player on the wall
No, that is correct, it can be very important, especially in game dev, to control exactly when objects are collected and not just leaving it to the collector. But this falls into the subject of extreme optimisation
have you thrown a Debug.Log to check the direction?
in the editor it's public but it's 0
Hi could someone help me with this error
not unless you post a proper screenshot
Thank you so much, I finally understand. I will start using it too
@languid spire can you help me, too?
no
lol
hmm there used to be Collision.hitPosition or something i cant seem to find it on the Unity documentation but i think your playerPosition and Collision.transform.position is probably the same lol
Better?
Collision.transform.position is the same as playerPosition, but collision.transform.position is different
hmm then idk it should be setting the playerdirection fine
i forgot to use collision.gameobject.transform.position, and instead used collision.transform.position
there's a difference?
you've probably got a package compatibility problem, so check which packages you are using
Thats exactly the same
The transform of the collision is the same transform as the transform of the GameObject of the colisión
shouldnt make a difference
idk now it's set as positive
Hey Guys, I have a pretty advanced problem. I am currently working on a registration screen in Unity while storing the user data on a MySQL Database. Does somebody here have experience on the subject?
but it doesn't change if the collision is negative
yes, what is the problem?
The storing of the Data is working fine, but I hav implemented a function where the php Code should echo a Error Code when the Username is already taken. The function is working, but i don't get the Error code that should be echoed
that sounds more like a php problem rather than a sql problem
Is it ok if I pm you? To further explaine what I am having issues with?
no, I don't do php
Ok
ohh it could happen when your player's X is negative
so
if player is left of the wall player.x - collision.x could be -3-6 and now you get -9 which means you apply force on the right side when you should be applying force on other side
or wait bad math on my end 
nvm idk lol
if it’s negative i apply a force on the right
@dire torrent actually you are right, i switched them and it works
tyyyy
This is why you ask your question instead of asking someone to commit to answering before they know what the question is.
https://dontasktoask.com/
also a typical X Y problem
gotta suffer to reach perfection
why is it that so many times when I try to do the 'attach to unity and play', VS goes into play mode but unity itself just freezes up and does nothing
Did you hit a breakpoint in code
nope, it's just doing nothing
Does the game run normally without being in debug mode
perfectly fine
its just like just spending an absolute preparing itself to run in debug
oh and now somehow implementing file saving has broken my ui... neat
how is that even possible? System IO has absolutely nothing to do with UI
@dire torrent No off-topic media, please
must have been something else I changed while trying to get it to work. No matter, will fix it later
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehaviour : MonoBehaviour
{
public float minXValue;
public float maxXValue;
public float xSpeed;
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.velocity = new Vector3(xSpeed, 0, 0);
if (transform.position.x < minXValue || transform.position.x > maxXValue)
{
xSpeed *= -1;
}
}
}
this should invert the enemy direction if it gets out of selected bounds, but, using a cylinder as an enemy it's buggy and doesn't work
well it's going to invert the direction every single physics frame while it's outside the bounds
not to mention you're inverting it AFTER you already set the velocity this frame
so there wil be a 1 frame delay before it takes effect
Define buggy?
Please properly format your !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.
it inverts every single frame
even if it's inside the bounds
how about this:
public float speed;
float currentSpeed;
void Start() {
currentSpeed = speed;
}
void FixedUpdate()
{
float xPos = rb.position.x;
if (xPos < minXValue) currentSpeed = speed;
else if (xPos > maxXValue) currentSpeed = -speed;
rb.velocity = new Vector3(currentSpeed, 0, 0);
}```
https://pastebin.com/FMp66y25 anyone know what this error means
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.
Looks like a problem in SkinChangedServerRpc at Assets/Scripts/MultiplayerPlayerController.cs:163
[ServerRpc(RequireOwnership = false)]
private void SkinChangedServerRpc(int variable)
{
SkinNetwork.Value = variable;
Skin = variable;
}
public void SetSkinWizard()
{
//CharacterSelect = GameObject.Find("CharacterSelect");
//SkinNetwork.Value = 2;
SkinChangedServerRpc(2);
animator.runtimeAnimatorController = WizardCombo[0].animatorOV;
animator.Play("Attack", 0, 0);
m_Coll.size = new Vector2(0.35f, 0.66f);
m_Coll.offset = new Vector2(0f, 0f);
CharacterSelect.SetActive(false);
}
those are the 2 functions it has a problem with
based on the rest of the trace possibly you have a NetworkObject that was not properly initialized
so for example im trying to doa character select screen should the canvas or buttons be network objects
Which line is 163? (initially when the error occurred)
like should they have a network object component
SkinNetwork.Value = variable;
this is 115
SkinChangedServerRpc(2);
no
Whatever object MultiplayerPlayerController is on needs to be a NetworkObject
it is
That's the line that's giving the error so it would imply that Skin Network is null
and how was it created?
Nah the NRE trace would end there
a network manager
the NRE is happening inside some deepish networking stuff
Where do you instantiate it? What is the variable referencing?
which kinda implies to me the network variable is somehow not set up properly, or the network object itself isnt
so i get the errors when i try and click on of the buttons on the character select screen
everything works fine otherwise
So you get the error because something is null. Which is expected - the entirety isn't working properly.
Two options:
- Record the previous value and check if it's changed.
- When you change the value, update the other.
but i mean in equation
x ++
y --
is the equation
Unless you have something more elaborate? But not according to your initial question
so weirdly 1 button works the other 3 dont
Does anyone have an idea why a UI won't update a number?
public void PhaseAbilityNumber(int phaseToAdd)
{
phaseNumber += phaseToAdd;
if (Input.GetKeyDown(KeyCode.Space) && phaseNumber > 0)
{
phaseNumber--;
}
hardPhaseText.text = "Phases Left " + phaseNumber;
}
The code works in every way except it doesn't decrement phaseNumber visually (it still obviously recognizes that the number has been subtracted) I'm sure the answer is simple I just am unsure what to do. I tried moving the if statement to update but that didn't work either. It's like the "phaseNumber" part of the .text isn't updating
i need to make weight reliant to hunger IF the hunger decreases the weight will increase
it updates positively but not negatively visually
but i have no idea how to do it
Hi could someone help me
you need to set a number to the array, even like 0
obvious syntax errors
an int
what is line 21 and 22?
Where ?
so each character is a button and the samurai one works but the other 3 dont i get the previous error when i try pressing the other 3
public void SetSkinSamurai()
{
SkinChangedServerRpc(1);
animator.runtimeAnimatorController = SamuraiCombo[0].animatorOV;
animator.Play("Attack", 0, 0);
m_Coll.size = new Vector2(0.31f, 0.7f);
m_Coll.offset = new Vector2(0.06f, 0f);
CharacterSelect.SetActive(false);
}
public void SetSkinWizard()
{
SkinChangedServerRpc(2);
animator.runtimeAnimatorController = WizardCombo[0].animatorOV;
animator.Play("Attack", 0, 0);
m_Coll.size = new Vector2(0.35f, 0.66f);
m_Coll.offset = new Vector2(0f, 0f);
CharacterSelect.SetActive(false);
}
public void SetSkinKnight()
{
SkinChangedServerRpc(3);
animator.runtimeAnimatorController = KnightCombo[0].animatorOV;
animator.Play("Attack", 0, 0);
m_Coll.size = new Vector2(0.38f, 0.64f);
m_Coll.offset = new Vector2(-0.02f, 0f);
CharacterSelect.SetActive(false);
}
public void SetSkinButter()
{
SkinChangedServerRpc(4);
animator.runtimeAnimatorController = ButterCombo[0].animatorOV;
animator.Play("Attack", 0, 0);
m_Coll.size = new Vector2(0.46f, 0.83f);
m_Coll.offset = new Vector2(0f, 0f);
CharacterSelect.SetActive(false);
}
those are each characters functions
So the issue implementing your already decided on math, or are you asking for math help?
did you not read the error messages?
yes
yes i read the messages
You can't answer "yes" to two given questions in a sentence.
this is the script
this doesn't contain the error
So where is the error?
Vector 2 ?????????????
its line 22, character 34 according to your error message
Line 22 of the Player Movement script
Obvious Syntax Error
what should I write there?
given that your avatar is the python logo, I presume you've written python before
Vector and 2 needs to be joined
what do you think should be in place of Vector 2 ?
foobar = 3
print(foo bar)
yse
yes
this is clearly bogus
you've made the same mistake
I dont know?
this one Vector2
so why are you not using that?
btw your !IDE is probably not configured otherwise it would have shown you 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
thank you very much @languid spire 
Yo! I want to Clamp an (euler) angle between -90 and 90 but angles in Unity are between [0, 360] (from what I saw). I saw people create functions to convert it between [-180, 180] but my question is. Is it easier to Clamp a Quaternion ?
you cannot clamp a Quaternion
R.i.p...
Those values wouldn't be euler values
well, that would involve converting your quaternion into euler angles
can you explain what you want to accomplish first
not "clamp an angle"
what are you making your game do?
https://hatebin.com/njslecvgho
now it doesn't work anymore, it flips forever
I have a camera on a player. I want the camera to be locked between -90 and 90 degrees (on top of my character or on the bottom)
I used Mathf.Clamp() but it doesn't work because the transform.position.eulerangles.x is between 0 and 360
The solution I found is what I said earlier. But I want to know if this is the correct way to process (if there is one)
i would suggest just storing the pitch you want the camera to have in a float
and then directly set the camera's rotation based on that
whya re you doing this?
if (gM.isGameActive)
{
gameObject.SetActive(true);
currentSpeed = xSpeed;
}```
private void HandleRotation()
{
float xAxisMouse = _playerInputActions.GroundedGameplay.CameraMovement.ReadValue<Vector2>().y;
float yAxisMouse = _playerInputActions.GroundedGameplay.CameraMovement.ReadValue<Vector2>().x;
transform.Rotate(-xAxisMouse * _rotationSpeed, 0f, 0f, Space.Self);
transform.Rotate(0f, yAxisMouse * _rotationSpeed, 0f, Space.World);
yPivotAngle = transform.rotation.eulerAngles.x;
yPivotAngle = Mathf.Clamp(yPivotAngle, _yMinimumRotation, _yMaximumRotation);
transform.rotation = Quaternion.Euler(yPivotAngle, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
}
This is my code actually
float yaw;
float pitch;
void Update() {
yaw += // yaw input
pitch += // pitch input
yaw = Mathf.Repeat(yaw, 360);
pitch = Mathf.Clamp(pitch, -90, 90);
camera.rotation = Quaternion.AngleAxis(yaw, Vector3.up) * Quaternion.AngleAxis(pitch, Vector3.right);
}
This is how I usually do it.
if the game is not active the speed is 0
reading back individual euler angles is always a bad idea
that's not what that code even does though
How should I process ?
Thanks!
tracj your own variables
also if the game is not active the gameobject is not active
then you don't need to do anything
why?
why not pause the game e.g. with timeScale when it's not active
Vector3 flattened = Vector3.ProjectOnPlane(entity.transform.forward, Vector3.up);
yaw = Vector3.SignedAngle(Vector3.forward, flattened, Vector3.up);
Vector3 rotated = Quaternion.AngleAxis(-yaw, Vector3.up) * entity.transform.forward;
pitch = Vector3.SignedAngle(Vector3.forward, rotated, Vector3.right);
This is how I figure out the right pitch and yaw when taking control of an entity in my game
if the object isn't active it won't move anyway
Why does this visually update when I add but not when I subtract? do I need to pass 2 parameters to this method for that? It seems to functionally decrement, but it doesn't update the number on the screen (only positively) any ideas?
public void PhaseAbilityNumber(int phaseToAdd)
{
phaseNumber += phaseToAdd;
if (Input.GetKeyDown(KeyCode.Space) && phaseNumber > 0)
{
phaseNumber--;
}
hardPhaseText.text = "Phases Left " + phaseNumber;
}
What is "yaw" and "pitch" ?
What does that mean ?
well yeah but that’s not the problem
Yaw is left-right rotation. Pitch is up-down rotation
(and Roll is...rolling!)
the speed changes between -speed and speed every frame
Repeat is just a modulo ?
Ok thanks
Not exactly, because C#'s % operator isn't actually the modulo operator
it's the remainder operator
-1 % 5 == -1
oh, well
yes, that's right! :p
Repeat is the modulus operator. It's just that people often call % "modulo" when it really isn't
Define "visually update". It'll only decrement on number being greater than zero and space key pressed.
(please, microsoft, give me a %% operator)
Ok thanks!
GetKeyDown is only true for a single frame
I am using .text to dynamically update on screen
Perhaps you wanted GetKey?
perhaps, I'll try it
Hi, how can I create a Text Input action in the new Input system?
So if I only want Y rotation the "yaw" serves no purpose ?
I don't know what you intend for this code to do
No, yaw is rotation around the Y axis.
ok lmao
Then the other one serves no purpose ?
You called it "y axis", but that's probably because it's coming from the Y part of player input
Wrong channel, try #💻┃unity-talk or #🖱️┃input-system
alright
If you only want to tilt the camera up and down, you're only changing its pitch, or its local X rotation
Okay
Hey what can I do against camera object clipping and stuff like theese?
yeah the issue isn't that it's not registering, it is, it just isn't updating visually, the number on the screen won't go down even if the program recognizes that it did!
and it will go up which makes the mystery even worse
how do you know the program "recognized" that the value went down?
use raycast to retract the weapon or make the player collider big enough
(using two cameras is also an option but come to avoid this technique because you won't get any shadowing , if that doesn't bother you then use camera stacking)
Place a log to print the value after updating the string text
because when the value is 0 you can't use that resource anymore, even if it says higher on screen
Likely how you're calling this with a negative value simply likely isn't occurring instead
prove it by logging the reduced value, as well as the value of hardPhaseText.text at the end
I'll give it a go
I don't think this works for my case. I want to Clamp the transform rotation not the input?
The point is that you track the pitch value you want
and then directly set the rotation based on it
you aren't just adjusting the existing rotation
note that you'll probably want to switch to local rotation here
so that the camera is being pitched up and down relative to its parent
You don't clamp the rotation. You'd clamp your own managed variables and only update the rotation values with your variables.
Sure, does it hel if I make the gun collider bigger? or If the raycast hits, lets say within 1 meter, the gun rotates/or the collider increases size, or something like that?
putting collider on the weapon wont stop it from glitching through the wall if your player keeps pushing into the wall, you'll get weird collision
the collider resizing makes more sense on the player(since its moving) not the weapon
Don't know if this can help you. But i've seen a indie game developer talk about this. The general solution (if I remember correctly) is to have two different things the in game object and the visual. The visual is like an "image" that isn't in your world but in your screen (if it's understandable)
If it's not in your world it can't clip
yea I suggested that already, its called camera stacking
My b
that wont give you shadows on the weapon from the world you're in, which is a major drawback
but if you dont care about that then its fine
I've got a bunch of objects with the same script and one manager object with a manager script. Now I want the manager script to have a list with every object that has the other script. What would be a smart way of doing that where I wouldn't have to drag and drop the objects in the list in the editor?
it can also be a bit of a performance hit to have multiple cameras
I like to go with the physically accurate approach of pulling the weapon back
same
if you also accurately fire from the gun's muzzle, rather than just raytracing from the center of the screen, this could have some gameplay implications
Drag and drop if possible else have whoever instantiated those objects, initialize them.
do you spawning them at runetime? add them to list when you spawn. otherwise a simple FindObjectsOfType or something in awake should be fine to cache
all the objects are there at the start i dont spawn them in
whats wrong with the inspector then? its usually the fastest solution
when my game evolvs
oh true
what does that mean?
If you're always adding and removing objects, I would just grab them all in Awake
well I need to add new ones and remove old ones while developing and i think its annoying to have to reasign them
or have each object report itself to the manager
void Awake() {
Manager.instance.Register(this);
}
this sort of vibe
if you type t:MyScript in hierarchy search, you will find all your objects btw so you dont have to go through the hirerchy
I have an EntityManager that keeps track of all entities in my game
at the end of the entity's Awake method, it registers itself
EntityManager.Instance.Register(this);
It's incremental. You'd provide the change as change occurs. Automation is usually less performant - the cost of your efforts with precaching vs potential error prone runtime loading.
forgetting to drag an object in is going to be a major source of errors, IMO
If the goal is to just get every object of type X, doing it at runtime will be way more reliable.
If you have more specific needs, then the issue is murkier
let me try this
Having a missing dependency is greatly more confusing. You'd at least be able to validate with the inspector in the editor.
for example, if you care about the exact order of objects, and also need to exclude certain objects based on non-trivial criteria, you might just want to set it up in the inspector
but, by definition, there would be no missing objects
because you got all of them!
If you didn't drag an object in, it's not meant to be in 
or you forgot to drag it in
it sounds like Pixel wants to get every instance of X.
Hi, why doesn't BoxCast detect the stairs when the player is in the middle of them?
Code:
void ClimbingStairs()
{
if (CheckUp(stairsLayer))
{
rig.velocity = new Vector2(rig.velocity.x, Input.GetAxis("Vertical") * wallMovementSpeed);
}
}
// Check Up
private bool CheckUp(LayerMask layer)
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.up, 1f, layer);
}
make editor script that mixes FindAll and Inpsector xD
are you italian?
If you can express the criteria for which instances of X to get through code, it's going to be very, very reliable to just get them through code.
not a lick!
isn’t “modulo” italian?
latin
there you go, latin
just about everything stems from latin
which type of collider are you using for your player and for the ladder?
anyway i have not solved this yet
for the player I use BoxCollider2D and for the Stairs I use Tilemap Collider with Composite Collider 2D
mb
Which is fine. I'd just not ever promote automation unless human effort is beyond manageable. We won't remember these self initializing procedures and debugging can be annoying.
to the contrary, I automate everything I possibly can
try looking in the composite collider options, there should be an option to select whether you want it to be "outline" or "polygon". Make sure to choose polygon
I am a fallible meatbag
had to take latin in my middle school 
Italian schools..
for example, my game's settings menu is generated completely automatically
I hand the game a hierarchy of settings definitions and it spits out menus and sliders and buttons
When I add a new setting, it automatically appears in the settings menu
I can't forget
Oh thanks, it worked!
and I can't accidentally modify one of the prefab instances so that it looks a little wrong
are you italian too?
yas
I automate anything that I can express through code.
i am taking latin in middle school too
i couldn’t do informatics since my parents wanted me to do latin bc “it makes you reason”
right
nice! the issue was that te box collider was detecting the outline, so at the middle of the ladder you were inside the collider so the boxCast didn't catch it. When you set it to polygon, the collider is set also inside the outline
do i want to use object pooling when spawning enemy.....?
smart.
when I went to school we had windows 98 and had to learn Office, thats about all the "information technology" we got . Poor school
When a setting is missing and you don't recall what you've done with it, how it's found or which script does the initialization.. it can be tedious if your system isn't well built.
but anyway can you repost your issue @novel shoal
I don't know what you mean by "don't recall what you've done with it"
they all live right here
I do have an editor script that makes sure every setting has valid localized strings and is included in the hierarchy
data validation, basically
a setting with no category makes no sense; there is nowhere to put it
It's all very uniform.
I guess it would be bad if my code was bad
but that's a tautology. everything is bad if it's bad.
For example, Play button is missing but it's obviously in the scene. You've set this up 3 years ago and do not recall which component script is managing this.
if it's obviously in the scene already, then it's clearly not being created automatically
Or if whatever is expecting it to be there simply isn't able to properly acquire it etc
the enemy gameobject should basically just go back and forth between two given ranges, but it doesn’t, instead its speed becomes negative or positive every frame
you're describing a very vague category of problems
Automation was referring to referencing already existing objects in scene as the op had described
me? i answered to my code
I would probably not grab a reference to the play button from code
There is only one play button, after all.
But if I had several levels, each of which had varying numbers and kinds of enemies, I'd be very unhappy if I had to make sure every single one was dragged into the EnemyManager's enemy list
But.. everything can be automated 🥹
i do not understand what your point is
why are you doing this way
No user awareness is necessary if the code base is perfect
this does not feel very productive
that’s the only way i thought about
i could also use a coroutine
thinking about a mechanic where the player can walk to each "door", and a snapping arrow appears that points to each other door, too which the player can teleport too. any suggestions on starting to make this?
yeah that seems the best thing to do
What I would do is when enemy reaches a point you rotate 180 instead of making -speed
so speed can always be positive
and can i use coroutines instead of points?
Each door should know which door it connects to. Each door should also have an arrow sprite positioned next to it.
When the player hits a trigger collider on the door, it tells both itself and its linked door "show the arrow!"
why would coroutine change anything
whats the objective of that?
If you want to draw an arrow between the two doors, you'll need a LineRenderer or something. You would give each door its own LineRenderer, and you'd set its points appropriately when the player runs into the trigger
it’s easier to make it go for some time and then flip it than to do it with points
like a timer you mean?
sure that can work
public class Door : MonoBehaviour {
[SerializeField] Door linkedDoor;
[SerializeField] SpriteRenderer arrow;
public void ShowArrow() {
arrow.enabled = true;
}
void OnTriggerEnter(Collider other) {
if (other.TryGetComponent(out Player player)) {
ShowArrow();
linkedDoor.ShowArrow();
}
}
}
It'd look a bit like this
you'd write similar code to hide the arrow
they go in a direction for, say, 5 seconds, then flip, then 5 second to return to the starting position, then flip
and so forth
that can work, you have to also consider obstacles / wall, what happens if you bump into those
also is this 2D or 3D ? because you're using Rigidbody and not Rigidbody2D??
Hi, I want to Raycast to a navmesh. But navmeshes are not colliders. Is it ok to add a mesh collider to the navmesh surface or is this dumb af? What would be a better solution?
if at target
if target is point A
set target to point B
else
set target to point A```
just in case you find this later, this doesn't sound like you want -- https://docs.unity3d.com/ScriptReference/AI.NavMesh.Raycast.html
this method checks if a ray crashes into a navmesh edge
Maybe you can just use SamplePosition?
Especially if you can raycast onto the colliders that are used to create the navmesh in the first place
raycast onto a floor collider -> SamplePosition to snap onto the mesh
yeah def raycast on collider then use SamplePosition
This won't work if you're using renderers, not physics colliders, to create the mesh
I don't like doing that, though :p
i always switch my surfaces to hierarchy only + physics colliders
I'm already using that but I specifically want to raycast downward from points high up above the navmesh. SamplePosition has a "spherical" range.
same, that makes my "scenery" objects have navmesh
it’s a 2.5 game
gotcha
anyways i can put the time of the coroutine in a variable and change it for every enemy depending on its position
yeah
If the time is off though, the object may not be where you'd expect it to be 🤔
Sounds like potential future problems but it likely will work.
Pokemon-ish type of game.
Each player / character has the list of the "pokemons" he owns. "Pokemons" are also upgradeable and so on.
Player is also upgradeable and so on.
Serialization: Do I serialize both player data and pokemon data as player data or do I separate the pokemon data from players data and serialize (I mean save the data into json or binary) them separately?
Together: CharName.dat
Separately: CharName.dat + CharNamePokemons.dat
I guess I could also use SamplePosition and then NavMesh.Raycast to see that point fall on the border, which means it wasn't above the navmesh but next to it 🤔
Not sure how NavMesh.Raycast behave with a source position that isn't on the NavMesh
curious, what is the usecase here?
i can set time off?
You could be missing frames and potentially traversing farther or shorter than the wanted distance. But likely this will not happen. Just sort of reminds me of older Bethesda games running at frames > 60 or lag
ohh Navmesh raycast apparently is not what i thought it was xD
It rays from point to another point, it has no direction . Apparently the best solution would probably be Raycast + Sample Position to find that point on navmesh itself
I'm creating random points with Poisson Disc Sampling over a rectangular area, and then I want to project those points to the navmesh, discarding any that wouldn't hit the navmesh. Using SamplePosition with a small range does that but if there is lots of height variations on the navmesh then I need to increase the range and I'd get lots of points on the borders of the navmesh.
Yeah that does make the most sense. I can simply use the ground geometry that is already there.
I'll generate the points really high up and raycast down to infinity
yea as long as the ground has collider should work perfectly this way
Does anyone know how this code could bug out my pickup system, where gameobjects that the player is holding, moves freely around while the player is looking around? If the player is just moving and not looking around, the item stays in the right position. ```#Movement///
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// Calculate the movement direction relative to the camera's rotation
Vector3 forward = playerCamera.transform.forward;
Vector3 right = playerCamera.transform.right;
forward.y = 0f; // Ensure no vertical movement
right.y = 0f; // Ensure no vertical movement
forward.Normalize();
right.Normalize();
Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;
// Apply the movement to the rigidbody
rb.velocity = desiredMoveDirection * playerSpeed;
///
#Camera Movment
///
yaw = playerCamera.transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSensitivity;
if (!invertCamera)
{
pitch -= mouseSensitivity * Input.GetAxis("Mouse Y");
}
else
{
// Inverted Y
pitch += mouseSensitivity * Input.GetAxis("Mouse Y");
}
// Clamp pitch between lookAngle
pitch = Mathf.Clamp(pitch, -maxLookAngle, maxLookAngle);
playerCamera.transform.localEulerAngles = new Vector3(pitch, yaw, 0);
///```
The item is a child of the playerCamera
I'd advise against reading and writing to localEulerAngles directly.
Store the rotation in degrees in your script, as two variables, and modify those instead. Then assign to localRotation using Quaternion.Euler(x, y, z). This is because there can be multiple Euler angles that represent the same rotation, so on two consecutive frames you might be getting wildly different XYZ values
ok
Okay i changed, but i'm still dealing with the objects not staying with their parent
Is the parent scaled other than (1, 1, 1)? That might be the cause of them warping
dynamic rigidbodies will not follow their parents
warping is also a possibility
No, their not warping, there quite literally moving, within the players hand. Basically like your in space.
Yes
Is the movement consistent or random?
Consistent, moves only when i move AND look around at the same time.
Show the Inspector of one of these pickups while they're a child of the player
Screenshot or video?
Screenshot, just to see what components are attached to it
Does it need to have a rigidbody? What I usually do is have the base item as a prefab, and make a variant of it for the pickup
See if the problem goes away when removing the Rigidbody
Rigidbody, is for dropping it, and it being "pushable" while on the ground.
Yeah I have these separated. A prefab for holding, and a prefab (variant) for picking up
and your right, the rigidbody is the culprit
How is the rigidbody doing this?
They run on the Physics system, which is updated at a different rate than the rest of the game (eg. Update vs. FixedUpdate)
So how can i fix this without making multiple variants of an object?
You can't
Make prefab variants. Updating the root prefab will also update its variant
How do I change the z-index of UI Images if I cannot change the hierarchy? (it is used for layout reasons)
In this example, if I hover over any card, it should be the topmost card
void FixedUpdate()
{
if (gM.isGameActive)
{
gameObject.SetActive(true);
}
rb.velocity = new Vector3(xSpeed,0,0);
StartCoroutine(MoveForSecond());
gameObject.transform.Rotate(0, 180, 0);
}
is this ok?
how can i acess an int variable from another script
make a reference to the inspector
someone asked about this a few days ago and I didn't have a great answer then
the z-index is just the z-axis of its position. you can change or if the sort order (if the cards are placed on a sorting layer) . . .
No, it's a UI image, not a sprite
you can't change the sibling index of each child from the hierarchy?
the order is being used for layout already
SetSibilingIndex
that was the issue we ran into last time
I guess you could just run the layout once, then turn it off
how can i do that
!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.
Mm, that's an idea. Thanks
check the general section of the pinned messages (from this channel) . . .
You could also lay out a bunch of empty/dummy cards
then make the real cards follow the dummy ones as long as they're in your hand
gameObject.transform.Rotate(0, 180, 0); can be simplified down to just transform.Rotate(0, 180, 0);, since component scripts have direct access to transform.
Also the rotation should be done with the Rigidbody, if the movement is done with it too
I think I will have a single "Detail" card instance that moves to the currently hovered card. Could be a birt risky because of anchored positions and stuff, but maybe it works
if the script you are trying to access to is the game manager, just declare a variable in your script: public GameManager gM;
and then access its component gM = gM.GetComponent<GameManager>();
and then you can access every value in that script by using something like gM.(insert variable name/method name)
@carmine elm
Yeah, that's a reasonable idea. It's what we came up with last time this was asked here (i forget when exactly)
The only problem is that you need to seamlessly get rid of it when you grab the card, and make sure it always overlaps properly
rb.rotation =new Vector3(0,180,0);
doesn't work, how do i rotate it with the rb
"doesn't work" - what does this mean?
cannot convert from vector3 to quaternion
like, what the hell is a quaternion
Yeah. Really wish Unity allowed setting a separate z index, just like with sprites
yeah, that's just down to how UI rendering works
okay, for what?
You don't want to know how it works inside
it is a rotation
the specifics are irrelevant -- just like how you don't actually care how a Transform works
huh? dude you are scaring me
You can search for it on Wikipedia but I'm not liable for the brain damage induced from reading the page
transform is a class that has position, rotation etc. values withint it
It is a way to store a rotation. It works better than Euler angles
its a rotation matrix
It abstracts a Matrix4x4
a 16-element matrix of floats
Quaternions are weird math, but you don't really care about the weird math
I kind of wish Unity just called it a Rotation
rb.rotation =Quaternion.Euler(0,180,0);
Yeah, that's what you need to do.
Quaternion has lots of methods for creating and messing with rotations.
rb.rotation = new Rotation(0, 180, 0);
i'll (maybe) understand quaternions at university (not likely)
i have not done them yet at school, but kinda
real number: a
complex number: a + bi
quaternion: a + bi + cj + dk
huh, maybe i shall quit the idea of doing anything math related
they're a bundle of joy
fr
but again: we do not care about how they work
I don't care how they work!
I've also forgotten how transformation matrices work. Been a hot minute since I did those in college.
I just let Unity deal with it
how old are you?
all you really need to use is Quaternion.Euler which has x, y, z
God that method name is awful. FromEulerAngles() would be better
the best question to ask on social media:
Roblox uses FromEulerAnglesXYZ() for their CFrame rotation matrix
rb.rotation =Quaternion.Euler(0,180,0);
it doesn't flip the object
the fact that it has constraints on the axis affects it?
😒
Check other places where you could be overriding transform.rotation directly
https://hatebin.com/ddlbjmddqs
nowhere
And yes constraints will prevent it from moving/rotating on the enabled axes
with transform.rotate instead of rb.rotation it used to work
If you just need to flip a sprite, then use spriteRenderer.flipX instead of rotating the whole object
can i enable the rotation only when i need it to and then disable it?
does your gameobject have colliders
Is there a command to get a component in a parent of a parent or do I have to make a self refrence loop?
if you move transform.rotation, that does not update the colliders etc
no it's an enemy which has to go on a direction for some time and then flip to go on another for that amount of time
GetComponentInParent should go all the way up the chain iirc
But it returns the FIRST hit
Oh ok cool
I made a gravity simulation using rigidbodys and a script that adds a force to them but making a stable orbit is really hard because you have to restart the scene and slightly tweak the initial velocity until its stable. So I want to make a script that shows me where the object will go in the future but i have no idea how to do that. I've looked at other peoples code that did similair stuff but they dont apply to my case, how could I even approach this?
it's not flipping at all
but with transform.rotate it used to rotate
can i?
2D rigidbodies have rotation as a float, not a quaternion
Yes, the constraints is made up of a flags enum value you can toggle from the code.
But before editing the code, disable the constraints to see if they're the cause.
i'm using 3D stuff
and it has a rigidbody, not rigidbody2D?
exactly
it's not rotating but it's also adding a z force and the enemy cube falls even though the game is a 2.5
like a teleport
okk thx
Hi. I have a problem that I need to select several array elements at the same time to change the volume of the sound on the slider at the same time. I tried to write comma separated (0, 1, 2, etc.) or from 0 to 10, but there can only be 1 value in the array (the console told me so). Is it possible to get around this somehow and call several array elements at once through 1 line? Of course, I know that you can create a new int, etc., but is there an easier way?
rb.MoveRotation(Quaternion.Euler(0, 180, 0)); @buoyant knot
You simply can't provide an index like that
You want a loop (foreach or for)
this will make a kinematic rigidbody rotate to that rotational state next physics update while respecting collisions
Ok. Thanks
and automatically interpolate during non-fixed frames
I just installed the Input System, but its not showing up in code?
so is thir right?
should be
go to Preferences -> External Tools and hit the button to regenerate project files
but that is a really fast rotation
and also restart your code editor
that's what it's supposed to be, it's not supposed to be noticeable
instead, it should be instant
well, that rotation will take 1 fixed frame, potentially many normal frames. so 0.05 s by default
The Unity Editor, or Visual Studios?
rb.rotation is instant, but does not respect colliders
Visual Studio is your code editor.
the thing you use to edit code files
Can the tile system rule placement feature be used at runtime? When a player places a tile, I want it to change the terrain so that the edges get a cliff for example. So it knows if it will be a corner piece or not
it's not working, what the issue with transform.Rotate()? it's the only one that worked
rb.rotation should automatically move the transform as well, but I’m more used to 2D
i would debug.Log to see the transform.rotation and rigidbody.rotation before and after. For rb.rotation, and transform.Rotate()
It worked, thank you!
because it’s possible something else is overwriting the change
there is nothing that overwrites it
then do this
now even transform.Rotate does not work
sounds like it was never really working
that’s the problem with moving transforms. there are side effects
void FixedUpdate()
{
if (gM.isGameActive)
{
gameObject.SetActive(true);
}
rb.velocity = new Vector3(xSpeed,0,0);
StartCoroutine(MoveForSecond());
transform.Rotate(0, 180, 0);
}
what could overwrite it?
just print with debug.log
Debug.Log(transform.rotation.ToString() + “ - “ + rb.rotation);
that code makes no sense. what happens if gm.isGameActive is false?
Do note that transform.Rotate() will not wait until the coroutine has finished running. It will be executed immediately.
Co-routine, runs "separately" / "concurrently"
!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
also, you are doing this in fixed update, every fixed frame rotating to 0,180,0. Meaning you move once and never again?
if gm.isGameActive is false the game is in the starting screen/gameover screen
so why are you executing the rest of the method?
does anyone organize there code?
or do you just look at it and are like "good enough"
if the game is not active the rest of the method doesn't apply since the gameobject is not set as active
that makes no sense
If the game object is not active the method does not run at all
i know
So your if statement will technically never pass when this object is disabled
It's not needed to have it right now
i need to put it in the game manager?
Anywhere else that is active, so the code to enable your object runs
Please can someone tell me the simplest way to make a gameobject active when a player hits a boxcollider2d trigger box?
do you know how to set a gameobject active?
SetActive(true) right?
yes. so do that in OnTriggerEnter2D
@short hazel
https://hatebin.com/bwbiakeqcj
it still doesn't flip the object
or with OnCollisionEnter
that wouldn't work with a trigger
you're starting the coroutine every FixedUpdate. after a certain point it will start rotating constantly as all of the coroutines begin to end
if it starts a coroutine it should wait until the coroutine ends before executing that code
why would it do that?
you thought wrong. there is nothing preventing you from starting multiple separate instances of the coroutine because you do nothing to check whether it is already running or not
and how do i make it running only when it’s not running? by using a bool?
that is one way, yes
https://hatebin.com/yinqfnivzf
@slender nymph now the object is standin still
what is xSpeed set to
one
okay and does anything else like friction or a drag affect its speed?
before putting a bool in the coroutine it used to move
because it sounds like now your speed is too low to overcome those forces since you are no longer resetting the velocity every single fixed update
that doesn't answer the question i asked
so i just need to make the speed higher?
maybe, you didn't bother answering the question i asked
then come back when you can troubleshoot your issue
what do you mean by "it just defaults to all of them"
also you should consider changing that to a for loop now so you don't have to come back later and fix the for loop whenever you've got it set up. also you do not need to access a gameobject's gameObject property to call SetActive on it. you're already access the gameobject
public void Rotate(float degrees)
{
var transformContainerRotation = _transformContainer.localRotation;
_transformContainer.localRotation = new Quaternion
(
transformContainerRotation.x,
transformContainerRotation.y,
degrees,
transformContainerRotation.w
);
}
When I pass Rotate(2f) for example, in the inspector the rotation turns out to be something ridicilous like 164f. No matter if it's rotation or localRotation. Does anyone know how to properly rotate the container?
well for one, quaternions are not in degrees
Quaternion XYZW are not angles in degrees, do not modify them manually
That's fair, I just mean the z value in the inspector though
Oh
and even if you were assigning using Quaternion.Euler rotations can be expressed in many different ways so what you see in the inspector may differ from what you set in code
Maybe my approach is overkill too. I want to change the rotation of hand cards based on their index in the hand. So for example card 1 and 10 have a rotation of -5 and 5, cards 2 and 9 have a rotation of -4 and 4, and so on and so forth.
private void RecalculateTransforms()
{
var hasMiddle = _handCardViews.Count % 2 is 1;
if (hasMiddle)
{
for (var i = 0; i < _handCardViews.Count / 2; i++) _handCardViews[i].Rotate(2 * i);
for (var i = _handCardViews.Count / 2 + 1; i < _handCardViews.Count; i++)
_handCardViews[i].Rotate(-(2 * i));
}
else
{
for (var i = 0; i < _handCardViews.Count / 2; i++)
_handCardViews[i].Rotate(2 * i);
for (var i = _handCardViews.Count / 2; i < _handCardViews.Count; i++)
_handCardViews[i].Rotate(-(2 * i));
}
}
Never mind the unneccessary split between conditions, it's just easier to test right now
also if you just want to rotate by a specific number of degrees, you can just use transform.Rotate
for(var i = 0; i < weapons.Count; i++)
weapons[i].SetActive(i == selectedWeapon);
Yes I think that sounds good. I would use the one with three floats for x y and z degrees and set x and y to 0 and z to the desired amount right?
keep in mind that transform.Rotate does not set the rotation to what you pass, it rotates by that number of degrees
i would personally not even have those other checks and just parent your weapons to the weapon slots or whatever. then have the weapon slots determine whether anything is equipped there
Aww man.
yeah so use Quaternion.Euler like i suggested before
Ok, thanks
Uhm, why am I getting the error "Type or namespace "FreeTickets" cannot be found..." when im doing super basic stuff...
public FreeTickets fc;
In a different script
Not even sure what to show here..
do you have a type called FreeTickets
is it in a namespace?
have you imported that namespace into the other file?
make sure your !IDE is configured so that you can easily fix these issues using the quick actions and so that you can also automatically add using directives
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
Yo! Quick question, is it better to use Cinemachine or do my own camera system ? I want to do a simple camera capable of colliding with wall, follow and rotate around the player.
cinemachine
so I have this bullet and it spawns with the key press but unity is saying there's no rigidbody attached to the bullet clone
is there a rigidbody attached to the bullet clone?
it's a clone from a prefab
and is there a rigidbody attached to the bullet clone?
Why? There is not a single situation in which I should do the all thing myself?
you can if you want. but cinemachine will be better
no need to reinvent the wheel, it is better to focus on your game
show it
I'm gonna learn to use cinemachine then. Cinemachine allow you to do 99% of the job ?
now show the relevant code and the error
//from bullet
public class Projectile : MonoBehaviour
{
// start of void (ridigbody)#1
Rigidbody projectilRidigBobody;
void Awake()
{
projectilRidigBobody = GetComponent<Rigidbody>();
}
//end of start
// ----------------------
//start of Launch
public void Launch(Vector2 direction, float force)
{
projectilRidigBobody.AddForce(direction * force);
}
//end of Launch
// ----------------------
//start of Collision
void OnCollisionEnter2D(Collision2D other)
{
Debug.Log("projectil has touched" + other.gameObject);
Destroy(gameObject);
}
//End of Collision
// ----------------------
}
//from character
public GameObject projectilePrefab;
void Launch()
{
GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
Projectile projectile = projectileObject.GetComponent<Projectile>();
projectile.Launch(LookDirection, 300);
animator2.SetTrigger("Launch");
}
//End of Launch
well that error is correct. there is no Rigidbody attached to that object at all
there is a Rigidbody2D though which is a completely unrelated component
because it's a clone
no becaues it doesn't have a Rigidbody component
"RidigBobody" ?
oh now i cant someone at all until it hits something
Please not
just go with it
and it's not colliding with anything
does it have a collider
Trying to resolve item saving and loading, but I'm having issues. I've got an item database that contains items with IDs and Ids with items as two separate dictionaries. The player script will call load inventory when spawned which will simply read the file corresponding to the input string, then the database should assign the items and ids. I can see that the inventory is correctly filled with the item, but then in my inventory this line here breaks because the database is null. The database is assigned in the scriptable object for the inventory, but as soon as I run it, it just dissapears and I've got no clue why
alright its all fixed thanks a lot
share the full !code for the inventory class
📃 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.
https://hastebin.com/share/ajivimetoj.csharp hope this works
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
not used it before
seems like it's all there
you're overwriting the entire class inside of LoadInventory with whatever you have serialized. this includes those references to the other objects which you cannot just write to disk like that
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
If the object contains fields with references to other Unity objects, those references are serialized by recording the InstanceID for each referenced object. Because the Instance ID acts like a handle to the in-memory object instance, the JSON string can only be deserialized back during the same session of the Unity engine.
oh I see, cause of the this it's saving the entire class which loses the reference
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class doortry : MonoBehaviour
{
public GameObject character;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("collide");
character.transform.position = new Vector3(25f, 25f, 25f);
}
}
}
i get collide msg on log but it doesn't teleport my character
are you using a CharacterController
yes
hey guys, i need help with the unity starter assets third person controller. the mouse speed goes sooo fast when the fps drops .
how do i fix that ?
Do not multiply mouse input with Time.deltaTime
Lower FPS => greater deltatime => increased sensitivity
so i should just remove the * deltaTimeMultiplier here ?
Seems like the condition above fails
It's not detecting your input as a mouse, if it was the multiplier would be 1 as per the ternary expression
Changed it so that it should only load the inventory item container rather than the whole class, but now the json string is just empty. I've already gone and added the serialisable tag to everything but it's still being a nuisance
well the issue was more so where you load the save and overwrite the assignments that were serialized in the inspector
i only linked the ToJson doc so you would understand why that was happening
yeah it seems like the database is sticking there which is nice
not sure why this is suddenly happening though
it worked thank you bro
is it possible to set the value of a public gameobject variable to null through script?
cause gameObject = null; doesn't work :/
gameObject is a property of the script, you cannot set that to null but you can set other GO variables to null
See my next messages because there's an issue with the code (the asset's code?). It was multiplying by deltatime because it did not recognize your input device as a mouse.
float deltaTimeMultiplier = IsCurrentDeviceMouse ? 1.0f : Time.deltaTime;
Do you have a controller plugged in that could affect the value of IsCurrentDeviceMouse? Try to look where that variable is set for more clues
hmm no i dont have any controllers only the mouse
(Steering wheels / HOTAS included in the "controllers" devices)
what are you trying to accomplish here?
and it does say its a keyboard and mouse
what are HOTAS
as Steve said, you can't just set a mono behaviour's gameObject property to null
if that's not what you're doing, show your code
whenever I switch to a different item it changes gameObject variable "heldItem" to the gameobject that you switch to (all this works well and is simplified here so I don't have to explain it) problem is, when you drop an item the heldItem variable doesn't change and can cause some wacky issues, so I want to make that heldItem variable be nothing
gameObject = null;
doesn't work :/
Set the variable to null
thats
would this need to have some serialisable tag on it for it to properly serialise into json?
what I am doing
No
or just the type in the list
heldItem = null
Show your code.
