#💻┃code-beginner
1 messages · Page 314 of 1
you don't include extensions when loading with Resources.Load
is there a way i can make a class thats inherited be able to be referenced by the base class?
like for example if I had public class Fireball : Ability
I have an object that is following the players movement, how can I use rotateTowards to make it move 15 degrees?
You can just reference it by the base class
and I wanted to allow any ability to be filled into the inspector, would that work
vert vague question. Wdym "move 15 degrees"? You mean rotate 15 degrees? Around what axis? Why constrainted to RotateTowards?
Yes just make an Ability field
public Ability Ability
you can put any Ability there
👍
RotateTowards allows from a more gradual movement, I want it to rotate 15 degrees along the objects x axis
Allows more gradual movement than what?
You can achieve gradual rotation in many ways.
do you mean around the x axis?
Rotations happen around axes, not along directions.
Yeah the x axis of the object, not of the game world
over what time period? Under what circumstances? With what other code in action?
no other code handles the objects rotation, but it does interfere with the objects positioning
Whats it the solution when the instance is null?
It should never be null unless you did something wrong.
the only thing to do if it's null is say "oops the lobby manager is null, we can't create a lobby"
I want it to rotate along the x axis of the object
but idk how to access that as a variable
you can use a coroutine pretty easily:
IEnumerator RotateOverTime(float degrees, float time) {
Quaternion startRotation = transform.localRotation;
Quaternion endRotation = startRotation * Quaternion.Euler(degrees, 0, 0);
float t = 0;
while (t < time) {
t += Time.deltaTime;
transform.localRotation = Quaternion.Slerp(startRotation, endRotation, t / time);
yield return null;
}
}```
Is there a way to make tangled code more readable easily?
what is a coroutine?
never heard of it
code that can pause in the middle to allow time to pass
in this case yield return null; allows one frame to pass
MAN I WISH I KNEW THAT EARLIER LOL
Do anyone know how to change a rigidbody's gravity scale via a script ?
Thx
Only possible in 2d
Its perfect since my game is in 2d
You can change the 3d gravity by applying a static force in the desired direction
Well what?
It says it is null.
However I set it in awake
Sounds like you're reading it before that awake code runs
or it's never running
e.g. because that script doesn't exist in the scene
Is it because I'm moving scenes, and the instance is not the same?
Could you explain this a bit more, I am having a hard time understanding it and thus a hard time implementing it
I don't know how your game works. Check the stack trace of your code to see where it's being called from.
I am already using moveTowards to move an object back for a set amount of time...
should RotateOverTime()s time be set to that number?
What does this mean?
PlayerCountSelector.MakeLobbyOfPlayers (System.Int32 playerCount) (at Assets/Scripts/PlayerCountSelector.cs:27)
PlayerCountSelector.<OnEnable>b__4_0 () (at Assets/Scripts/PlayerCountSelector.cs:15)
I have no idea whatr that function is
That';s a function you made up
so I have no idea what it does
OnEnable on one object can run before Awake on another
that's probably what's happening
I also tried start
start would be better
Moves the object backwards in while the player is holding it until the if condition is true
multiplayer 😬
Nope?
ohh I saw lobby idk lol
Does not impact rotation at all
Same problem
Then you don't have a LobbyManager in the scene
I actually deleted it without a reason
comment functions and add spaces in between different functions (boom)
refactoring
Is there a way to play an audio file from a certain point?
I have music playing in the main menu (scene 1) and I want the song to continue in the actual game (scene 2) with a different audioSource so I can create a fadeout effect
whoa that was fast, thanks a lot I will read through that
This will be more accurate though https://docs.unity3d.com/ScriptReference/AudioSource-timeSamples.html
thanks legend
I have a script and with that I can move object with my mouse when dragging them. But whenever I click and drag an object, since the game is 2d, it detects the object behind them ocassionally. Why is that?
back in the early days of Unity 2.6 there a kid (forest something) who made all their demo projects, he used coroutines a lot so we learned from that. nowadays examples are super convoluted so you miss a lot of the niceness (and also coroutine tend to explode in your face at scale haha)
which reminds me this skit https://www.youtube.com/watch?v=FXhXbswt3Bw
Taken from Jim Carrey's Live Performance "Unnatural Act"
lol
Should I put assertions in UNITY_EDITOR only? I.e. what happens in a build? Because I guess the best thing would be to try to move on, but I believe failed assertions block the program flow like exceptions right?
{
activeBattlers[currentTurn].PlayParticleEffect(activeBattlers[currentTurn].zoneHighlight);
}``` Ho can i make this pre fab follow the player with out making it a child?
Constantly update its position
It is easier to have it be a child tho
ok cheers
All method calls will be conditionally included only in a development build, unless specified explicitly. See BuildOptions.ForceEnableAssertions. The inclusion of an assertion is controlled by the
UNITY_ASSERTIONSdefine.
https://docs.unity3d.com/ScriptReference/Assertions.Assert.html
tldr; they are enabled by default in a debug build. A built game, that isn't that, won't have them, so you don't need the conditional for em.
Awesome thanks for the reply
what does this mean, i understand that its tell me to change it, but im just trying to destroy a instatiated game object (Particle)
i then get this if i use DestroyImmediate(activeBattlers[currentTurn].zoneHighlight, true);
you're trying to destroy a prefab thats prob why
don't use DestroyImmediate. thats for editor only
yh my bad, thanks
i dont understand the problem
get your !IDE configured. then make sure to actually save you code so unity recompiles it
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
when you save the code you should see a new error
how do i switch to vs code?
well you'll have to configure that too, and it is notoriously harder to get configured and get it to stay configured
you need to follow the guide to configure visual studio
complete all of the steps to get it configured
ok
What do people usually do when they want to prevent a more derived class from being inserted into an inspector field? I've been deriving a similar class copy to overcome this limitation but it feels like such a janky solution.
or is there some attribute im overlooking here
Is there a specific use case for this?
!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.
Well, such that using a more derived version in those fields would probably break a lot of things when using polymorphic method calls
How can I make the moveCamera() actually move the camera
do I need to use courtine or whatever its called?(if so how)
how can i check if any controller connected has the button B pressed?
Sounds like you're wanting to seal the class but only from future derivatives and not those you've defined right now - which isn't possible as far as I'm aware. What concerns are there from future derivatives?
It's a projectile class, but further along the deviations do I let them recursively call less derived projectile classes, but this wouldn't create a loop of projectiles because you couldn't produce more of the projectiles that create recursively
AbstractProjectile -> CastableProjectiles
so basically I branch from AbstractProjectile into an empty class such that I call them TriggerProjectiles but really it's an empty class /shrug
So now CastableProjectiles has components of TriggerProjectiles it can trigger, but if I were to have a non-abstract Projectile class instead it would allow CastableProjectiles to have CastableProjectiles
so yeah, some editor jankyness to get around
A coroutine is not needed. You have to just actually move it. Nothing in that method has anything to do with movement, just rotation.
There are tons and tons of tutorials on how to move objects online.
I'll just say, do camera movement/rotation in late update
my bad i want to rotate it
Well you have the method already. Just call it
why is that?
just wondering
camera movement in lateUpdate I mean
how can i check if any controller connected has the button B pressed?
Input System probably
It is after the internal animation update and is IMMEDIATELY before rendering
It happens after most things have moved too, and after input would be captured
i know that, im using the new one but idk if i can just call "If button pressed" like the old one
@stuck palm
Check that maybe?
I uploaded an example of a simple input system I have a few days ago
makes sense, I should change it in my game) Thanks
Where did u get that "Inputs" class
using UnityEngine.InputSystem;
I think
I only just started using the new Input System
So I am not entirely sure how it all works yet. But what I posted there works on controller and pc
i dont see it there
i thought u made that class yoursel
let me check really quick
cus it looks very convenient for sure
Dont have my project open was about to go to bed xD Gimme a sec to launch it
but i canat find it
sorry to delay your slumber
no worries xD
Now im curious myself cause I still need it
Did that a few weeks ago just to make sure some controller inputs work
The dirty Java solution would be to use interfaces with conflicting function definitions but I'm not certain if c# can do this. In Java, using multiple interfaces, you could prohibit inheriting other specific interfaces by having the interfaces require specific methods but with different return types. As return types aren't a part of a functions definition, they would conflict in that the other interface has already defined the function but with a different return type - making it impossible to implement both.
(what a Stack overflow suggestion stated, at least https://stackoverflow.com/a/50534086) Hacky ol Java.
I guess that wouldn't work with the inspector either way as they (interfaces) aren't visible to the inspector. @timber tide Waste of effort 🙇♂️
I am using a boolean to allow for it to work
but it doesnt work
@stuck palm Pretty sure I used Brackey tutorial on this. Its a bit old but seems to still be working:
https://www.youtube.com/watch?v=p-3S73MaDP8&t=373s
it worked like once than i changed something and now im lost
What does the boolean have to do with anything?
I was thinking about some editor scripting for it, but that stuff is too much of a hassle. Really I should bite the bullet and just grab myself odin to fix a lot of the editor's shortcomings. Though, a lot of the problem does stem from the structuring and not the editor. So ultimately the real fix here is just do composition over OOP if I were to refactor my code.
MoveCamera is never called. So it will never run
A method that is not called is never ever run...
the boolean is preventing the update method from altering transform
I call it in another method
If the spring sale is still on its 50% off
Problem is it's per seat so I'll be buying it for my mate and friend haha
where did u get the inputs class from?
yes
i see
how do you generate the class?
actually its fine i can just watch the video
its autogenerated if you tick this box
No problem!
That video probably explains it alot better so might aswell watch it)
Also gonna have to rewatch it once I implement the rest of my controller inputs)
Well if you call it then it runs...
alr i got it working... ish
i've never seen this part before lol
thanks this is very helpfyl
So after I rotate the camera, are there any variables that keep track of the original rotation? how can I rotate it back?
You would have to make a few floats to track how much you have rotated, then negate that
Could have an empty gameobject that represents "base" rotation, and just set the camera to the same as that when you want
So after the thing rotates I try to rotate it back
you can see its commented out right now
because for some reason even without calling it it snaps back to the origin
where am I setting the rotation I dont understand
I figured out this is why its snapping
and also that my code to move it back does not work....
kinda silly question, but is everything written in C# part of the ".NET framework"? Just trying to understand some documentation better
hello guys. i need a little help here.
sorry im new .(
now i can jump infinitely i just wanted to make a double jump thing
you need to get your !IDE configured
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
no, but it will at least point out your compile error so you can fix it
do you see the compile error underlined in red in your code now?
I have a model I'm trying to import into Unity and define as a Humanoid.
I get an error saying it has to have at least 15 bones.
Is there a way I can import custom humanoid models with any amount of bones? I have the animations all complete as well
OMG I JUST REALIZED YOU ARE A BOT 😮
🤖 but is your IDE configured yet
this is a code channel, mate
yes it iss but it doesnt solve my problem
mb bet
i specifically said it wouldn't. but you need to show that it is configured
yeah not configured
how !!!!
follow the entire guide to configure visual studio. after you have completed the steps regenerate project files and restart it
getting it configured will save you a lot of suffering in the future
after you do all that open the solution explorer inside of visual studio and screenshot the entire window
this isn't the only step
My unity editor freezes upon clicking a button created with the script - https://paste.ee/p/E9KLo performing the method BeginBattleRuntime(EnemyCardManager enemyCards)
https://paste.ee/p/eUpNj - editor logs
i apologize in advance for the scripts organization its just a prototype 😭
how would i make the loading screens for my game stay for a certain amount of time, currently they disappear after around half a second which i don't really like, is there a way to make them stay for about 5 -10 seconds?
make it wait 5-10 seconds then instead of whatever other operation it is waiting for, you'll have to show code for more specific help
!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.
ok i have done it
does it show you the error in your code now?
after you do all that open the solution explorer inside of visual studio and screenshot the entire window
https://hastebin.com/share/oxarunesuz.csharp here are the few lines of code i use for loading screens and closing loading screens
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
there you go, it is configured
what is this???
the error i was referring to
attach the debugger and play line by line. probably some infinite loop somewhere, or maybe these arrays are just massive and its taking an insanely long time to complete the LoadCards function
you hadn't saved before so it wasn't showing up in unity (also why you were still able to play)
alright ill try it
yes, that is not valid code
idk i tried so many things
how to fix it
&& means and..
where is it
well start by thinking about what you want to do there
🤷♂️ if you're gonna show the absolute bare minimum i really cant suggest anything. The only thing i see here is photon related function calls, so you should post this in the photon chats. pinned inside #archived-networking
also really shouldnt do multiplayer if u are a beginner
Irrelevant now, but in view
yes i know i made it myself B) (combined two peoples codes)
And is for bools
Y = this thing and this thing
How does that make sense?
if that is what you think is valid, then stop everything you are doing now and go through the beginner c# courses pinned in this channel
dude pleasseeee i need to see my project starting until i go for 6 months
im trying to figure it out
It does not make sense. Remove the &&. Make it two statements
another thing i notice could be related, in update you call BattleRuntime every frame if some condition. this method also calls InvokeRepeating("EnergyGrowth", 0, 1);. This will be extremely laggy quickly, if its not an infinite loop, your game is freezing because its running way too much
wait wait i figured it out
i will make it work right now!
note that if you have the debugger attached, when the editor freezes you can Break All in the debugger and inspect what is happening on the main thread
i think this is the issue ill look into it
how does the debugger work im new to using it often
?? is this ok???
nope im still jumping infinitely...
no for two reasons, one the logic doesn't make sense. and two, you clearly have a compile error (hence the red squiggly line)
i fixxed it after i sent you B)
Why the two duplicate if statements?
because they don't know how to code so they are attempting to code by approximation
dude please be a little more kind you cool
stop wasting your time and go learn the basics
yes i dont know how to code but im trying to learn
i had a working game on godot but i converted to unity thats why learning is so hard rn
If that is true, stop everything and do this
https://www.w3schools.com/cs/index.php
It can take just a few hours if you take it slow
Then do this
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Just do essentials and junior programmer
THEN come back to your game
😦 just double jump please
Well, good luck with it 🤷♂️
i already told you, there is a flaw in your logic. if you'd read your code you would see it
this is cool btw
coding before learning ☹️
coding after learning 😁
"just one thing" until the next thing
Not in my experience. Just different
It's not like you can just switch without relearning some things
the issue here isn't really even an issue of unity vs godot. it's a matter of reading your own code so you can see the glaring flaw in the logic
okay let me try again
i create theese
Did you see my question bte
#💻┃code-beginner message
yess i will fix it right now
if the jump button is pressed and i can move and my remaining jumps are greater than 0 i jump and the jumps remaining gets -1
right?
Correct
and if im on the ground remaining jumps will be equal to max jump count which is 2
so what i dont understand is
read that again
okay i will read it again
No, that if statement does not mean that
! is the negation operator
Aka, not
You didn't fix the issue I was pointing out
You combined them, which you do not want
i was doing the two seperate things for that i remember
i forgot it in the middle of im writing it
thank youuuu just wait
why cant i do this? slugger inherits character
Just because player is a Character does not mean it is a Slugger
im using it but it doesnt detect anything... could it be from the code causing huge lag to freeze it then?
could be user error tho
wdym it doesn't detect anything? i told you to break all when it freezes. then you can look at what is happening on the main thread to see what the loop is
like no break points
i did not say anything about break points
i'm trying to follow the guide you sent me mb
Every slugger is a character, not every character is a slugger.
Is it not possible to upcast like that though?
GetComponent is the cheap sloppy way
Am I using the term upcasting correctly
Honestly that's all I need
you can cast explicitly to the derived type. but at that point, why are you storing it as the base type in the first place?
It runs once
if (player is Slugger slugger)
{
slug = slugger;
}```
okay there is one more problem. the jumps remaining count is 2 only when im grounded
Oh right I forgot about that
That... sounds like what you wanted?
noo like
i can jump on the air one more time
considering that is the value of Max Jump Count right there, that sounds right according to your logic
like the double jump thing
Yes, that is what the code does
That is the point of subtracting from jumps remaining
but it is subtracting so fast i think
This is for an info screen, and some characters have special info, like the slugger needs a special ball count. Not all characters require this though
Ahhh, I see. Use GetButtonDown
Not GetButton
The latter is true as long as you hold it down, which is gonna be more than a single frame
What?
Ah I see.
I mean yeah, int makes more sense there
Since you can't half jump, unless you want to implement like a percent of max jump? Hahaha
the guy who write the code made it int and i used float because the guy that made the character controller used that only
regardless you'll still need to have a field for slugger on your script, instead of one of type Character. Maybe consider redesigning this, where each script themselves provide the special info from some overrided method.
what should the KeyCode be?
use GetKeyDown, not GetButtonDown
oh not that sorry
Yeah I was just going on memory. Down is the important part
oh now mouse doesnt work
wait i will fix it
oh its fixed and i can jump 3 times right now i will fix it too
the gameobject has the script and the player body sprite has the rigidbody
sorry it took so long
I installed the unity today, coming from godot. i spent all my day by learning right way of fbx exporting from blender, learning about post processing in unity and trying to recreate the look of my game in godot. its 3 am in my country and i need to sleep. before i sleep i said i need to try some coding and mess up with the code. you guys are so helpfull, thank you so much for helping me fix it and im sorry if i disturbed any of you. good night guys.
its looking good for now @summer stump thx @slender nymph thxx
cool grafix
thank youu
and this is the original project
#💻┃code-beginner message
why the switch from godot if i may ask
The script needs to be on the same object as the rigidbody. (The parent). Otherwise you are moving a child which has no affect on the parent
so if i do that, will the dash indicator then follow the parent?
or i mean the object
Children maintain their offset from the parent unless explicitly moved via code
Or they have dynamic rigidbodies of their own
kewl. reminds me of some of the ps2 games that use realistic textures
let me try it out
what kind of game are you going for
i was trying to create a animated sky for 2 days ended up adding 90 frames one by one for half an hour to AnimatedTexture thing. when i asked the godot community said there is no other way and AnimatedTexture thing will be removed in the next update. i even tried a TextureAtlas but it was worse. so i think there is some technical deficiencies in godot. godot is still one of the best for me but i will give a chance the unity since i tried it once or twice in the past. (one more reason is that i see my idol world4jack converted his game to unity from godot)
yeah godot looks interesting but i feel like i'm going to wait for it to mature a bit more before trying it out
an open world game that has many little stories in it. trying to catch the vision from when we were childs and see the world more brighter and differently, like a ps2dream as an adults eye with graphics. and the stories are about daily things but one by one they get crazier and more dreamlike.
@summer stump it works now
but im confused why wouldnt it work before and now it works?
is it the fact that i had a script and the rigidbody in two separate gameobjects?
like a trippy shenmue lol
ahahahahf yessss
if you like this kind of graphics you can look at world4jack's videopix on youtube he inspired me alot
Parents move children. Children don't affect parents at all
That's it
a tip for you if your trying to learn c# is you can ask an AI like chatgbt to teach a beginner about a topic and keep asking questions like a teacher
it worked well for me when i first started
but i would fact check it every now and then still
İsnt there a credit system for using or did it get removed from chatgpt
That is some pretty bad advice.
A beginner isnt gonna be able to fact check it in the first place, and if you can then you know how to google to research what you need in the first place. Just follow the links sent above by others
i will try it thank you if it dont fit me i wont use it thank you for the advice againnn❤️❤️❤️❤️
Now im going to sleep goodnight guys you all so cool
Do yourself a favor and dont even try learning from ai. You wont know the difference between it being right and completely wrong. It's designed to spit out any answer to make you happy, so that's why beginners always thinks it's good.
is there a variable type of Tag?
If you make one, sure
A tag is a String internally
ive tried to do one with a string and it doesnt work and they are the same name
How does one do a get a radial position on a 3d plane? Basically what I'm trying to do is get a random direction then have it raycast to see if there is anything in that direction, if there is do a rotation along one axis. The purpose is i want a flying enemy to find a direction to dash to. So I'm checking it along a radial pattern
Always do CompareTag
But likely your issue is checking the wrong object if it's in OnTriggerEnter (assuming you are SURE it is the same string)
oops nvm it was working i just didnt realise it :/ sorry
Quaternion.AngleAxis
thanks
I'm having issues with the jumping code, I'm following a tutorial and everything is correct. So I'm not too sure what is wrong
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
public float movementSpeed;
public float groundDrag;
public float jumpForce;
public float jumpCooldown;
public float airMultiplier;
bool readyTojump;
[Header("KeyBinds")]
public KeyCode JumpKey = KeyCode.Space;
[Header("Ground Check")]
public float playerHeight;
public LayerMask WhatIsGround;
bool grounded;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, WhatIsGround);
MyInput();
SpeedControl();
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
}
void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
if(Input.GetKey(JumpKey) && readyTojump && grounded)
{
readyTojump = true;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
}
void MovePlayer()
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
if (grounded)
rb.AddForce(moveDirection.normalized * movementSpeed * 10f, ForceMode.Force);
else if(!grounded)
rb.AddForce(moveDirection.normalized * movementSpeed * 10f * airMultiplier, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
if(flatVel.magnitude > movementSpeed)
{
Vector3 limitedVel = flatVel.normalized * movementSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
private void Jump()
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
readyTojump = true;
}
}
I don't have nitro so that's why i broke it into two
!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.
the more i know
well i started using it after learning some and it worked really well, dont knock it till you try it
i used it to explain things like properties and give examples
yeah but you dont know if the explanation is correct
that's the point
Debug.DrawRay(transform.position, Quaternion.AngleAxis(_currentAngle, Vector3.up).eulerAngles, Color.red);
The ray isnt matching the arm, is this the right approach to converting the angle to direction?
ive never used the attatched debugger with unity and im having some trouble
ive managed to attatch it but the first time I recieved -
No compatible code running The selected debug engine
also how can I step each line to try and find errors?
Ive got a UI button in world space however its being covered by a UI image that the camera is projecting to and so i think thats why the button isnt working so i dont know how to fix it
not sure exactly what angle you want to match...
AngleAxis would spin the angle around the V3.up, which wouldn't really do anything in this case, as we're already pointing upwards.
it seems like you want to use Debug.DrawRay instead, as DrawLine draws from a position to another, while DrawRay draws in a direction.
If you want the angle to be relative to the arm you should use the arm's transform when rotating with _currentAngle, so maybe arm.transform.right in the AngleAxis.
uncheck the Raycast Target on the UI image.
I'm tryna get the length of the animation, but the results are always inaccurate. It's gonna be 1 or 0.833333 or something
public void UseButton()
{
animator.SetTrigger(TriggerName);
float ClipDuration = animator.GetCurrentAnimatorStateInfo(0).length; //I'm trying to reference the duration of the animation state
Log("ClipDuration: " + ClipDuration.ToString());
StartCoroutine(ExecuteFunctions(ManualTiming ? AnimationDuration : ClipDuration));
}
The comment in the line of code describes the problem.
Anyone here can help me?
I found out that it does work correctly, but the reason why it wasn't is because it's referencing the time of the empty New State
thar didnt work
I'm trying to make the function reference Play button click instead of New State. Why isn't it happening?
I already transitioned to the state there
what do you mean by "Camera is projecting"?
so the camera is projecting onto a texture which is then being placed as UI
check what clip you're checking the length of with a Debug.Log
I already figured out that it's New State
So the problem now is... how do I make it not the empty state
I want my custom animation's length to be referenced, not the empty state
oh, I believe you have to give an extra frame of leeway for the state to actually change.
Unity is evil 💀
Thanks by the way
animations are framerate-dependant, so even if you change the trigger in code, it won't actually change the animation until it undestands that it needs to.
No wonder
giving extra frames isn't the norm in Unity, but some systems do need it :(
I'm gonna try it out
I don't really understand what you mean?
Is it another UI element?
Is it a texture?
What do you mean by "projecting onto a texture"? Are you using a RenderTexture?
so the camera has a target texture which then that texture is being used on a UI image
I see, okay.
And this UI image of (presumably what the camera can see), is blocking your other UI elements when pressing buttons etc?
thanks ill give it a shot, all im trying to do is have it draw a ray toward a direction the arm is just another visualization
exactly
seems like they came up with something here: https://forum.unity.com/threads/keep-a-ui-image-from-blocking-clicks.272963/
"To keep any UI canvas or element from blocking clicks or registering mouse input, simply give that canvas or element a Canvas Group component (Add Component->Layout->Canvas Group), then turn off Blocks Raycasts. "
that didnt work
@hollow slate Thanks dude, it worked
What can I do to stop this when it reaches a certain position
doing == doesnt work, probably too precise
= or <=
try the other solutions in the article
i did
not article, forum post. Whatever
it says i cant use those operators bettern Quaternion
hmm, try adjusting Z-position?
you can compare V3.Angle.
its greyed out
Oh sorry, I didn't look close enough.
Yeah, what leole said
Or track a float and compare that
Vector3.Angle()
and get an angle?
also i dont think that would change anything as the image is screen space and the button is world space
but the angles for the game object are independent from the gam world rotation
they are adjusted by player cam
Instead of lerping with a changing start position and fixed percentage, you should lerp from a fixed starting and destination, and increase the percentage to 1. This will put you at exactly the ending position. You can probably do this in a Coroutine.
https://gamedevbeginner.com/the-right-way-to-lerp-in-unity-with-examples/
try disabling the image just to make sure it's actually what's blocking your elements too.
it works when its disabled
it says lerping rotation is used to rotate over a period of time, how do I use that to get a position
assign a different layer to the image maybe?
watch a video on lerping, you'll get it in no time.
alr
nah that didnt do it
is it possible to have code execute after frames/milliseconds?
yes, keep track of how long its been or how many frames its been in update.
any idea why my DisplayDialogue coroutine is not waiting at all before calling TypeText()?
just a short wait like something i would do in scratch. the idea is, after ExitCollider2D, wait 5 frames before removing the ground check
look at your coroutine line by line. what is it doing first, then when it is yielding and waiting for a certain amount of seconds
you can either use update or a coroutine to keep track of it. Usually you would want to base these things off time rather than frames, so everyone has pretty consistent behaviour. If theres a specific part you struggle with, then show what you've attempted and people can help
I've tried placing the method call after the yield return, but for some reason that causes it to break completely. Thought it may have been like other methods, if you return early it will just not execute anything after the return
im trying to make it possible to wall jump between 2 walls and just wanted to widen the time window to do so, but when i try to do it in a coroutine it only gives me WaitForSeconds or WaitForSecondsRealTime. can i place a float in that?
I've tried placing the method call after the yield return
if you look at it, it already is before the yield. Right now your code calls textEffects.TypeText then waits 7 seconds and does nothing after.
what do you mean "it" only gives you WaitForSeconds or WaitForSecondsRealTime. Are you using AI or something?
Look at the docs for what either of those takes in
suggestions unity gives me to finish the code. also what i see in videos when i try to look up the issue
so this should actually call the method?
IEnumerator Test() {
yield return new WaitForSeconds(7f);
Method();
}
get used to looking at the docs before anything else. No point skimming through someones (likely poorly made) video when the doc just tells you exactly what you need.
https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
can you recommend any videos? I can only understand using lerping in the context of doing a rotation for a set time
yes, it'll still execute. yielding here is saying wait for this long then continue. returning from a method is different
ah okay thank you, so that means I'm probably running into some weird issue with interdependencies on the two coroutines, I'll look into that
how do I use a void from one script in another script
what do you mean by void?
like exampleVoid()
do you mean a method?
so I got it to work how I wanted
but the transform.localEulerAngles interferes with it
and basically just overrides the animation
what do I need to do to it to make both work?
I'll look for one I think is good
I just figured it out
ah
right, well you're adjusting the rotation when you set the angles no?
they're both "working", but I'm guessing you're not getting the behaviour you want. Is the moveCamera not a part of it at all?
we're just doing Update and moveCameraBack?
ok so with moveCameraBack I get a nice smooth animation going to the position, but with the transform.EulerAngles uncommented, it snaps back to the origin position
but I need transform.EulerAngles to control the players cam vertically
so im kinda stuck
uh-huh, is it a first-person style camera?
or some kind of camera that needs to move horizontally at least?
so what effect do you want the moveCameraBack to have?
just move the camera to Quaternion.identity?
which is the same as setting the angles to (0, 0, 0).
I'm going to assume mean a method. void is a return type for a method, it signals "this method has no return value". I do recommend looking into that more, but to actually answer your question:
you need to get a reference to an instance of the class that method belongs to. There are multiple ways of doing this, too many to list here. A popular one is to use [SerializeField] private <class name here> cowboy
then drag and drop the reference via editor
you can then call the method by using
cowboy.methodname();
I demonstrate the differences there
basically
the moveCameraBack makes it nice and smooth
I got it
so how can I make them work together(look at video above)
np
so what's the issue when you comment the line out?
looks like it's doing it smoothly then no?
the issue is I cant move the camera up and down with it commented out
idk if you can tell from the video
ah
but with it commented out I can only move the cam left and right
if what you want to create recoil with this I'd suggest doing it in a similar way, but with a few generalizations.
I hate the unity animator :3
ok, like what?
if you want constant control of the camera (which is generally what we want for FPS games), but with additional stuff like shaking/recoil - I'd suggest this (as I've done this pattern before):
store a value for the X and Y rotation of the character, which you're already doing for the verticalRotation variable.
Every Update, create a Quaternion that aligns with these value, often just doing Quaternion.Euler(horizontalRotation, verticalRotation, 0)
Then we add whatever recoil we want to this rotation. The concept of adding doesn't really exist for Quaternions, as they're quite mathematically complex, but we can essentially do it using multiplication.
Create another function to get whatever the current recoil-rotation would be and add it to the current camera's rotation (look up order of multiplication for Quaternions).
Finally set the rotation of the camera to the combination of these two.
that's the general way to allow for adjustments of the camera's rotation without overriding the input.
"Create another function to get whatever the current recoil-rotation would be and add it to the current camera's rotation (look up order of multiplication for Quaternions)." You mean like the current rotation of the gun or the rotation I am trying to get to???
it would be this line in your script.
could someone tell me why this block of code refuses to work
I'll drop the whole .cs file's code if that's required
what are you trying to do with those wait for seconds? you shouldnt be guessing at what logic to write here. Look at the docs for coroutines
Hey guys, I have two crate Prefabs in CratePrefabs[] both are tagged with Yellow crate and Red crate respectively as per their crate color. I used Input method to move Yellow crate left and right arrow keys and used A & D keys to move if it's a Red crate. However, if the Yellow crate is instantiated, it's using A & D key to move and if Red crate is active, it's using arrow keys
Can someone please help me understand what mistake I'm doing here?
add some debugs, to show which part of the code is running. youve likely given the wrong tag to each object
Even I was confused for a while that I might have added wrong tags to those crates but I've checked multiple times to confirm that the respective crate tag is added and even I have added the logs in some other method to confirm, which crate is instantiated when it's instantiated and even the logs confirm that the Yellow crate is instantiated but still it's using A & D keys to move instead of arrow keys
well add some debugs inside the current code, to see which part of the code is running. Then you'll see more into why its entering one if statement instead of the other
I did just added debugs and I see that if a Yellow crate is instantiated, it's saying "Red Crate" However, since I'm taking reference of the tag names to use to move them accordingly, the tags are matching the crates but the logs are showing opposite
how can i make it more gradual?
The recoil is pretty snappy
also using transform.localEulerAngles cancels out any of the effects from trying to adjust the angles
so i still need to comment it out
I am making a game with roads of different markings, there are roads with markings that show that we cannot overtake. If we do i want the game to detect it and deduct my points. Is there a efficient way to implement this? I was thinking of using some collider triggers, but having them for every road in my game could affect performance right?
the logs dont lie, maybe you are looking at the wrong object. But i suspect its an issue more so with the prefabs. The array is named cratePrefabs, so it is checking the tag of the prefab, not the spawned object. Are you setting the tag at runtime?
trigger colliders will be the easiest solution to define an area that does something. I wouldnt worry about performance until performance is actually an issue. You can say the same about having a complicated environment, every single wall, terrain, npc, whatever, will have a collider on it.
Are colliders being used for everything in games common?
if you want collisions, yes
Makes sense
But i think mesh colliders are a bit more heavy performance wise compared to the cube or sphere ones right?
If you plan on having a TON of these, well first thing maybe you are trying to have too much in one scene.
But also then you can specify more about your game, like are you using rigidbody or other movement where the user can go absolutely anywhere they want? Are they on a fixed path and dont have control over going offroad?
If its completely free movement, triggers will be your only solution really. If you decide where the user goes, and for example they press A/D to move left or right you can keep track of it differently possibly.
Ive been using cube colliders to help traffic vehicles stop if they detect a car up front, stoo at a traffic signal etc..
Well its just a game made to educate people on how to drive, just a bunch of roads
probably. though still I wouldnt worry too much about it
Since these arent gonna be moving and colliding with each other, i doubt you'll have any issue
its just the cars moving
I was just asking to see if there was a unique approach to this problem, colliders seem the easiest way, and the most effective, thanks for info!
also the profiler can tell you about physics stuff. if you arent using primitive colliders, and you have issues, you dont use the roads mesh as a collider. Make your own lowpoly version of it
idk too much about asset stuff, but i noticed that was a common thing done. making a separate mesh for the collider
I'll look into that👍
Yes my bad @eternal needle , I was trying to move arrow keys based on the crates instantiated and wasn't using the crate's instantiated and instead I just used the crate's tag. I just fixed it by taking reference of the instantiated crate's tag which helped me fix the issue.
@eternal needle Thank you so much once again for helping me on this 🙏
hi
is there a way to get the reference of a text GameObject inside of a canvas object?
Yes
wait
I can just make a public variable
modern problems require modern solutions
Ok so turns out you cant do that
I couldnt drag a text object onto the reference var in my inspector
Canvas or Text, I cant drag any of them
The variable should be a TextMeshPROGUI or TMP_Text for you to be able to drag and drop the Text, did check what kind of variable it is ?
TMP_Text is the better type to use.
Handles all TMP Text objects I believe.
Probably.
I agree
It is the parent class of the two
ya figured
Either have a Vector with a single coordinate not set to 0 or multiply the direction by a float
Guess setting eulers should work
you are rotating it by one axis. use this code on a basic cube and see how it works. Do not trust the rotation you see in inspector. 2 things, it is a local rotation, and it is also an euler representation of the real quaternion used. The conversion from euler (what you gave) to quaterion, then back to euler will not always give the same numbers back. It is the same rotation though
just a simple gameobject var
i need 2 rotate it for black objects was at bottom
- before
- after
Don't use GameObject
Use TMP_Text as they said
Oh wait, are you trying to drag a scene object onto a prefab? You can't do that
still, try doing the exact same line of code on a basic capsule or cube and see how it works. Maybe you are just rotating around the wrong axis
i needed 2 rotate z, not y, you're right
yep
what if I add my prefab in as an invisible Gameobject and turn off its mesh?
Hey guys! How do I make the yellow Puck spawn only once and share location through the host and client?
I'm using NGO and Relay
what type keyword should i use instead if its a prefab?
This question doens't make sense. What do you mean by a keyword you should use?
Are you referring to its type? As they have told you, you should use TMP_Text, not GameObject
ok
I didnt create a script inside of a prefab instead I added it into my Player gameobject
why is this taking so long?
4 minutes?
I just saved a script
probably some unity error. you might just have to close and reopen
Hey,
I have a script and with that I can move object with my mouse when dragging them. But whenever I click and drag an object, since the game is 2d, it detects the object behind them ocassionally. Why is that?
if it's not on a canvas and fully 2D then it's probably grabbing the first collider it hits and if all elements are on the same z then i assume that would cause some complications
Alright I realised the problem just now, its the z positions, how would you look at it?
Is the script assigned to those cards? Are you sure it's assigned to all of them?
Yes the problem is the z position
not sure of the most correct way of solving that in 2D besides just inching back the z values by a few minor units
So those cards aren't UIs?
They are prefabs, sprites
could also do a raycast all and iterate through all colliders and pick the most top card if you have it sorted as it seems
since you do seem to have a most top card being rendered
Alright, sprites. Then they aren't UIs
Well, why wouldn't you make them UI instead of sprites?
It makes more sense, since you also have those users, Ben and Steven, which should be images
Because I need them for other use cases
For instance?
Interaction, animation and iteration
I would do it on OnMouseDown, right?
Well, the top card is selected by default.
I still don't see why they cannot be UIs
OnMouseDown has to be applied to the GameObject directly
You'll thus have to have a script applied to each of your cards
I assume the top card has the highest sorted order what i mean, such that you can just check through all those hit by the raycastall
In the case, when the cards are sprites, multiple will be selected using OnMouseDown
It's redundant, as a single Raycast already does return the nearest card
if they are on the same z then it wont always do that though
it will be rng at that point
raycastall would grab everything bunched together then you choose the collider by highest render ordering
How would you want to check for the nearest card, if they all have the same z?
When using sprites, you'll simply have to change their z positions according to the desired order
I assume canvas does something similar
It doesn't, no
Canvas doesn't care about the z position
right, it cares about the ordering, but grabbing elements via colliders wouldn't be accurate alone
Canvas has its own order, which is top -> bottom in the Hierarchy in case when both Materials's render queue is the same, and highest -> lowest render queue otherwise
Where the render queue is changed via Graphic.renderQueue
Which you don't do in UI, because of Colliders not being usable there
I tried this, but nothing happens
It is
Consider sharing your code as text. !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.
Dont think OnMouseDown is the idea here. Probably just check for input then raycast onto the board if you want to do it that way, and you'd need RaycastAll if you want to compare multiple colliders per ray
This happens because of the Physics2D.Raycast not being affected by the sortingOrder
Actually I guess that kinda works
What could?
Well, Physics has nothing to do with your Renderers
Where have you ever heard me recommending you raycasts?
Anyway, as was mentioned by Mao, you can actually find all Raycasts and check for the sortingOrder, as that's how you see the objects appearing on the screen.
You can also find the Raycasts and change the objects' z position, which is more appropriate when dealing with Physics
But I would rather do it in UI space
The thing is, sortingOrder is the same for all objects.
then how do you have some cards above other cards
In this case a random card appears first
Spawning order I assume
So you either
-
- Get all
Raycastsand check which has the highestsortingOrder
- Get all
-
- Get the first
Raycastbased on theZposition, which you have correctly set up
- Get the first
-
- Use
UIand get the cards according to the firstRaycast target
- Use
Note that the options are ordered from the best worst to the best
When I'm spawning them, should I just increase the spawning order with .1 then?
idk what you mean by spawning order, it's pivot sort then sorting order
I spawn them from right to left (Instantiate)
Are you reffering to the 1st or 2nd option, to the sording order or z position?
Yes, to the first
Yes, you just increase the sorting order
Just make sure the cards don't have their orders willing to exceed 32767
Hi. I like to shorten very much, if possible, and I have a question: Is it professional and correct to shorten the code? Of course, I understand that everyone has a different approach, but I would like to hear the opinions of others. Также хотел бы узнать: Можно ли пренебрегать фигурными скобками, если для условия нужно будет 1 действие (если фигурные скобки необязательны)?
Please, consider writing your question fully in English and sharing the code in the text form.
Which code writing option is better?
Alright I've done that. Now, where do I call the raycast? I have an Interact script attached to every interactable gameobject.
There are far better ways
Are you talking about the code sharing option? As I have mentioned, in the text form.
!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.
Well, having a script for every single object is so bad for the performance in your case..
Have a single script to manage Raycasts
It's a little game so it doesn't really ring a bell for now, but I understand your concern
It's a little game, so you are willing to decrease its frame rate?
For now, yes, later, I'll optimize
That doesn't make sense at all
if (Input.GetMouseButtonDown(0)) {
RaycastHit[] hits;
hits = Physics.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
foreach (RaycastHit hit in hits) {
if (hit.collider.TryGetComponent<Card>(out Card card)) {
if (card.GetSortingGroup().sortingOrder > lastSortingIndex) {
lastSortingIndex = card.GetSortingGroup().sortingOrder;
}
}
}
}
}```
Somewhy, the positioning is off
The code you want to write won't even be easier than the normal one, which is much better for the performance
But I tried this, this will get the card object which has the biggest index
Please, consider putting a cs markdown and left tabbing it
Sorry I don't know how to do that, but I see the problem
That's alright
// the following code should be
// selected and left-tabbed twice
The correct cards should be get in this case
sashok, hope I'm not coming off as needy, but I hope you could check your dms.. thanks and sorry in advance
No, please, write your question here and some one who knows the answer will respond
alright then
Although I don't see lastSordingIndex being assigned
You should get the card with the highest sortingOrder among the Raycasts
private int lastSortingIndex = 0;
private Vector3 offset;
private bool isDragging;
private void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit[] hits;
hits = Physics.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hits.Length < 0) return;
System.Array.Sort(hits, (hit1, hit2) => hit2.collider.gameObject.GetComponent<SortingGroup>().sortingOrder.CompareTo(hit1.collider.gameObject.GetComponent<SortingGroup>().sortingOrder));
RaycastHit hit = hits[0];
selectedObject = hit.collider.gameObject;
offset = selectedObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectedObject.transform.position.z));
isDragging = true;
}
}```
Now, please, format it as I have asked you 🙂
Yes
add c# after the 1st ``
And in this case, please, send it via a site
I'll just do this 😄
Thanks
I don't do anything yet with the selectedObject and isDragging, and also with the offset neither
https://hatebin.com/kyszaelfmr
https://hatebin.com/lntnbnjgtn
I know this looks atrocious( I have less than a day to finish the project), but currently the problem I'm facing is somewhat a Update() Overload(? I dont know how to phrase it properly)
where when I craft certain items it doesnt pop up (Cake and Cage) to be exact, but others do, they have the same function structure, same lines of code, so I guess the function is working,
but the update is overloading(still dont know how do you call it), could anyone help out or give some advice? Much appreciated.
Well, is the desired object selected?
Yes
selectedObject = hit.collider.gameObject
So the object, which is above all the others is selected, right?
I think so, yes
I got an index was outside the bounds of the array error to this piece:
RaycastHit hit = hits[0];
How so?
nothing hit?
Looks like it
Because of the -1 in the CompareTo being returned when hit2 comes before hit1
This way it's sorted as hit2 -> hit1, where hit2 has smaller sortingOrder
Therefore, hits[0] returns the lowest card
So I rather compare hit1 with hit2
Because of this line. The length of the array cannot be smaller than 0.
This way you get an error, because of you trying to access the 1st hit of the array, which has 0 items
You'd have to check it being the same as 0.
if (hits.Length < 0)
return;
Yes
https://paste.ofcode.org/zqi46GLVmfVfsfEgwsgQ9j
This is the new piece of code.
Fixed the error and inverted the Sort method
But it doesnt debug me anything yet
You may also want to use IEnumerable.OrderBy method instead of Sort
hits.OrderBy(h => h.collider.GetComponent<SortingGroup>().sortingOrder);
Hey guys, I would like a dropdown for my enum parameter for UnityEvents. Any way of doing this?
Alright
Yes, it was a simple suggestion before comping to the real issue
Make a script and a public method
Have done, not working
Alright, I'm confused then, what do I do?
Can the mouePos.z be a problem?
You have a 2D game, right?
Correct
you appear to have made no attempt to debug your code so you should do so
also I would return a bool from your confirm methods so you can see which confirm method is working and maybe take action because of that
I treid with Physics2D.RayCastAll, now it hits objects! Let me debug if its the correct one
Well, yeah, both Raycast and RayIntersaction would work
thanks for your response truly, but can I ask if Update() will ever overload or something? like if I have too much code for it, will it only work partially?
no, that will only be the case if an exception is thrown which you should be seeing in the console if that is the case
I'm so lost, this doesn't work either
additionally, I have try a few things that seems to me if Update() is relevant at all,
- I removed the craftCard function including the check if craftable all together, and the whole system works again
- I added a line of DebugLog in CageCrafting, specifically in confirmCraftCage after
if (canCraftCage && itemSlotScript.craftingImage.sprite != itemSlotScript.emptySprite)and seemingly no log was debugged. - I removed every item craft except Card, Cage and Cake, and only Cage seems to work.
hmm thats interesting to know.. then I'm even more confused. 
there is very little point adding Debug.Logs AFTER if statements because they tell you very little.
Add a Debug.Log of the variables used in the if statement before the if, then you actually gain useful information
And dont take them out when you post your code
Alternatively learn to use the debugger, it will prove to be much more useful
public void cageCraftingRecipe() {
Debug.Log("selectedItemImage=" + itemSlotScript.selectedItemImage.sprite + ", cakeLCraftItem=" + cakeLCraftItem + "selectedItemImage2=" + itemSlotScript.selectedItemImage2.sprite + ", cageRCraftItem=" + cageRCraftItem + ", craftingImage.sprite=" + itemSlotScript.craftingImage.sprite + ", cageCraftedItem=" + cageCraftedItem);
if(itemSlotScript.selectedItemImage.sprite == cakeLCraftItem) {
if(itemSlotScript.selectedItemImage2.sprite == cageRCraftItem) {
itemSlotScript.craftingImage.sprite = cageCraftedItem;
canCraftCage = true;
} else {
itemSlotScript.craftingImage.sprite = itemSlotScript.emptySprite;
}
}
}
selectedItemImage=CA (UnityEngine.Sprite), cakeLCraftItem=CA (UnityEngine.Sprite)selectedItemImage2=GE-export (UnityEngine.Sprite), cageRCraftItem=GE-export (UnityEngine.Sprite), craftingImage.sprite=1_Generic_16x16_0 (UnityEngine.Sprite), cageCraftedItem=cage (UnityEngine.Sprite)
UnityEngine.Debug:Log (object)
InventoryManager:cageCraftingRecipe () (at Assets/Script/forRoom1/InventoryManager.cs:330)
InventoryManager:Update () (at Assets/Script/forRoom1/InventoryManager.cs:83)
selecteditemimage1 and selecteditemimage2 is the same? how is craftingImage sprite still not = to cagecraftedItem ?
Opinions on making my SceneLoader class static? It's used for loading scenes, similar to SceneManager in Unity. Also deals with transitions and loading screens.
Is it possible to see the type of a variable inside of Visual Studio?
You should be able to hover over it and see
I am hovering
it says (field)
The type is TMP_Text
if you change it to int, then where you want to display the score?
create another variable to store it
First a lesson in how to write Debug statements. Try this one
Debug.Log($"selectedItemImage={itemSlotScript.selectedItemImage.sprite.GetInstanceID} cakeLCraftItem={cakeLCraftItem.GetInstanceID} selectedItemImage2={itemSlotScript.selectedItemImage2.sprite.GetInstanceID} cageRCraftItem={cageRCraftItem.GetInstanceID}
craftingImage.sprite={itemSlotScript.craftingImage.sprite.GetInstanceID} cageCraftedItem={cageCraftedItem.GetInstanceID});
good idea
So what you have there is a declaration. You have
public TMP_Text text_score
That means
publicyou can change or get it anywhere in the software without restrictionTMP_Textis the type, it is Text Mesh Pro text type, therefore Unity's way of dealing with texttext_scoreis the name of the field
float text_score_Variable_Carrier += TMP_Text text_score;
can't I do something like this?
Due to poor naming, I think you have got confused. This text_score name refers to the actual text... Not the score number.
If you wanted the score, you declare it like public int text_score
the tmp_text is a component in ui that displays the text
You need to actually read what I am writing
yep
I need to reference to that access to that and change it
so you need another varaible in your clsss to store the actual score then assign to the tmp_text.text
ok
i see what you mean
but why is it a problem that I name it text_score ?
I dont think thats a problem
So the mechancism of what you're trying to do is basically this.
You have the actual text, which is the TMP_Text. That is what needs to be updated.
Then you have the number or value, which is the score that the TMP_Text updates with.
there is no score
I named it text_score
but nothing in my unity is named score
im trynna create a score rn
Because it ambiguous, you're confusing the number(value) with the actual text.
yout should name it to score_text
ok
Perhaps to scoreText, according to C# naming conventions
btw keep your naming comvention consistent, snake_case and camelCase and PascalCase both exists in your variable names
I assume you missed a quotation at the end?
also, Assets\Script\forRoom1\InventoryManager.cs(319,80): error CS0428: Cannot convert method group 'GetInstanceID' to non-delegate type 'object'. Did you intend to invoke the method?
or should I have put the debug statement somewhere else?
They don't understand what the int is at this point, so I don't think the name matters. But yea it should be
@whole idol https://www.w3schools.com/cs/cs_variables.php
Well, yeah, I would say learning some C# basics might help.
I understand what the int is
its the type for number variables in c#
like float is another type for float numbers
and double is for double numbers etc.
I think i need to convert my scoreText variable
Just read the thing I sent you too.
Okay so you get that, yes. Now TMP_Text is like that, but actually for the text component itself
into a variable that can be editted
So what's the difference between int and float?
my bad
Debug.Log($"selectedItemImage={itemSlotScript.selectedItemImage.sprite.GetInstanceID()} cakeLCraftItem={cakeLCraftItem.GetInstanceID()} selectedItemImage2={itemSlotScript.selectedItemImage2.sprite.GetInstanceID()} cageRCraftItem={cageRCraftItem.GetInstanceID()}
craftingImage.sprite={itemSlotScript.craftingImage.sprite.GetInstanceID()} cageCraftedItem={cageCraftedItem.GetInstanceID()}");
one has whole numbers, the other one has numbers like this 4.43f
int has numbers like this 4, 5, 121 etc.
But how would you differ float from double?
no worries, ill try that now, thanks for the correction
Seisan, do you get this part? It's understandably confusing when Unity doesn't make it much clearer
doesnt matter, ill never use double anyways, double is more mathematical and more accurate and precise they say in complex calculations, thats it

selectedItemImage=90762 cakeLCraftItem=90762 selectedItemImage2=92154 cageRCraftItem=92154 craftingImage.sprite=90578 cageCraftedItem=204878
UnityEngine.Debug:Log (object)
InventoryManager:cageCraftingRecipe () (at Assets/Script/forRoom1/InventoryManager.cs:319)
InventoryManager:Update () (at Assets/Script/forRoom1/InventoryManager.cs:83)
Here are the result.
Hello, i have made a building system similar to Bad Piggies. However i'm having an issue connection the neighbour objects together, i have multiple object types (Ropes, Wheels, Blocks) that should have their own connecting types. The wheel should only connect if there's a block above it, the rope can connect to other ropes or blocks. What's the best way to do this? My current script checks the object type manually but i think the code will get very messy after adding more object types to the game. Thanks
the only way is ofc checking it adjacency cells(?) manually
you have serialize the eg accepted neighbors in list to prevent hardcode it or using json to define the connectivity
ok, so that tells me that both of your if statements are true
ok so i just realized
what my mistake was
and what someone of you where trynna hint at
and i fixed that
now scoreText I think will not work in the current set up that I have
int scoreTextVariableHolder += scoreText;
it seems to throw an error on +=
Yep, this is not correct syntax. This is why everyone is directing you to tutorials
public class Class{
private int _x;<-------|
public void Method(){ |
int _x=10;<----not the same _x
}
}
You shoudn't even worry about operators like +=, you should just stick to + and = then learn to code from the basics
yeah, thats why im pretty stumped on why itemSlotScript.craftingImage.sprite = cageCraftedItem; doesnt work... its infuriating
Please go and learn some C# and Unity basics as you have been told time and time again
ok
can anyone help why my speed is not increasing
This is an excellent tutorial
Since you know some stuff, you should wizz through it wth relative ease
So, I would do it like that:
-
Create a main class for all the objects you have, you may call it how you want, let's call it
Item -
The classes like
Rope,Wheel,Blockshould be derived from this main class -
The connection may be done by assigning multiple blocks to the parent
GameObject, so you may want every of yourItemsbe already placed in an emptyGameObject, which performs the position changes -
Implement the dragging object, I don't remember how it's done in the game
-
Implement a list of, I would say,
flag enums, which stores the items you have
[Flags]
public enum ItemType
{
Rope,
Wheel,
Block
}
- Every
Itemshould have its ownItemType itemTypeand theItemTypes collisionsit can collide with. Note thatitemTypemust have the logic of an enum, as if it doesn't haveflags. So have a singleitemTypeand multiplecollisions - When dragging the objects close enough to each other, check whether the each other's
collisionscontain the each other'sitemType
I literally wizzed through it the last time someone recommended this to me 3 days ago
note that you have only have up to 64 types if you use flag
Don't take offense because everyone is at different skills. But people are suggesting tutorials because you are not writing the correct syntax, which is fundamentally more important than int or +=.
I'd recommend following a guide for Unity then
but it does work. However itemSlotScript.craftingImage.sprite could be being over written by another method. So Debug your code everywhere you are setting itemSlotScript.craftingImage.sprite and see where this is happening
This channel is for fixing prolems assuming the person knows basics on how to code
Okay thanks i will try it
@whole idol This is a short video I found, I don't think it is amazing code but it's a quick start for beginners
please guys support me by wishlist my new steam game : https://bit.ly/3MVcipX
thnak your for watching ;)
for any question , let it in the comments
That's what I imagine you're trying to do
Good luck, don't be afraid to still ask
Yeah, that's so. Do you have better ideas if they want to have more items?
Hello, I am trying to read data from a json file. But getting this error.
Invalid vector string: 97.31, -47.31
This is the code for parsing the vec.
Vector3 ParseVector(string vectorString) {
string[] parts = vectorString.Trim('(', ')').Split(',');
if (parts.Length != 3) {
Debug.LogError("Invalid vector string: " + vectorString);
return Vector3.zero;
}
float x, y, z;
if (!float.TryParse(parts[0], out x) || !float.TryParse(parts[1], out y) || !float.TryParse(parts[2], out z)) {
Debug.LogError("Failed to parse vector string: " + vectorString);
return Vector3.zero;
}
return new Vector3(x, y, z);
}```
do you know how i can make the itemtype only 1 enum and collisions a flag type?
Impossible, unless you have 2 different enums. Just make sure you just have a single value for the itemType
OH I UNDERSTAND SOMETHING NOW THANKS FOR HELPINGME DEBUg
okay, i should also add an flags enum for direction right? because my build system is grid based
the purpose for flag is to fast checking for the type of other object collided with
What are you willing to use your direction for?
for example the wheel can only connect if theres a block type above its grid cell
this is why I said your methods would be better returning bool rather than void so you can then see if the method has been successful and then there is no need to carry out the following ones
you can still use the flag when assign the type to object, but you can only assign one enum to it
I see, then you don't use enums
i figured out the issue was I was using the same sprite for
ca <<< ke
<<< ge
<<< rd
and therefore it ran craftCake instead of craftCage
but still thanks for your debugging
can i create a thread? I feel the problem is hard to explain
You shouldn't ask to create a thread, of course, you can (and actually should)
hey guys i'm trying to access an object's component in DontDestroyOnLoad with this
public static CustomNM getNM()
{
// Je sais pas si y'a une version jolie pour faire ça
GameObject[] DDOL = SceneManager.GetSceneByName("DontDestroyOnLoad").GetRootGameObjects();
for (int i = 0; i < DDOL.Length; i++)
{
if (DDOL[i].CompareTag("RoomManager"))
{
return DDOL[i].GetComponent<CustomNM>();
}
}
return null;
}
but it says "this scene is invalid"
Should i use another thing to access it ?
Getting info from json and showing it on ui
I would probably recommend you to use a struct, which looks like a Dictionary, for this.
public ItemType itemType;
public List<Collision> collisions = new():
[Serializable]
public struct Collision
{
public ItemType type;
public List<Direction> directions;
//
}
unity has a built in type called Collision
Which is not usable in this case
Oh, sorry
I got it
Naming problems
then i wouldnt make the enum flags right?
btw maybe having four list for four directions and accepted item types
Well, yeah, you'd have to rename your class. It was just an example
Yes, because you should store the directions too
This might be a bit more complicated.
You'll have to enumerate through every single list
when you check the adjacency cell you first need their direction
top/bottom/left/right
it didnt give an error when i named it collision
so thats why four lists
Because they're in different classes, yeah. You still should rename it
I see what you mean
It's discussable
enum Direction{
top,bottom,left,right;
}
bool Accept(Direction dir){
//get the list at dir
//get the item at the cell at dir
//return if the item stored in the list
}
This will probably cause inconveniences in the Inspector
Because of them having to serialize all four lists.
Which might make it less easy to adjust
I would say, the performance wouldn't differ so much
They might find an item in the single list by its ItemType and check for the Direction being correct
Okay i implemented the item script to all prefabs, i didn't create inherited classes
The item, obviously, shouldn't always exist there
actually your way will slower than mine
Yes, I would assume so
that is amazing
now i have a much better idea of what to do, thanks
But as I remember from playing that game in my early childhood, the objects aren't merged too often, so the performance won't be affected almost at all
Enumerating through even a hundred of different ItemTypes won't cause any issues if done every second
This way, I would prefer the convenience in the Inspector
That's what you're going to do now,.. right..?
By the way, both methods can be combined. Serialize a single list in the Inspector and then split it into 4, for four different Directions, in the Awake.
How would one go about getting a direction from a Quaternion.AngleAxis?
Direction? 🤔
Basically I'm doing something like a radial check using quaternion angleaxis. I need to convert into a direction to raycast to check if somethings there before operating it
does putting this in update cause lag?
no
AngleAxis is a method that gives you back a quaternion, a rotation. You should specify what you are actually solving with this, not what your solution to a mysterious problem is. This sounds like an XY problem
No but why would it need to be updated every frame?
You should do this only when the playerHealthMax changes
Stuff in update adds up and will cause lag at some point
You cannot convert rotation into direction
hmm ye i should probably do that
So I have a flying enemy that has an ability similar to a dash, it needs to get a direction to dash but i need to make sure there arent any obstructions. In order to do this I want to implement something like a radial check from an intial random direction. During the radial check a raycast is checked.
It sounds like you just need to rotate a vector. You can use the result from the AngleAxis function (returns a quaternion) to rotate your initial random direction
Vector = vector * quaternion
Will rotate it
This sounds like it will work trying it now
I think they need to find the nearest rotation to the direction, which doesn't have the colliders on its way
Is that so? @abstract finch
That's not really what it sounds like, anyways that'd just be solved with the built in quaternion functions.
I'm not sure tbh, I just know Im sending a raycast in a direction, if somethings in the way then i raycast next basically in a 2d circle
the red represents the initial raycast and the direction it will check
Do I understand you correctly?
that looks right if the red is moving toward a direction
Red circles represent obstacles
And blue one is the position before and after the dash
yea
If it has to check clockwise, than the logic in the image is wrong
What is the desired direction? 12 AM?
well it doesnt have to be specific to where which direction it rotates along, as long as a full radial check si done
What I said above should work perfectly fine for this.
I want my enemy to turn completely white when damaged, I'm not sure how to do that, as setting the rgb to white is just the sprite's original colour, can anyone help?
Is this accurate then?
It worked thank you so much! Do you know how i can duplicate a joint 2D without resetting the values?
But you haven't mentioned how to find the desired rotation, have you?
Looks right but it doesnt need the circle below the desired and the circle right of the nearest
Alright, just starting from the desired rotation and moving clockwise, right?
They never mentioned anything about a desired rotation. You're the one who made it up
No, I don't
specifically a desired direction yea
I'm not the one who made it up. They asked how to find the nearest rotation which won't collide with the obstacles
I assume, they didn't want to simply rotate it
https://gdl.space/tacapodabe.cs Hello, for some reason the raycastHit.textureCoords is always 0,0 here. Could someone please help me find out why? the texture is a blank tex2D generated by the script in the link as well
Yes, so they take the initial vector and simply rotate it until finding the directions that do not collide. Where is the confusion?
Do you want them to check the rotation coordinates like 13.0001,13.0002, 13.0003 all the way up to 359.(9) in a loop?
I simply need a vector3 direction, im trying the code once i fix my unity
I assume, this might affect the performance
? What
I have interpreted what you've mentioned, haven't I?
This way they will have to call raycasts countless amount of times
No, I think you've misunderstood the problem
Perhaps, is there any way you could explain it to me?
hellooo I need some help real quick. I have this script that has a countdown from 30 to 0 but I cant seem to get this one part to work. I want to have a trigger where when tag player enters the timer stops and the script stops too but it aint working lmao
here's the script for the OnTriggerEnter2D code. Do I have to wrtite something else orrrrr (also ignore the other GameObjects lmao
public class Timer : MonoBehaviour
{
public GameObject timeText, inGame, postGame, gameOverTimer, gameOverHealth, fallOG;
public float timeRemain = 30;
float timer = 0;
bool timerRunning = true;
private void Awake()
{
timer = timeRemain;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
timerRunning = false;
return;
}
}
What you sent me is what i needed thanks,
Debug.DrawRay(transform.position, axisRotation * startDirection, Color.red);```
where is the bool timerRunning coming into play
How do you ensure the axisRotation doesn't collide with anything?
here
void Update()
{
if (timerRunning && timer > 0)
{
timer -= Time.deltaTime;
}
else
{
timer = 0;
timerRunning = false;
}
if (timer == 0)
{
inGame.SetActive(false);
postGame.SetActive(true);
gameOverTimer.SetActive(true);
gameOverHealth.SetActive(false);
fallOG.SetActive(false);
}
timeText.GetComponent<TMP_Text>().text = timer.ToString();
}
}
if (timer == 0)
never test floats for equality
Physics.raycast check
this