#💻┃code-beginner
1 messages · Page 56 of 1
Then saving is the problem. For example you never set 'age' to anything. I recommend you dont split the ui display stuff and the generating stuff into different methods, the way you do it is gonna make you error prone.
and my guess is that maxStatValue is not actually set to 100 in the inspector. If you have a serialized variable than the inspector will overwrite that value and the one you have assigned in the code doesn't matter.
@silver dock Saving all the data to playerprefs in lateupdate is a bit odd too. Would be better to save only when data changes
no its set to 100 in the inspector, and im not sure what you mean by your first text
what method should i save it in? only the update gets called again and again afaik, rest need to be called
yea its 0
In GenerateCharacter() you don't assign any value to your 'age' variable. https://hatebin.com/dplcplqucl
ah crap, UpdateUI() should be called in GenerateCharacter() and not SaveCharacterData()
What's the best approach to make any world gameobject do something when they are clicked?
Use the IPointerClick interface
i tried that, idk why it wont work on non-ui
had to add an image and put it under a world space canvas for it to work
is the scripting for pc game dev and android game dev same and we just have to build it for android after coding in pc????
the input handling maybe different
yes but except that????
i have just started unity so i dont really know anything about it
like are the classes and their methods same for pc and android?
there maybe some sdk targeted for either pc or mobile, but i think you dont need to worry about this
Tysm
does anyone know how to make the automatic firing mode work with the new input system?
private void Start()
{
switch (firingMode)
{
case FiringMode.Auto:
inputManager.playerControls.Shooting.Mouse1.started += _ => Shoot();
break;
case FiringMode.Semi:
inputManager.playerControls.Shooting.Mouse1.started += _ => Shoot();
break;
case FiringMode.Burst:
inputManager.playerControls.Shooting.Mouse1.started += _ => Invoke("BurstFire", 0);
break;
}
}
i don't know how to read if the mouse is being held and if it's being pressed
aww, onmousedown doesnt work on tilemap collider 🥹
ig no other option than to raycast and IClickable interface
Raycast, get hit point, execute tilemap.GetTile(point) to check which tile you hit
think you might also need WorldToGrid
Yeah, docs aren't clear on whether the point you pass to GetTile are world coords or cell coords
I guess they are since the method only accepts a Vector3Int
yeah, I just look at Vector3Int and assume grid
dont think id need to know what i hit, i just need to do something if the mouse hit any tilemap
anyways, what is the raycast format for making a raycast from mouse click to world pos?
ohh in that case you still need WorldToGrid
raycast pos != gridpos/tilemap
ViewToRay or ViewToWorld
Vector2 ray = mapCamera.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D[] hits = Physics2D.RaycastAll(ray, Vector2.zero, 1, LayerMask.GetMask("Ally", "Enemy"));```just copied from my other game 😅
havent used that viewtoray before though
do note if you choose ray instead of pos you need tilemap collider
this is just what i want to hit anyway
if i hit any of that tilemap, i want to show a menu
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var cols = Physics2D.RaycastAll(ray.origin, ray.direction, float.MaxValue, tilemapLayer);
not sure RaycastAll is really needed tbh lol
rc all cause the tilemap can overlap
it's weird yea 😄
yea i suppose
shame, cant derive from collider 🥹
what is even the point of doing that lol
also that switch 😬
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public Transform player;
public Vector3 offset;
// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
}
}
what is the error in that
yu tell me
wat
If you got an error, you need to tell us what it is
How would we know?
sry i started yesterday
looks like you have a copy of this script
duplicate script
how to fix that
Delete the duplicate
Delete the duplicateS
Show the project window where the scripts are
The error is saying you have multiple script duplicates
the filename might be different but the classes are copies somewhere, search through VS
Show the main assets folder too
there you go
And there they are..
Probably held control while moving them?
Which will copy move
Excuse me guys
Can anyone explain this fuction for me please ?
Thank you
Why the formula is Sqrt(jumpHeight * -3.0f * Grav) ?
player look
I enabled PixelPerfect on the canvas and now my background image just stoped displaying. Why?
Not a code question
#💻┃unity-talk
square root of jumpHeight * grav * -3
Yes, but why is (jumpHeight * -3 * Grav ) ?
There is no reason for it to use Matf.Sqrt, you can replace it with something else, especially since it doesn't seem to change
Oh
Unity wrote it
You mean why Gravity is even in here despite the existence of Unity's built in components like Rigidbody ?
I don't know
The guy I'm watching, he did it
because Character Controllers don't have gravity, just a simple form of it
so you have to make custom usually
WHATTTTT ???
https://medium.com/@brazmogu/physics-for-game-dev-a-platformer-physics-cheatsheet-f34b09064558
here is some outlines on the physics parts
What else can we use other than Character Controller ?
Rigidbody
i'll have handle in default for what to do when i hit many things
Thanks
eh why not just if(hits.length >0 )
but also that GetComponent is a possible race condition you might want to fix
always replace GetComponent wit TryGetComponent
unless you're doing parent or child i suppose
I guess the formula is the way it is so when you set the jump height to 3 the character will always jump 3 units up, no matter how high the gravity is
Why ?
Is there something wrong with GetComponent<>() ?
Ohhhh
because it gives you a sense of Defensive coding by having a nice check for null
le trygetcomponent hits[0].transform.GetComponent<IClickable_L>()?.Left(); 😄
if(hits[0].TryGetComponent(out IClicable_L clickableL))
{
clickableL.Left();
}
low budget tryget 🥹
same concept
u2017 dont have tryget 😭
yea, been a pain from the beginning
ehh make your own extension method 🧠
always had to getcomp, then null check a cached var
there are {} and Left() ?
yes just saw that u were missing that in switch 😉
What's with the Left() ?
ops just missing a )
idk its their method in the script lol
Yeah I saw this line of code and got curious.
Don't mind me
TryGetComponent is just a shorter way to write
var myComponent = transform.GetComponent<MyClass>();
if(myComponent != null)
{
myComponent.DoStuff();
}```
the ? operator looking at tryget while sipping tea
I wish I knew this before one of my test
when i am typing my code a lot of times the thing where you click tab to autofill doesnt show up
why is that
anytime you use a component is good practice to do != null before using it
just incase its not there you don't get NRE (null reference exceptions)
!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
configure it
actually, why does tryget have to exist when ? can do its job?
Unity components dont support it
?. cannot do its job with Unity objects
Doesn't check for the "destroyed but not null yet" state of them
Welp
Sleep time
It's half past 2 am
I got a game making class tomorrow
I mean today moring
also ??=
unity cant
(for unity components)
i dont even know what that does so ig izzfine
you can use it for Coroutines for example though
?., ?[], ??, and ??= yeah, these do not play well with anything deriving from UnityEngine.Object
so on each weapons item data it holds the weapons prefab
can i just instantiate the object as a child of the weapon holder and destroy whatever was being held originally to switch between weapons?
if so how do you instantiate as a child object
Instantiate has a few overloads that take a Transform as their last argument, this is the transform that will be the parent
shhh... I cant even hit the tilemapcolider```cs
if(Input.GetMouseButtonDown(0))
{
Debug.Log("Clicked");
if(!EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("here");
// var raycasthit = Physics2D.RaycastAll()
Vector2 ray = camera.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D[] hits = Physics2D.RaycastAll(ray, Vector2.zero, 1, LayerMask.GetMask("Clickable"));
switch(hits.Length)
{
case 0:
break;
case 1:
Debug.Log("Clicked one");
hits[0].transform.GetComponent<IClickable_L>()?.Left();
break;
}
}
}```I'm hitting a normal box colider though..
are you certain that hits.Length isn't perhaps more than 1 when you click on a tilemap collider?
you should also ideally be using the NonAlloc version of that method rather than allocating an array each time you click
i am currently testing with normal raycast
not all, still not hitting it
im hitting other kinds of collider though
when I am trying to make the score add by 1 every 1/10 of a second how can i code that (picture provided is my current code)
you need to show the current code. also why are you even using a raycast rather than OverlapPoint?
if(Input.GetMouseButtonDown(0))
{
Debug.Log("Clicked");
if(!EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("here");
// var raycasthit = Physics2D.RaycastAll()
Vector2 ray = camera.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero, 1, LayerMask.GetMask("Clickable"));
if (hit.collider != null)
{
Debug.Log("Clicked one");
hit.transform.GetComponent<IClickable_L>()?.Left();
}
}```
mb, but this is the current code
score += Time.deltaTime * 0.1f
it currently shows a rly big decimal in gamefor my score instead of adding it by 0.1 im not sure why
I forgot about delta time ty
it is continous though, it doesnt do ticks that are actually each 0.1 sec
yea i see that
if you wants ticks, usea coroutine
btw are you certain the colliders are where you think they are? since you've not bothered to enable gizmos we can't actually see them
its still a rly long decimal
yes that's what happens when you just print a double without formatting it
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
the gizmos are over the tilemap, lemme get a SS
while you're at it, you should print useful information instead of these practically useless "here" logs
idk if it's visible, but there's a very thin green gizmos in side the tilemap layout
i dont get it
you're just printing the double without formatting it. so it's going to print the entire thing. and if you haven't learned about floating point inaccuracies then you should go learn about that now
string formattedFloat = score.ToString("F2");
for 2 decimals
there still is a lot of decimals and i just tryna get a whole number
then F0
show your code
lmao
you're not even using the formattedFloat. you're also formatting it before you assign to it
so what should i do
🥹
use the formattedstring in the line that changes the text
i was trying to follow along with a tutorial and they said to copy the script on the screen but dont ever show all of line 67 here:
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.
Quaternion ClampRotationAroundXAxis(Quaternion q)
{
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1f;
float angleX = 2f * Mathf.Rad2Deg * Mathf.Atan
angleX = Mathf.Clamp(angleX, minimumX, maximumX);
q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX);
return q;
}
what is likely to be the end of that? " float angleX = 2f * Mathf.Rad2Deg * Mathf.Atan"
i believe the correct answer to solving this issue is "use cinemachine"
Is there a common/known way of avoiding OnTriggerExit2D being called when a player exits out of the game while inside a trigger?
When I exit the game in Unity while inside a trigger, OnTriggerExit2D is called and I don't want that to happen
i don't think that is supposed to happen 🤔 are you sure OnTriggerExit is being called when the game is closing?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that no work 😦
but unity says that "sentences.Clear();" doesnt references an object
show your code
you changed nothing functionally. all you did was move the line
so wat i gotta do
A programming course
you're probably calling StartDialogue either before Start has been called or on the wrong object (like on a prefab)
If you can't solve an issue of this level then a programming course would be best
start with the beginner c# courses pinned in this channel
Because at this rate we would just end up babysitting you through every script you make
look at your code, at which point do you want to turn scrorefr into a string?
instead of using the ScoreFr variable you should use formattedFloat
also you should probably set formattedFloat after you update Scorefr
inb4 formattedFloat += Time.deltaTime * 1f
OMG!!..... IT WAS THE RULETILE...
ruletile is using the sprite as collider
now i gotta manual these all ig
so just changing the naem of the variable?
lol no
no
Dear god
please do yourself a favor and go learn the basics instead of wasting your time by guessing how you are supposed to code
read your code slowly
point out where you use formattedFloat
not where you assign it, but where you actually use it
to make my variable scorefr formatted
so the line where i set the text
the problem is that the name Textmesh works but the dialogue not
right
the line where i set the text
tbh it's a "learn c#" scenario already
but what variable are you using there
huh?
scorefr
and you should be using...
formattedFloat
there we go
but i tried it
It's not a float, and it's not formatted lmao
What's the point of multiplying by 1?
the name is working and it starts aswell from the StartDialogue but the dialogueText doesnt work either it has to start with the StartDialogue function
That doesn't work if the player crashes right?
what do you mean by "doesn't work"? are you still referring to the NullReferenceException?
it doesnt show up
What is formattedFloat
nothing works if the player crashes
well i'm not a mind reader so i don't know what you mean by "it doesn't show up"
as you see here
Idk I was told to replace the variable
I believe it would be faster to just take a C# course instead of guessing
if you cannot even explain what you think is supposed to be happening then i'm not going to continue to try helping you
look
that is not what i meant
aight... that's now the most anticlimactic debug for the month..
in here, just replace "Score: " + scorefr; with "Score: " + formattedFloat;
its really not that hard
right, but a trigger could still be abused that way if they deliberately crash their game and thus leave the trigger in the eyes of the game
Can you please explain what formatted float does
Ok, that's actually getting funny now
Once again, what is formattedFloat
There's nothing called that in the code
click the message i replied to
if is your double formatted to 0 decimal places like you asked for before. this is why you need to stop wasting our time and go learn the fucking basics man
what? The player has crashed there is no game
someone else gave them that line unfortunately
He changed it because he has no idea what he's doing. Just let him go so he can learn the basics, nothing good will come out of this
😔
actually true, but i still want to avoid OnTriggerExit being called just to be sure
If the question is just how to display a float with some number of decimals, why not just use ToString with a number formatter?
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
have you even bothered confirming that it is being called in that circumstance? because it shouldn't be
good luck trying to catch something when your code has completely stopped running and is probably no longer even in memory
yes, the code debug.logs whenever it exits the trigger and it debug.logs that specific message everytime I stop the game
but i thought that was normal since i haven't done anything weird
weird seems it's probably a quirk of 2d since it does not happen with 3d. either way though, it really shouldn't affect anything the game has technically already started quitting at that point since it's called after the Application.quitting event is invoked
I was doing brackeys’s course on how to make a video game and the way he did the score made me want to do it a slightly different way I started yesterday and I am still learning how everything is used together
there are beginner c# courses linked in the pins. start there.
Ok got it
Should I be starting with c# and unity in the first place tho
my opinion is that you should learn c# separately from unity first. then it will be easier to learn how to use the unity engine's API
Though it can be valuable to look at it in a Unity context for practical applications and examples of more general c# concepts
heres the result btw
Inheritance as a whole is really easy to understand with game examples etc.
Still not it
i legit copy pasted what u wanted me to do tho
You should instead read things and learn what they mean instead of copy pasting
i now understand what formattedFloat is but idk y its not workin
formattedFloat does not exist
do i gotta call it
You have nothing by that name
thats why i was confused as to why _tud was giving me that code line
but you did have a variable by that name. you just removed it for no reason
cuz it didnt do anything
which, again, is why you've been told to just go learn the basics
ima try once more
because you weren't using it. stop wasting your time and go learn how c# works
People on this discord aren’t professionals dropping polished videos, not all help is going to be perfect and various assumptions will be implied in certain suggestions. It’s a lot harder to take suggestions at face value if you don’t understand them fundamentally
It’s really not easy starting to code
fun fact, this is what they are trying to use. it was just being stored in a local variable because someone else posted that as an example and they just took it literally and dropped the line into their code with no thought as to what it is or how to use it
i am on the website, with no help as to what to look at
because dropping a link is enough
go learn the basics
which pinned thingy do i use
Intro to C#
Then it just becomes intuition
shows you how to use, declare, and assign variables
why is there a dollar sign
so im using the dollar sign to call a variable within my statement?
start at the beginning and do all of it. and pay attention to it.
you clearly missed the part where it explained what that was for
honestly for that specific code tutorial example the $ seems a little unnecessary ngl
string interpolation is used a lot throughout that series of courses. they should pay attention to what is being taught to them so that they understand the following courses
I don't disagree but at such a early stage where imo a big aspect of stuff clicking is patter recognition it is abit of a curveball considering it's specific to strings and somewhat of a shortcut to doing that.
I think a big moment that helps a ton in understanding code at the start is figuring out what the author gets to name themselves and what is required based on the language rules
Hey can someone give me an idea of how to make a character 2d move with buttons
That's quite vague. Why not look for a 2d movement tutorial or follow unity learn
Capture button input.
Create a vector from it.
Apply that using the rigidbody or transform
can i make an object hold a prefab thats in the scene that can be changed?
so that if the active weapon gets swapped with another one the 2 prefabs switch with each other
imagine it actually explained what that was for tho
you mean like this where it even helpfully links to the documenation page for it?
They do... the screenshot is from it lmfao
where
this is why i told you to start with the first course and do all of them. then you wouldn't miss stuff from literally the second lesson in the first course
Are there any easier languages with simpler syntax
That can help me build up to c# cuz I’m clearly not ready
it's going to take you even longer to learn if you go and learn a completely different language first
Oh
C# is pretty darn easy compared to many languages honestly. But there's things like python and ruby I guess. But it'll hold you back because they are substantially different. Just do the tutorials without skipping anything.
Is there a way to refrence these values in a script
Reference the component. Access the properties.
those are the transform.localPosition localEulerAngles and localScale
I mean how would write it in the script
Thanks ill see if that works
I typed the message as the other one was sent
also make sure to look at the docs
https://docs.unity3d.com/ScriptReference/Transform.html
I actually did it this way, I started with html/css and moved to javascript then to C#. See Supersimpledev's tutorials on Youtube to get started
Is it possible to see values for a different object
what do you mean by "see values"
easy: reference the other object
how would you write that
Just plug in the obj name?
i'm gonna go learn how to make a bowl a cereal, learn how to cook a batch of meth, then i'm gonna finally learn how to bake a cake. that's basically what you've claimed to have done to learn c#
making a reference should be something you outta learn, its not a particular code
eg
[SerializeField] private Transform someObject
ideally you use Components / Object (classes) directly instead of just Transform
depends what you do
Okay
you mean javascript is harder?
where did i say that?
uh lets not reference hard drugs
yes, both of those things are not that difficult. but one of them is ruining lives
lmao
Prefabs dont exist in scenes, they exist in the project files, scenes can have references to prefabs though - what is it exactly that your trying to do? What is your use-case to add a bit more context to your question? Are you just trying to have input swap 2 prefabs that have been previously instantiated into the scene or something else?
(Also to extra clarify, Scenes can have references to prefabs and they can have instances of prefabs)
^ Yes, good note "instances" was the word I should have used, as its likely more relevant to what they are wanting to do
Hi all! Having an issue here with my script (not made by me). Whenever the VRChat SDK tries to build my avatar, it comes back with these compiler errors and due to my non-existent knowledge of coding in Unity, I need help lol
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
public class FindAnimationClips : EditorWindow
{
[SerializeField]
private List<AnimationClip> _clips = new List<AnimationClip>();
private void OnEnable()
{
var serializedObject = new SerializedObject(this);
rootVisualElement.Add(new Button(GetAllClips) { text = "Get all clips" });
rootVisualElement.Add(new Button(SetToLoop) { text = "Set Animations to loop" });
rootVisualElement.Add(new Button(Unloop) { text = "Disable Animations loop" });
rootVisualElement.Add(new PropertyField { bindingPath = nameof(_clips) });
rootVisualElement.Bind(serializedObject);
serializedObject.ApplyModifiedProperties();
}
[MenuItem("Tools/Multi-Anim Loop Toggle")]
private static void Open() => GetWindow<FindAnimationClips>().Show();
private void GetAllClips()
{
string[] guids1 = AssetDatabase.FindAssets("t:AnimationClip", null);
foreach (string guid1 in guids1)
{
Debug.Log(AssetDatabase.GUIDToAssetPath(guid1));
AnimationClip animClip = AssetDatabase.LoadAssetAtPath<AnimationClip>(AssetDatabase.GUIDToAssetPath(guid1));
if (!_clips.Contains(animClip))
{
_clips.Add(animClip);
}
}
}
private void SetToLoop() => CanLoop(true);
private void Unloop() => CanLoop(false);
private void CanLoop(bool canLoop)
{
foreach (AnimationClip clip in _clips)
{
var settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.loopTime = canLoop;
AnimationUtility.SetAnimationClipSettings(clip, settings);
}
}
}
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
Its not a script from VRChat, its a custom script made a mod and a helper from this server
Its not something for VRChat either. Its stopping the upload of the avatar because the script has compiler errors
then it probably needs to be put into a folder titled Editor
Ah! Perfect6! Might I ask why that worked?
content inside an Editor folder will not be included in the build process since it will be considered part of the editor assembly
I'm suddenly getting this error and 2 warnings that I don't recognize... I'm not positive their related to each other... Anyone familiar with these?
the error is an editor error related to some graph editor window you have open. it can typically be ignored but if it bothers you just close which ever window uses the graph editor (animator, shader graph, etc)
the last two logs are warnings and unless you're writing code that uses jobs or native collections you can ignore them as well
In my scene I have some gameObjects that are inactive due to a toggle state. I want those inactive gameObjects to also get destroyed using the method below. But this is not happening. What changes are required ??
private void DestroyOtherAxisFrames(string node)
{
GameObject[] axisFrames = GameObject.FindGameObjectsWithTag("AxisFrame");
foreach (GameObject obj in axisFrames)
{
if (obj.name.StartsWith("AxisFrame-") && !obj.name.Equals("AxisFrame-" + node))
{
Destroy(obj);
}
}
}```
FindGameObjectsWithTag cannot find inactive objects
https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
any alternative then?
I think they started popping up when I tried to create an async task, but I backed that code out. I don't believe I have a graph window open so I'm assuming I'll just need to restart unity to clear that one. Thanks!
get a proper reference to the objects instead of using any of the Find methods
you absolutely do have some window using a graph view open, otherwise that error would not happen. unless it is stale from when you did have one open
I don't recall EVER opening one, because I don't even know what it is. Lol. But that doesn't mean I didn't open it at one point by accident. I believe you that's what it's from, I just don't have it now is all I'm saying
Oh holy hell I just had a bunch of them spam when I switched to the animator window now
my dude, the animator is a graph view
like, it's literally one of the two examples i gave of windows that would cause that error
Oh shit my bad, I didn't see you say the animator
Starting vector, travel a given distance at a given direction, new vector. How do I calculate the new vector?
PointA + direction * distance
Is there an easy way to freeze gameplay (like objects falling, stopping animations) without having an effect on UI / UI animations?
setting timeScale to 0 messes with more than just the physics stuff 😄
You could set the fixed timestep to 0 I guess.
Oh yeah right, ill try that, thanks 😄
Danke
!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.
now might someone know why i can save my game on my pc but on others and doesnt do anything, and i am using Application.persistentDataPath which im finding odd isnt working on other computers https://gdl.space/oqedusiziw.cs
Do you see the error from the try catch block?
How are you confirming that it doesn't work then?
Ive had my friends try to make a new game on there pc's
And?
How are you checking of the error was printed or not?
https://gdl.space/qoninupupu.cs now this could also be the cause but im still not finding anything wrong
I even gave them the project files to load the project
and still nothing
i'm sorry for such a late response but yeah i just to be able to have a child GameObject be able to be changed to whatever item is in the active slot
now i was thinking at first that it was maybe there anti virus deleting files but thats also not the case either
i'll probably have to Destroy, the Instantiate
How do you know that the error was not printed?
Because it never displayed itself or in any logs?
What logs are you looking at?
i looked through everything in the built version and project and still have nothing
indeed using screen share they went through all of it
endless something was missed im at a loss here
Try removing the try catch and letting them play the new build.
Ill give it a go and let you know
Also add more verbose logs at each stage of saving/loading.
will do
You want to see how far the execution went.
for sure
That may be up to how you design your game, for mine I instantiate the weapons once, make them a child then disable all of them - I then have only 1 referenced as a variable, when I want to change weapons, disable the referenced one, enable the one I want to change to, and update the reference - if you will be destroying and instantiating weapons often (for example, maybe enemies drop weapons) you could look into an object pool
To give you a general idea of my approach, it looks something like this:
public Weapon drawnGun;
public List<Weapon> allGuns;
void SpawnGuns() { ... }
public void SwapToGun(int index)
{
if(drawnGun != null) {drawnGun.Disable();}
drawnGun = allGuns[index];
drawnGun.Enable();
}
Thats not verbatim code, but a general idea, some input might call SwapToGun and pass the next/previous index to switch to, and if a weapon is already in-hand, hide it, otherwise just swap the weapons - and SpawmGuns is where all of them would get instantiated and stored in the list once, or handled by an object pool if need-be
i think my biggest problem now is referencing the child object weapon that is getting destroyed
and then instantiating a new weapon in place of it
Why might you want to destroy it as opposed to disabling it? Do you only plan to use the weapon once?
well no but there's a lot of different weapons
i don't see why you need to destroy the weapon (unless it's single-use), but you should already have a reference to the gun you want to disable . . .
it uses scriptable data and that holds the items prefab in it
if i just disable it that means i have to put every prefab as a child object of the holder?
but only some items have prefabs (only weapons or visual items)
it's a 2D game that works like an RPG where you have to craft the weapons and stuff
If you do not start with these weapons, then it might make sense to create them when you need them, and then keep them referenced in case the player wants to use them again at a later point in that game session, but if its a collection of weapons the player starts with, you could spawn them all initially in your "holder" and then hide all of them except for the one the player is currently trying to use - for example if you have a craftable sword, you dont have to instantiate that sword to your "holder" until the game is in a state where that sword should exist (ie: they have the materials to make it, its stored in some saved inventory, or part of some loadout, etc)
so basically keep all items in the quick bar slots (they are all weapons or items the player can switch to holding) as disabled until active
and those disabled GameObjects become Destroyed and Instanced when being replaced by different items/weapons
i guess that makes sense
Thats one way, since you have a "quick bar" I would just keep all those items in the quick bar disabled until the player swaps to it, and only destroy/instantiate new ones if the player decides to modify the quick bar
i wonder how unity does the endless grid thing that the beat saber level editors have
Probably a custom shader.
the custom platforms creation does require it to be made with a unity project with a 2018 version of the editor cuz of all this custom stuff (including shaders)
like a project from the creator of the mod has all this custom stuff in it
Okay
just play the audio clip. what would be the use case?
History log prints in Debug.Log after being loaded, but doesnt update the UI text, pls help
https://hatebin.com/jcziovyhot
i think he wants to play the audioclip through the microphone
how come you are doing historyText.GetComponent<TextMeshProUGUI>() when historyText is already a TextMeshProUGUI?
If you manually put some text inside the tmpro component, do you see that one?
thats not the issue here, even before i added that it wasnt updating the text
I understand that, but still that get component does nothing. You said the history log debugs meaning this is probably an issue with the tmp component. Did you try manually putting text in it and see if its visible?
Yeah its visible
it just doesnt update it, cause its empty even in the inspecter
then i believe it isnt updating the correct tmpro object
do you have any console errors/ can you show a screenshot of the object that has HistoryLog on it?
there is only one historytext, and its correctly assigned
no console errors
if its truly referencing the correct object and the debug is printing some text for loadedHistory (not an empty string), then my only other guess would be that you are calling ClearHistory() somewhere or setting the text to empty somewhere else
Or referencing a prefab
true it is probably referencing a prefab
there's not a single prefab in this project
Then one of the things that bawsi mentioned.
You can use a breakpoint or Debug.Break ot examine the state of the game at that point in time.
See if the text changes.
How can I make this block move, scale and rotate?
Adjust the parameters in inspector or drag it with your mouse
good guess
protip if you didnt use this, you can find anything thats using your method with this button Find All References
Haha i just tried removing the method, and saw the console error, thanks
https://paste.myst.rs/vzfw56pq @summer stump
a powerful website for storing and sharing text and code snippets. completely free and open source.
So you have to change the type of the Text variables to TMP_Text
You had it as that from the screenshot here
#💻┃unity-talk message
Did you change it back?
yes
Ok. Well that is the only issue. Change it to TMP_Text, then drag you Score object and the Timer object into the boxes. That is it
Text is a legacy type of component you aren't using. So you do not want that
can anyone explain why the function not showing on OnClick
Did you drag the script into OnClick or an object WITH the script attached? It has to be the latter
it's showing on my other project, not on this.. strange
still not showing up, i dragged the gameobject instead of dragging the script last project
Got any compiler errors?
nope
It doesnt match the signature of the UnityEvent
Can you show the inspector again WITHOUT the dropdowns showing
Oh yeah huh. Multi-parameter methods aren't able to be subscribed via the inspector afaik. You have to subscribe via code
Good catch Lazy 😆
You can define a UnityEvent<string,string> and subscribe there.
But yes it's likely best to just subscribe via code and define where the parameters come from there.
That MainLogin class will need access to the Username and Password text fields to get their values.
i could do it this way... but not sure its efficient/good
Wrap the start coroutine to another method
It's completely reasonable to hook into events this way.
In what way would it not be efficient or good?
something about faster, tbh idk
but its work on other script
"hello" is the function
Does it have two parameters?
It has 0 parameters
That was what we said above, yes
Only works with 1 or 0
In the inspector of course
mb, bit skill issue with english language
anyway thanks! 
No worries!
Is there something with this scriptable object script?
i cannot assign the items i create with it
show the script in the unity folder, the error is saying the file and class name are not matching
like in the explorer?
in the unity project tab
but yea thats still a matching name
🤔 maybe u need to recompile or something, unless i am missing something
Isn't he trying to add the PetData as a component?
im trying to assign them here
Yeah, you need to drag it into an Element slot
yeah which leads to the error i showed above
screenshot console
the error is different for me if i try
Whats the code for the PetItems list/array?
How do I get the light to invert? So only the edges are lit up instead of the edges being shadowed
its empty
Like he asked, screenshot it, some new people hide the errors.
#archived-lighting probably? not a code question
Then the code for your list/array
this?
Ah, are you adding the script instead of a scriptable object? Did you create one?
wait, wait wait.
Are you trying to drag the script into there or a PetData asset you created?
PetData asset
This doesn't seem right to me. Can you create a new one?
yeah i tried creating multiple new ones, its the same. is my unity broken? lol
Well I don't know then. Perhaps someone with more knowledge on SO's can help.
sometimes Unity can get weird like this if you renamed the class name then the .cs file or vis versa
try restarting Unity, or if that doesn't work deleting the Library folder from your project folder (this just holds cached data that it will rebuild when you delete the folder and re-open the project)
thanks for the help guys, fixed it
Trying to use root motion atm on my character. Noticing a weird thing on the animator tab where my values (Lateral, forward) seem to constantly be changing in the animator and causing the character's animations to kick in some times. Like walking forward without any input from me.
Anyone have any ideas where I'm going wrong?
Code is too big for discord limit apparently so I just paste linked it
Can somebody help me with this line
Ship_Rigid.AddForce(Ship_Rigid.transform.forward * EngineForce);
It does not move the ship at all
Its in 2D, everything is set up properly
Well if you say everything is setup correctly, what's the EngineForce then?
set the engine force to be 100000
Oh, and it's 2D, forward is not valid in 2D. Use right or up.
Forward means it goes into the world.
// Calculate engine force to add
float EngineForce = MovementInputRaw.y;
EngineForce *= Acceleration;
EngineForce *= Time.fixedDeltaTime;
ahh thats probably it
Yep that fixed it
thanks

HELLO
I am trying to change this code from this video I found
https://www.youtube.com/watch?app=desktop&v=3sWTzMsmdx8
(it is a movement script)
I am attemting to change it from aswd keys to the arrow keys
Can I pritty please mabey have a little bit of help???
Source & game: https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller
Extended source: https://www.patreon.com/tarodev
Learn how to build an amazing player controller.
This Unity character controller is built using custom physics and incorporates all the hidden tricks to make it feel amazing. 2D player controllers can be difficult to get ...
This is the code
If it's using GetAxis then it already works with arrow keys
Anyway you haven't explained what issue you're having
I would just like to try and rewrite the code but to work with just the arrow keys and not the aswd keys
Like a local
game
There is no need to rewrite any code to achieve this
oh
Go into the input manager and remove the bindings of the axes from the wasd keys
Well thats good
Okay
right i have just relized that I have no idea were that is

No you're still looking at code
Remember when I said this has nothing to do with code
Stop looking at code
okay
Why this is happing?
Your code is trying to access a reference that isn't assigned to an object
how to make 2D animation work when timescale=0?
@wintry quarry
Yep that's the input manager you found it
solution?
Stop doing that?
Make sure you have properly assigned all references before using them
I have a pretty complex UI with lots of different windows and elements in it
Is there a way to trigger an event on right click, no matter where that right click happens?
Specifically: I have a button that changes the cursor to a sell icon and then when u click an item it sells that item
But I want the cursor to change back to standard if you right click anywhere
My issue is this logic is currently on the Item, and there's plenty of places on the UI that are not items
cant you capture input in update loop?
yeah but it only captures it when I click on an item
I have like 10 different UI windows that can all be open or closed
Hi! I'm making a sort of Space Shooter type game and was wondering how I would make the enemies spawn from any direction rather than from the top only. Please reply to this message so I get notified. :)
I can show any material needed
there's tons of youtube guides on this
How have I not found any? I guess I'll look around more🤷♂️
idk what is your design but you should be able to capture any mouse input independent of any UI
I'll check it out! Thank you
does anyone know how to create a trigger level changing script...?
a what what?
a object in game 3d scene, that has if you tap it with your player capsule it changes to another scene
ill try it, thanks
ok it worked
thanks
but I need to add a spawn point for the capsule now for the next level, is it just copy capsule and paste to the next level?
I got it, copy and paste the capsule and add the camera to it, worked, it properly level transitions to the next of a player start in the right zone
Hello, is it possible to language localize a word in which the code looks for any occurrence of that word in all strings in the game without having to go to each text that has a string and put a localization key there?
Maybe with some reflection you could implement something like that, but I doubt there are assets that do that, as no one does localization retroactively.
Could you explain more what do you mean by reflection? although I don't see it a good practice for a programmer to spend hours translating words and sentences from language to language and then go to the 500+ places where those words are implemented in the game as texts and add keys for them (apart from what you said)
Reflection is a feature in C#/dotnet for coding the code. Sort of meta programming. It allows you to find and manipulate existing code in the project.
No, normally the programmer doesn't go through the game text to localize it. Most decent projects, use some kind of localization system(either third party or developed for the project), that takes a key and returns a string based on the application/system language.
Programmers are only involved with writing/integrating the system. The translation and asset organization is usually done by designers or some other miscellaneous role in the team.
Gotcha, makes so much sense, thank you
The point is that localization is something that is supposed to be considered at the early stages of the project.
That indeed is the right thing to do
is it possible to call a function where some part of is name is a string variable ?
i have in mind something like this :
{
MyFunctionmyString();
}```
Okay thanks i didnt know i could use invoke for that ! So i did something like this
{
MyOtherC#Script.instance.Invoke("MyFunction" + myString, 0);
}```
Use string interpolation for strings that use values, it's cheaper
($"MyFunction{myString}", 0)
Is it cheaper than using string.Format or string.Concat to do something similar?
Using $ is shorthand for string.Format
aight so im using this to make my object move around, when i just spawn in the object, it goes straigh ahead, everything is fine n dandy, but whne i play around with the rotation, then try to move... then it becoems just a bit off, dont know why tho
What does "a bit off" mean and why are you using trigonometry?
Why not just use transform.forward * movementSpeed?
a bit off = doesnt work right 💀
cuz i want the direction to depend on where the object is looking
which depends on the rotation
note: after further testing the pivot point was off
so ill fix that n see
wait... forwards automatically checks where it is looking?
Yep, that's the whole point
You don't need to do trigonometry
This statement is so vague as to be meaningless and doesn't help anyone fix your problem
Hello,
I'm trying to make a simple 2D character controller for a platformer game. (code -> https://paste.ofcode.org/AFzVG46MF9c43xBKUJGUUb)
the code is simply supposed to provide a player that can walk on flat surfaces and jump while affected by gravity.
My problem is that I can't seem to find a way to handle diagonal collisions. If my player moves diagonally and hits an edge it gets stuck ...
I am supposed to first check for horizontal collisions, move horizontally, only then check for vertical collisions and move vertically. But still it fails to check .. can you give me some hints of what I may be doing wrong .. ?
the direction wasnt forward
but yea ill js use the .forward
alright so... quick question...
I had my teacher on how to copy components, since i had a newer model for my object. When he was showing me how to do it, he dragged the new model from the project folder (bottom area) straight to the layers instead of the scene, and now like i cant see the object, i cant drag it from the project folder area to make a new one, and yea uhmmm what
like uhmm i assume that when it was draggon into the layers it created the object
but i dont see it in scene
There's no such thing as "dragging it to layers"
do you mean the hierarchy?
just double click it in the hierarchy to see the object
or press F
yes
doulbe clicking or pressing f is uhmm not doing anything
try again
oh
wait
you're in game view
switch to scene view
this isn't a code question
these are basic general unity questions. #💻┃unity-talk
This is my first day ever actually trying to learn Unity. I'm trying to add a feature to this open source Unity 2018 project, and I'm kind of stumped. I see these components have (Script) appended to the end, but I don't see any script fields to open said "script" in Visual Studio. Am I misunderstanding what this is?
Are these base Unity objects just referred to as scripts?
Components are scripts
not all scripts are components
And those components are built-in. You can write your own
yes GameObjects carry components
"object" has many different meanings in many different contexts
in the epistomological sense, everything is an object
in the C# sense, everything is also an object
and then there's the UnityEngine.Object which all of these things also are
but in the sense that Unity has GameObjects, components are NOT GameObjects
they are attached to them
Thank you for explaining that to me, I appreciate y'all
"Pivot" refers to the origin point of rotation according to the model itself, while center is calculated by unity?
ok so...
if both are wrong
and dont rotate in the actual middle
does that i gotta change the pivot point in the model?
yes
could an incorrect position for the rotation point be the cause of this not working right?
(not working right = the direction isnt actually forward and is almost unpredictable)
maybe you need transform.up, is your game 2d or 3d?
Translate is already local. Use Vector3.forward instead of transform.forward
3d
why did you switch from AddForce to Translate
they are not 1:1 replacements
as digi said if you're using Translate, you would use Vector3.forward not transform.forward
i didnt know how to make addforce work
but yk this works now
i have just gone cold turkey off of Translate if something has a rigidbody or any colliders
every time I put transform.Translate or set transform.position manually, i wind up needing to refactor it later anyway to make it work properly
how do i interact/see an empty
what
there's nothing to see
figured it out
you interact with it just like that
it had spawned somewhere far away at first thus my confusion
You may be able to solve that with a frictionless PhysicsMaterial2D: https://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html
Why are you doing a separate boxcast for vertical and horizontal movement
combine everything into one
and it will work fine
you can also cast in the direction you are moving
which is exactly what you would do when you combine everything into one cast + one move
also, i would avoid BoxCast in favor of Cast in case you add edgeRadius in future
i had to refactor my BoxCasts like that before because of that
I assume you are doing separate casts now to check for wall floor and ceiling separately
I would use Cast. Cast outputs RaycastHit2D, which has a field for normal.
The normal tells you the angle of contact, so you can decide if you want to consider yourself grounded or on wall etc based on a single given hit
i currently use OnCollisionEnter/Stay to know if I’m grounded, and I’m going to be changing in future because these methods evaluate after your physics update
where did the other guy’s message go?
probably solved it
im making an thing that can throws projectiles, so i was thinking, if i make it a rigid body, and i then give it an upwards speed and a forward speed, would the gravity handle the rest?
like if set upward speed to 100
would gravity make the speed 100 - gravity * time
gravity is a global variable
so you can’t give just one thing left gravity, if that is what you mean
but if it is a dynamic rigidbody, then you can start it with upward speed, and gravity will make it accellerate down
as it travels
no i meant if i have a speed that is taking an object up, but this object is affected by gravity, how would the speed change?
i would use a kinematic equation to calculate the speed you need to give it, btw
what i am afraid if that.. like.. suire gravity will result in a speed down, but this speed wont be reduced from the speed i give to the projectile, so there will be a speed dragging the projectile down, but the upwards speed stays at 100
gravity is simply doing Vector3(0, -9.81, 0)
unity uses Euler integration.
Every frame, you move by deltaX = deltaTime * velocity.
And deltaVelocity = deltaTime * force / mass
i would NOT want:
speed up : 100
speed down: gravity
but instead want
speed up: 100 - gravity * time
gravity is straight acceleration, so every frame, velocity += gravity * deltaTime
yes id like to have a speed i give to the projectile - velocity
if you start with a large upwards velocity, it will take many frames for gravity to completely change your direction
if it is a dynamic rigidbody, try rigidBody.velocity = newVelocity;
or myRigidbody.AddForce(additionalVelocity, ForceMode2D.Impulse);
but does the velocity grow so big that the speed i gave originally doesnt matter or is the speed i had originally reduced by the gravity til it eventually becoems negative
is there a script that combines animations at all?
combines animations?
what that even mean
the velocity changes whenever you change it. if it is a dynamic rigidbody, velocity also changes whenever the physics system says to
if it has gravity, it will have velocity += gravity * deltaTime every frame
and there is no terminal velocity unless you program it
i have multiple animations that follow a sequence i would like to be able to get a script to put them one after the other and combine them into 1 animation]
you mean an animator?
an animation is like a sequence of sprites that show in a given order (with/without looping)
if it can turn multiple animations into one sure
an Animator is like a finite state machine that lets you change between Animations on one gameobject
Animator wont change the original keyframes or other animations
its just playing the clips
scripts can tell the animator which state to go to
i find it hard to explain things
i would like a script where i can drag in 2 or more animations it then creates a new animation putting them in sequence
This might be the tool to allow your script to know when one animation ends, I think
how can i check for collision but not any colission but between two specific objects
since this is for vrchat i cannot change the animator
how can i make object have collision trigger but keep working colisions
Use Tags or Component filter
thanks
OnCollision callbacks give a Collision/Collision2D argument. This object has the collider you hit in it
can you change object visibility in game
turn of rendering but keep everything working
yes ofc
I’m trying to explain that you might be able to use the fireEvents bool to get messages when one animation ends
okey thanks
thanks
that way you can have a script that automatically starts one animation the moment another one ends
understand?
i’m not super familiar with doing this, but that is what that feature seems to be for
custom scriptss cant be uploaded for vrchat so although that would work in unity it wouldnt work in vrchat
this should be in
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
and its not code related
if you can’t use code, then that cannot be a code question
I've gone ahead and tested this behavior and confirmed that it happens in both editor and build but only for OnTriggerExit2D, it does not happen at all for OnTriggerExit. it is also called after the Application.quitting event is invoked which is even more weird. Now that the bug reporter tool is working again today i've submitted a bug report so hopefully it can be addressed
wow, thanks! weird that it only does that in 2d, seems not intended?
weird that this hasnt been seen before
yeah i assume it's probably not intended. it could also be a more recently introduced bug. what version of unity are you using?
custom scripts can be used in unity but cant be uploaded to VR chat. The code I'm looking for is a tool to combine multiple animations into one. Since this will all be done in inside unity there is no need for it to be uploaded to VR chat and thus can be used
2022.3.7f1, so one of the newer ones yeah
unless i gotta update i havent been paying attention to that
if my prefab uses a script and i change the script in project files will the script used by prefab also change or by making a prefab all components are copied to make it functional separate object
well you're about 5 patches behind, but that is still a fairly recent version. but i did confirm the bug in the latest 2023 tech stream release so 🤷♂️
nothing is copied. Scripts are referenced
if you change the script, it changes the script
that would be a nightmare otherwise
yes, if I have 5 different prefabs with a MyBehaviour component, and I edit MyBehaviour.cs, all of the prefabs just reference that new (altered) file
my wall have box collider2D and my bullet have circle collider2D with trigger
bullet.cs->
void OnTriggerEnter(Collider col){
Destroy(gameObject);
}
the bullet doestn disapear when it hits wall
Yeah mb, Sorry i didn't say I solved it by making a seperate hitbox and I made a mistake in my message.
Can I ask DOTween related questions here?
could i for example
void OnTriggerEnter2D(Collider2D col){
col.health += -10;
}```
i need to get the script atached to the object
collider does not have a health property. you can use something like TryGetComponent to check for a specific component that has a health property and get it to assign to it
Collider2D param holds the object u hit
Can anyone show me pseudocode for reloading my weapon with reserve ammo in mind?
yep, assuming it's code
whats "reserve" ammo mean
thanks
Im having a weird issue. With TMP line break is not working properly i have this. In a TMP text in canvas. The info gets taken from a string list and get feed that. If i manually type the exact line then \n works as intented. But when doing it via script with the text.text = list.text its not
It's "reserve", not "reverse"
ops mistyped ..anyway , same question
The number of ammunition you currently have that's not in the weapon magazine
so check if magazine remaining == 0 then grab from the reserve ammo
or put reserve ammo in the mag
if reserveAmmo is > clipsize, reload
hmm, no, doesn't need to be more than clipsize
more than 0
if(currentammo > clipsize )
store ammo in reserve
?
if reserveAmmo is > 0, clipsize = full, reserveAmmo - clipSize
There are three variables, ammo in magazine, magazine size and the ammo in reserve
maybe clarify , are you talking about depletion or pickup/refill
Refilling the magazine based on the number of reserve ammo
I know if the reserve ammo is more than the magazine size, you simply refill the magazine and deduct the reserve ammo by the magazine size
but depends on game, for example one of my games you can pickup individual bullets and fill mag 1 bullet at time
but if mag was full then goes in reserve
In other words
if (reserve ammo >= magazine size)
{
current ammo = magazine size
reserve ammo -= magazine size - current ammo
}
But I don't know the logic of what happens if the reserve ammo is less than the magazine size
else if (reserve ammo < magazine size)
{
???
}
Try plugging in some numbers. If your gun holds 12 bullets, and you have 5 bullets in reserve, and there's 3 bullets currently in the gun, what would you end up with?
How many in the gun and how many in reserve?
https://hatebin.com/fvacuqkenm
On the first video my character just falls down how I like. But when I change directions. Even though I think I use Local axis, The falling gets kind of messed up as it can be seen in the second video. I am using DOTween
8 in the gun and -4 in reserve
How do you have -4 in reserve
I'm not asking what your code does right now I'm asking pure math
Integers can go in negative values
But bullets cannot
How do you have a negative amount of bullets?
Yes but reality cannot. How can you have a bag with negative four bullets in it
In normal math, you would have 8 bullets in mag and 0 in reserve
instead of transform.position.x maybe do localPosition
or change it to transform.right * amount
Correct. Now, let's make those numbers using only 12, 5, and 3. Add or subtract those numbers to the starting value of the gun and the reserve ammo to get to the answer of 8 in the gun and 0 in reserve
And in game, this would mean you can't reload
You can actually, but you wouldn't fully refill the magazine
You cannot reload if you have 0 bullets in reserve 😄
They mean reload again. You have 0
Oh ok
Sorry I did not get it. When I replace transform.position.x with local position the result is the same.
This is where the confusiom starts, but I'll try
Your starting value in the gun is 3. What do you add to make 8
Add 5
transform.DOLocalJump(new Vector3(transform.localPosition.x + 8f, transform.localPosition.y - 12, transform.localPosition.z), 13, 1, .8f).SetEase(Ease.InSine);
And your reserve ammo starts at 5. What do you add to it to make it 0?
Umm... None of the numbers here can change it to 0
Why not
The mag size is 12, the current ammo count is 3, and the reserve ammo count is 5, like you said earlier
Those are your building blocks. You are free to use whatever mathematical operations on those numbers
So, what do you do using only 12, 5, and 3 to make 5 into 0?
Some advanced math going on here
Oh no
This is where my brain p much short-circuits
what am i doing wrong? it works for 1 side but for the other it just teleports when it reaches the max rotation and i dont know why
https://pastebin.com/yaaN3Bdn
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.
If this is too advanced for you then you're going to have a very very bad time trying to make a game
So the issue with rotation is that -30 is the same as 330, which is, in fact, greater than 30
Clamping rotation is always trouble because of the cyclical nature of degrees
ok so what do i do
Store a target rotation value you clamp instead of the real current rotation
that doesnt tell me anything

You should set euler angles, but not read from them
Keep your own stored value for what the degrees should be, pass them to the objects transform, and never read them back from the transform
Create 3 class properties: targetX, targetY, targetZ
Then you edit them on keypress, clamp them and at the end set them as the current rotation, or even better store them in one Vector3
Good Afternoon. Im trying to map my little test turret to move using a controller. Left joystick moves the tank up and down, and right joystick rotates the turret left and right. My left joystick is working fine, but my right keeps being fed a value of -1 and i have no idea why. Any solution for this?
Let me think a bit, then I'll come back
Does your joystick have four axes?
I believe so, its a regular ps4 controller
2 on left, and 2 on right
i checked a mapping on reddit and followed it
again i could be wrong here
Where is the second one on the right?
ok so
create a vector3
copy the rotation onto the vector3
edit the vector3
and then copy the vector3 back to the object rotation?
did i understand that correctly?
is the guide i used
Do not copy the rotation into the vector3, only ever edit the vector3 and apply the vector3 values to the rotation at the end
public class TestView : MonoBehaviour
{
private Vector3 _targetRotation; // <- this one
}
what would you recommend?
current += reserve; // Add all reserve to current
reserve = current - magSize; // Reserve is how much over magSize your current bullet count is
if (reserve < 0) reserve = 0; // Reserve can't be negative
current -= reserve; // Clamp your current bullet count to max of magSize
So if you have current=3, reserve=5, magSize=12 you get
current += 5 // 8
reserve = 8 - 12 // -4
if (reserve < 0) reserve = 0 // true
current -= reserve // 8-=0 -> 8
And if you have current=11, reserve=3, magSize=12 you get
current += 3 // 14
reserve = 14 - 12 // 2
if (reserve < 0) reserve = 0 // false
current -= reserve // 14-=2 -> 12
Or just simply make a loop to increment current and decrement reserve until either current == magSize or reserve == 0
are you using the new inputsystem for this?
oh nvm, just saw the Input calls
I'd try other axis and if they output the values you want
I was thinking too much on doing them all in a single line xd
Don't
Sometimes taking a step back, and writing it out, without code, can be very helpful.
this is a lot of math to just do
current = Math.Min(reserve, magSize);
reserve -= current;
oh wait, that's not entirely correct for what they are trying to do. one sec
this code discards what's already in the gun
ok that works but is there any way for me to rotate while ignoring the current rotation of other axes?
magSize - currentMagAmount for the second param maybe
Then of course currentMagAmount += current at the end
Not sure how you mean that
I'm not very good at math, and I have an assignment on the line
And it isn't even unity related, it's UE5
var remaining = current;
current = Math.Min(reserve, magSize);
reserve -= current - remaining;
yes i am aware, hence the message directly above yours
True
if my object is rotated on the Y axis when the X axis is also affected by that
instead of going something like a line it will now go diagonal because the Y axis is rotated
idk how to explain it
can you show a video?
of what
how it currently behaves
Every other axis either causes the same rotation (4th and 5th button), Does what i want it to do but the wrong axis (3rd Button), or does what the 3rd button does, and also stops taking input from my other joystick
what i might do, is take input from the third button, then add 90 degrees to the rotation (or its equivulant)
Can someone help me out with this one?
Hmm is that the only input you currently have or would you have to rework everything when switching to a different system? If its the only input I suggest you have a look at https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/index.html
It has way better control for gamepads and even an input device debugger where you can look at what your gamepad is doing
Any help with this^
ill take a look, thanks alot
use <br>
https://img.sidia.net/ZEyI5/reteXApa30.png/raw looks like this, i can see any axis thats currently modified
how would i make it so each axis doesnt affect the other ones
use .localRotation
that didnt really do anything
Its not a br \n. If i manually use \n it line breaks
OMG ITS THE SECOND TIME I CLOSE UNITY BY ACCIDENT
Please show your code
https://pastebin.com/4sCqtSjr
using rotation/localrotation wouldnt change anything if im doing it like this
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.
also why isnt unity giving me a warning or asking me to save when im accidentally closing it
this is the second time i've reset my project
Did you even bother to try <br>?
Oh you want camera dependent rotation? like if its upside down and you press left you want it to go left instead of the updside down right? idk if i explained that well 😄
im confused
I cant access the string that comes with \n they are getting downloaded from a client server
we cant go and change that
i even try to replace it
why the log can display \n, it supposed to be new line character, it maybe \\n
it's probably a literal. use @"\n" in the Replace call
\n will give you that text, it has no escape, you would do \\n in the string to escape for the \n to be accessed
@ is used for verbatim strings. which is what i actually meant when i said literal. because string literals can contain escape sequences like \n
it's likely that the original string had that escaped or that it was a verbatim string to prevent that escape sequence
(2D) I'm instantiating several projectiles at once around the edges of an object, trying to make them "burst" out in every direction.
I have the rotations set so that the "forward" of the object should be pointing in the direction I want it to travel, but I'm not sure how to calculate that movement. What process should I use for something like this?
first, is it kinematic or dynamic?
and do you just want it to go in a straight line
I had a kinematci RB on them because I don't want them to physically interact with things, just trigger colliders. Straight light, like a burst shot
then you have 2 options
But I don't know if kinematic is exactly what I want/need either so I'm open to suggestions
one is to just give the rigidbody velocity in the direction you want. that is easiest
despite what people will tell you, 2D kinematic rigidbodies CAN use velocity
I did try that at one poitn but it didn't seem to be working so I probably wasn't doing it correctly. Is there something specific you need to do for kinematic then?
this velocity gets ignored on any physics update where you issued a MovePosition command
first you want to basically teleport the rb to its starting point. you could try setting rigidbody.position manually
then set its velocity
if you call MovePosition after that, the target destination will get basically overwritten
Yea, I haven't been using MovePosition for this part. Why is it necessary to set the position of the RB? I don't think I've seen that before
because the rigidbody and transform write positions back and forth
rigidbodies are like a separate API
when the RB moves during physics step, it moves the transform and colliders with it
i don’t fully understand why they need to be separated like that, but they are
and you would need to call Physics2D.SyncTransforms to make everything immediately line up, but that has cost because we’re updating everything all at once
unity devs didn’t think to make an overload to just sync the one object
when you move rigidbody.position, it will immediately move the collider2Ds attached to it. So the .bounds and Cast calls will be correct
Ok, at least they're moving right now, but they're just firing across the screen in the same direction, how would I calculate moving in the current "forward" direction based on rotation
otherwise some shit won’t make sense. I could initialize an object at 0,0. Set its transform to 50,100. Then check for ground by raycasting down at the bottom of collider bounds. Well congrats, you just checked for ground at 0,0
is your game grid based?
No
you can probably use transform.up
I'm thinking maybe it should be based on how many "nodes" I've been creating, but this is all really jsut for a boss fight
transform.up is the vector that currently points up for that transform
I would define a rotation matrix by 90 degrees to rotate the vector real quick
In linear algebra, a rotation matrix is a transformation matrix that is used to perform a rotation in Euclidean space. For example, using the convention below, the matrix
R
=
[
cos
θ...
for the case of 90 degrees, rotation is trivial
Projectile is floating instead of moving forward