#๐ปโcode-beginner
1 messages ยท Page 271 of 1
how what? and why do you have the prefab in the scene?
how what
your pipespawner should be the thing that puts copies of it in the scene
i thought u had it working? why is it not working now
Yes
do u remember 20 minutes ago us helping u modify the code to work better?
Yes
we didn't follow along with that video.. soo its bound to be a bit different now
im sorry, im not familiar with iirc ๐ตโ๐ซ . but alot of my confusion comes from whenever i make a .jslib to go into my plugins folder, i get this thingy for my inspector
how do I change it tbh. I'm trying but it can't convert the quaternion properties to RB.
A bit different because that`s 2019?
after a week on khan academy i am finally able to understand math in unity 
would you perhaps have a link to this read?
What is "different"
iirc means "If I Remember Correctly"
This
What is the actual problem though. What is the thing that is different
alright, thank you, ill keep that in mind. i think you were the one who helped me find this channel, thank you by the way.
@rich adder https://hatebin.com/rqlizjnuwq I think the only line that needs to change is line 39 right? Since it's the one that really changes the movement of the hammer. And controls how it moves.
I identified the RB's existance but I don't know how to properly apply it
I did as in that video, but it didn't work for me, and here it turned out that a lot needs to be done to make it work again
do you guys think i should do a different script for attacking vs movement?
What isn't working
I cannot see your screen
Working now
Yes
they look identical to me
ok ty
you sent a screenshot that says "how" and provided no context
Make things as modular as you feel comfortable. More scripts is better than mega scripts
more scripts with good names ๐
how would i do it if i only want the player to move if they arent attacking?
if u get passed 1k lines. start to reconsider what ur doing
thankfully im not at that level yet
good, good lol
was this but stumbled on it a while ago idk if anything changed or perhaps I misread it .
https://forum.unity.com/threads/how-does-jslib-file-work.1379448/#post-8690661
Does anyone know if there's away to search these channels with some search bar so i dont have to skim for say, javascript mentions?
im going to play some video games lol..
for example the methods I listed already
transform.rotation to rb.rotation for example, or better .MoveRotation
the forum you will probably find better info
@rich adder @rocky canyon thank you guys
good luck ๐
I tried changing to rb.rotation but it didn't work. I think applying moverotation now wouldn't make much sense right? Since torque is a similar thing (at least from what I saw on the description).
im still at this, verified that its the animator causing this, where do i go from there?
And also the script with the flip method is attached to a empty parent for the characters sprite, again it used to work but suddenly it doesnt
thats not a problem with rb.rotation.. thats a problem with ur syntax
ah yes wait in 2D rotation is a float
try MoveRotation instead
lol i read MoveRotation when i read it
moverotation? Is that a class from RB?
yes, Function*
oops
it uses a quaternion..
nvm it uses an angle.. 2d*
need some conversions
oh yeah looking at my script again
arm.MoveRotation(Mathf.LerpAngle(arm.rotation, zRot, speed * 100 * Time.fixedDeltaTime));```
im using float
opsies
dir = (mouseWorldPos - arm.transform.position).normalized;
zRot = isInverse ? Mathf.Atan2(dir.y, -dir.x) * Mathf.Rad2Deg : Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;```
mine too.. why u still using rb.rotation?
start angle?
Look, they said to change the transform in the parentesis, but originally there where 2 tranforms and then they said to change the rb.rotation to rb.MoveRotation but now there's 2 RB's which one do I change

if you see earlier I corrected mysellf
btw what do i do if i want to reference loads of variables from one script, would it be best to make them the same or a different script?
2D does not need quaternion for rotation , its float
you have to get the angles in degrees
I showed you example how I did mine @twilit ocean
rb.rotation is a single float. 2D rigidbodies can only rotate around one axis.
I'm struggling to understand how to apply it on my current code
i feel so dumb i am making my very first project and i cant figure out how to make my game end/go to win screen when i make it to my object (just making a basic platform but trying to learn stuff as i go) can anybody help with a working script that i could study?
wdym its exactly like yours..
execept for the rotation part
Mathf.Atan2 * rad2D to get the angles then pass them in the Lerp (you have this already)
Get rid of all of that Quaternion stuff. There are no quaternions here.
note that Mathf.Lerp will not be appropriate here. It won't correctly handle how angles wrap around when they pass 360.
fortunately, there's Mathf.LerpAngle to replace it
yup thats what im doing now, but my lerp is wrong
this is 2 year old code :p
arm.MoveRotation(Mathf.LerpAngle(arm.rotation, zRot, speed * 100 * Time.fixedDeltaTime));```
I would suggest using Mathf.SmoothDampAngle or Mathf.MoveTowardsAngle for more consistent behavior
The former is good for reaching a target in a fixed amount of time. The latter is good for moving at a fixed rate.
... So I do already have the part that stores the mouse position and reads it back.. What part exactly do I need then? I'm really not sure on what here are actual classes and methods and what's your personal names for those functions. I'm very new to all of this so I don't know the names from my head.
I removed the quartenion stuff but I don't know what else I need to take away and what should I keep.
like i said many moons ago, all you're changing is transform.rotation to one of the rigidbody rotation..i never mentioned anything about the mouse
i just showed you that we had the same exact code for angles
the reason why its confusing is transform.rotation uses quaternions
rigidbody2D has no rotation methods with quaternions its floats (angle is only 1 axis here)
So ok lemme get this straight. All I need to change is the last line that sets how the hammer moves correct?
Using the Mathf.LerpAngle method?
if you want more accurate simulation of phyisics
yes or the methods mentioned here #๐ปโcode-beginner message
btw these are just to make it smooth going from one rotation to another
to make sure I'm up to speed here
the hammer was being moved by setting transform.rotation
yea
this was causing physics issues because this was bypassing the physics system
use the Parent Constrain component if you dont want to inherit scale
Yes, here's the current code https://hatebin.com/lilgbqctdu
you can also make a 1,1,1 object to parent to thats child /sibling i think
you're trying to set the position of the rigidbody here
i'm surprsied that isn't a compile error. does float implicitly convert to Vector2...?
no, it doesn't
oh, I see there's another compile error
those arguments don't make any sense
MoveTowardsAngle takes three arguments:
- The current angle
- The target angle
- The maximum change
they're all out of order and direction doesn't make sense at all here
brt just changed my old one to
arm.MoveRotation(Mathf.MoveTowardsAngle(arm.rotation, zRot, speed * 100 * Time.fixedDeltaTime));``` is this correct lol seems the result is same so tis not broken at least
speed * 100 should just be speed, where speed is the maximum angular velocity (measured in degrees per second)
does someone know why it isnt "bouncing" ?
Cannot instantiate objects with a parent which is persistent. New object will be created without a parent.
Instantiate(dmgNumberText, enemyPos, Quaternion.identity, GUI.transform);
it seems to not show the layer of the object in the videobut it is indeed the layer 6&7
why are you checking the layer like that instead of just reflecting the velocity using the collision's normal?
not as snappy
did you put the canvas in DontDestroyOnLoad?
well, yeah
could you elaborate on collision normal pls?
it's speed degrees per second
no
if you want it to be faster, make it faster
does anyone know how i could manage to get game elements outside the game? id like to create a small launcher before the game boots
ohhh he's using words I can read, so should I remove "rb.position" what do I replace it with? You also said direction doesn't make sense but direction has the target's position no?
well, sure, but you're supposed to be working with angles here
you can get the normal for the surface that was collided with by getting the first contact
you wouldn't use a string that says "he's over there!" to calculate the angle to move to, now would you? :p
oh, you're referencing a prefab
what do you mean with the normal?
GUI is probably a reference to a prefab. You need a reference to an actual thing in the scene.
oh yeah much better lol
You can also vary the speed based on how far you are from the target.
i mean im instantiating the prefab as soon as the game starts
Okay, but GUI is still a reference to a prefab.
Instantiating it doesn't change what the variable refers to.
It just creates a new instance of whatever the variable refers to.
https://docs.unity3d.com/ScriptReference/ContactPoint2D-normal.html
This is the normal vector, that is the vector that is perpendicular to the surface or the incoming Collider2D at the contact point.
Calculate the angle you want first.
Then use Mathf.MoveTowardsAngle to figure out what rotation to give your rigidbody.
ty!
hmm that makes sense but I don't think I have a variable that stores the current angle do I? Like, the variable Angl
rb.rotation
alternatively, if you are just trying to make it bounce you can just use a physicsmaterial2d that has a higher bounciness
by definition, that is the current angle
i cant actually find any tutorial videos on how to use parent constraints, and I don't really understand how to use them from Unity documentation... Do you know any tutorials or anything?
im just trying to make it bounce but i dont know what physicsmaterial2d is
This is the page you're reading?
rb.position still wrong
wait what I put that there. Wow that's surprising I thought it would be wrong because "yes".
So property 1 and 2 are correct right? Angle is the current mouse calculated angle and rb.position is the angle of the rb (ofc)
no, rb.rotation is the rotation of the rigidbody
https://hatebin.com/yuszijpoun I have this script that teleports player to the destination position which is just behind the door object. I made the door a prefab with destination empty. I assign the destination on the inspector. However when there are two doors. I come out of the first door's destination. I assign them seperately in the inspector why is this happening?
rb.position is not the rotation of the rigidbody
forgot to change to rotation
_playerTeleport = FindObjectOfType<FPETeleport>().GetComponent<FPETeleport>();
This finds an FPETeleport...somewhere
this?
Are you sure there's exactly one of them?
Yes that is where my teleport script is.
It works fine if there is one single door
if (_playerTeleport.isPlayerInRange && Input.GetKeyDown(KeyCode.E))
{
StartCoroutine(_playerTeleport.StartTeleport(_destination.position, _destination.rotation));
}
Both teleporters run this code.
Both of them try to teleport the player.
The player should ask the FPETeleporter to do the teleportation.
That way, the player can look for a nearby teleporter (maybe using Physics.OverlapSphere to hit a trigger collider) and ask it for a teleport.
So all that's left is the Maximum rotation. How do I set the maximum rotation? Maybe 360 would be it?
So teleporters should not run this code. Instead player should do the teleportation
This is the amount of rotation that you want to happen when this method is run.
This code is in FixedUpdate
360 will cause you to rotate by up to 360 degrees every physics update.
Right. The player should call a method on FPETeleporter
The teleporters shouldn't need to find a FPETeleport component and shouldn't be checking for player input
It should be called minimum rotation at that point ,_,
I think this might not be the right solution for my problem, I have a platform that can move, and I made it so the player moves with the platform, but when the player stands on the platform, its capsule becomes really skinny
idk why i replied to that
Yes, because you've parented the player to something that's been scaled.
The solution is to not do that.
huh
One option is to rearrange things a bit
i have a question, why not just do
transfom.position.x = -10```
in the if statement?
oh
- Platform <-- not scaled; you're parented to this
- Visual <-- scaled
wait i think i get it
It's a quirk of how C# works.
transform.position is a property
It calls a method when you access it.
The method returns a Vector3
yeah but in the condition he just did that
Vector3 is a struct -- it's a value type. When you have a Vector3 variable, it's literally just 3 floats glued together. It's like an int or a bool in that you don't store a reference to it
would it not work in the code itself?
let me finish (:
ah okay
A string is a reference to some data somewhere else
that's a reference type
Value types are never shared. They're always copied.
So transform.position returns a Vector3
In my game there are two 'modes' (I don't know what else to call them) the player can be in, Overworld and Battle. I only want the player to do 'battle' actions such as attacking when they are in battle mode and 'overworld' actions when they are in overworld mode, and I want the controls to change accordingly. I've heard you can do this witht the new input system, but I'm not fully sure how.
This is what i've done so far
Nobody else can see that Vector3, because it's a value type.
Assigning to one of its fields would be completely pointless.
You'd be modifying a Vector3 that nobody else will ever see
Thus, you get a compiler error.
There's no point in doing it, so if you do it, something must be wrong.
I see
Now, you can read from a field just fine
that makes more sense, thank you
you're reading a value from the copy
Ok so the right call is to make this a public variable that I can regulate when I need to change it or is there smart answer for that too?
a related tangent -- https://docs.unity3d.com/ScriptReference/ParticleSystem-main.html
This is why you have to do that weird thing:
var main = ps.main;
main.startDelay = 5.0f;
main.startLifetime = 2.0f;
ParticleSystem.MainModule is a struct
It's a struct full of properties that, when set, call some code to actually modify the particle system
So in theory, this would work just fine
ps.main.startDelay = 1f;
It'd correctly call a method that would go tell the particle system to change its settings
that wouldn't work floats need a decimal
so 1.0f
1f == 1.0f
oh
1 would also be fine. integers can implicitly convert to a float
But C# sees that you're assigning to something on a value type and flips out anyway.
hence the awkward code
You need to multiply by Time.deltaTime so that you change the rotation at the correct rate.
(in FixedUpdate, Time.deltaTime is set to be Time.fixedDeltaTime, so you can use either)
By default, Unity runs physics 50 times per second
So Time.fixedDeltaTime will be 0.02 (as will Time.deltaTime inside FixedUpdate)
If you want to rotate by 360 degrees per second, you must rotate by 360 * 0.02 degrees per physics update.
this works out to 7.2 degrees per physics update
360 * Time.fixedDeltaTime does the trick
My brain is legit burning 
Ok, if I got it all right, putting 360 * Time.FixedDeltaTime will make it work?
Using that for the maxDelta argument will let the rotation change by up to 360 degrees per second.
so this?
That looks reasonable, yes.

Well, at least it's moving so that's great, but the hammerhead is going wild
thats because the hammer is non-uniformed scaled, when you rotate the child hammer skews
Ok you gotta explain what are those words. What is something non-uniform scaled?
How do i use the action maps i have set up here in unity to achieve what i want?
Given an InputActionMap, you can call Enable or Disable on it to enable/disable all of its actions.
instead of numbers being the same they are not,
eg
uniform : x 0.5f, y 0.5f, z 0.5f
non-uniform : x 0.3f, x 0.5f, x 0.1f
ok ty
non-uniform scaling causes skewing when a child object rotates
The child experiences scaling in varying directions as it rotates.
make the hammer head child of player and attach it to hammer with a fixed joint
well if that's the case a hammer is not uniform by nature.
will try
or just parent the various visuals to a single object
avoid parenting something to a non-uniformly scaled transform
using fixed joint . legs too long or arm not long enough 
So making the hammer a single, more complex collision shape, and all the visuals just parents of it with nothing running?
You can have several primitive colliders parented to the object.
Instead of 2 separate collisions boxes?
a rigidbody uses all colliders parented to it.
So which one is more appropiate? One single collision with the shape of the hammer or 2 square-like boxes that have a similar-shape?
Whatever's easier to implement.
if I am trying to each of my characters to have a different hability (like an smash attack in smash) how could I face that?
I guess 2 colliders might also make it less capable of going through objects since it checks twice in overlapping points.
At least in my ooga booga logic (more equal good)
A script for each of the habilities?
@rich adder @rocky canyon update Solved ๐ฅณ Thanks for the tips. All in the search tool.
in here? nice
anyone know of any 1 on 1 tutoring services for Unity?
more financially viable to teach yourself
many many tutorials both text and video format
Thanks for all the help till now @swift crag @rich adder. The current state is still a little glitchy and I'm not sure why, since all calculations are being made in Rigid Body now.
I'm just thinking that we've been here for so long bcs I'm quite dum when it comes to coding.
if you're talking about the hammer going into stuff, it literally has no collider or rigidbody
ahhh the recording is all chopped
fixed joint goes on the hammer head with rigidbody and collider
I put my Mass probably too high, but you get the point
same ๐ฆ
ahh thats the one u were talkin about earlier
Is there a way to show this in the Inspector? Somehow the inspector doesn't show things computed with =>. The original objecti is not serializable.
yeah idk why its completly disabled now, it used to work..somewhat just badly
Even adding [SerializeField] will not show the fields in the inspector.
maybe they disabled it
At the end I showed the collisions. The hammer got all the collisions on it and the head is just attached to it
props don't show in the inspector
this is all types of wrong. why does the fixed joint on the Arm hammer, and why is rotation on Z locked?
and [Header] only works immediately before a serializabe displayed field
But doesn't [field: SerializeField] work for properties with simple setter/getters ?
yes, which is not the case here
afaik it will not work with =>
Is there a way to show a general ToString() in an inspector?
I don 't know what does "why does the fixed joint on the arm hammer" means but the Z-rotation is locked because of this
Basically, I have my own custom class, but want the inspector to show property.ToString()
because you still have a fixed joint on it..
so its locked to player
the arm hammer should have the Hinge joint to player, then hammer head is fixed joint to arm of hammer
So removing the pivot you say?
replace it with a hinge joint
so it swings attached to player rb
and also affects it
What should I replace?
I just tolds you
This then ?
yea
Cant wait to see what will happen
found an alternative if ur interested?
oh yeah I heard of that one, the only thing Im not a fan of is the telemetry but thats understandable
also its more like copilot than intellicode
true, but thats the rabbit hole i found that wasnt blocked ๐
do let me know if the results are decent with it
Man someone among u op guys take me under u and train me ๐
That's called tutoring, which isnt a thing given out for free
you probably couldn't afford it
too much work
sum weird stuff. Hammer can't lift the player anymore.
learning urself and reaffirming things in this discord is ๐
Getting over it?
make it have more umph
Nope, thought of a physics combat system idea and this will be a goof first step to what I want
is the player rigidbody locked ?
its a refreshing prototype to see around here
you are probably moving using Velocity instead of addforce maybe ?
that might override any external forces
ya, ^ tahts true..
//GetAxis only the axis being pressed and sets the movement on the H-axis based on it, GetRaw sets it to 0 when detects opposite movement
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);``` this is the whole movemente tbh
yup
I move using AddForce so i probably why my player gets affected
private void FixedUpdate()
{
rb.AddForce( Vector3.right * (input.x * moveSpeed));
}```
if i want an interactable to be highlighted/hover or w.e when lookin at it whats the best setup for that?
should i do that thru the raycaster (pov object) or tell the interactble to do that.. and then should it be an interface if its going to have a couple of interacted effects
hmmm what's input.x?
make seperate script for highlighting maybe ?
whatever forces ur hammer is making the player experience ur velocity = is just overwritting it with ur move vector
its a float from my V2 input same as yours
with an interface to raycast for?
i think i know how imma do it.. just its the same ole thing i always do
Interface is good
might be able to even levarage the ones already built in Event System with the IPointerHandler
using 3D physics raycaster on cam
holy crap i cant figure out how i call these events
VStudio wont tell me or idk how
Something like this then?
you didn't have to rename it from dirX
not sure why you did that
but yea ig
oh yeah that's because I changed it to a vector2 for a moment ("dirX.x" really?), but then I would have to change other things and realized I didn't had to do that.
well no even dir would not make sense to me
I make it v2 because usually do
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");```
you dont need vert, so you could just do horizontal = or w/e
also get ur inputs in Update and pass them in FixedUpdate
that's resonable, might do that
why is it not letting me
Can't reference scene objects from a prefab
Alright Thank you
Wouldn't the bullet just damage whatever it hits? Why does it need a direct inspector reference to the enemy?
why is bullet referencing specific enemy?
Get the reference in OnTriggerEnter2D or OnCollisionEnter2D.
becuz i wanted to test smthn like when the bullet collides it destroys the game object but it ended up destroying both the player and the enemy
i might just change it so it gets a certain tag then destroy
it was probably colliding with player and you weren't checking specific object maybe?
yea thats why
How do I use transform.LookAt without changing the x and z rotation?
I would like to lock the x and z but clamp doesnt work
var pos = transform.position
pos.y = target.y;
transform.LookAt(pos);```
?i think
ah yea
var pos = target.position;
pos.y = transform.position.y;
transform.LookAt(pos);
been a while ๐
But that's going to change your pitch and roll
Or do you just want to make the transform look perfectly horizontally towards the target?
without any up/down pitching?
If that's what you want, then this will do the trick.
Thanks will try implementing one moment
I followed a tutorial and now have a working tic tac toe game, yay! I followed another tutorial and now have a working restart button, woohoo! I'm now really lost on how to write a script to check for winner . Is there anyone who can help me? I'm completely new to game dev, unity and programming.
For a game with a small number of configurations like tic-tac-toe, you can really just brute-force it
depends howyou defined the move of each player
dont watch many tuts to avoid getting stuck in a tutorial hell
check each row, column, and diagonal to see if all three tiles have the same mark in them
I'm already there, trying to get out lol
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
when I mademine a while ago I had an enum (X, O, none)
helped me a ton
then checked with looping the grid
So that seems to be the easiest solution I've found however I'm really not sure how to write that. How do I setup the grid in unity?
I presume you've already implemented the tic-tac-toe game.
you can even use a 2D array
Yes I have and it actually works lol
so you're just looping through each colum and row
It might help to write a method that gives you every possible line through the board.
It would look a little bit like this.
How do I do that? Is there a tutorial you recommend for that?
Show us how your game actually works first.
Okay, do I just copy the codes or what's the best method?
!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.
Tried to do something similar for the jump but it didn't work out
How do I detect when two colliders with two different tags are colliding.
i dont recommend putting any inputs inside FixedUpdate btw
esp a one frame event like KeyDown/ButtonDown
I'm sorry for all the questions and appreciate all input
why are you waiting for player to press Jump and hold up arrow ?
Putting my son down for a nap, gotta step away for a bit. Thank you all again
public IEnumerable<List<Vector2Int>> GetLines()
{
for (int row = 0; row < rows; ++row) {
List<Vector2Int> rowLine = new();
for (int col = 0; col < cols; ++col) {
rowLine.Add(new Vector2Int(row, col));
}
yield return rowLine;
}
}
This method would give you every combination of grid squares that form a winning row. You could then also add columns and diagonals in a similar way. Given this, you could see if any line has the same mark in every single cell. If you find one, that player wins.
You could also just write them out by hand, I suppose
OnCollisionEnter
but I'd rather automate it (what if I want to do 5x5 tic-tac-toe?)
what does "esp" means
Right I know about that, but my object uses colliders that are childeren, with tags. I want only certain parts of those childeren to interact with another object that has a tag.
short for especially , sorry
wait "vertical" is the up arrow not space key? 
you wrote dirXY.y
thats linked to up arrow / W-S key
if you're not holding it then your value is 0
whats any number * 0 ?
maybe explain what mechanic / feature you're trying to do because sounds like you can just check the tags
or do you mean just colliders ignoring eachother
I feel like its hard to explain without just showing you what Im doing
make a video
Good idea
why is it Type Mismatch if I am introducing a png?
it requires a Sprite but isnt this type of image ?
And how about the full inspector for this?
yes -- I'm looking for the full inspector for whatever this is clipped from
sorry, I am not understanding what you want me to show you
it is an scriptable object
Hey, guys! I have a small issue with a game mechanic I want to implement. So, whenever my player reaches +10 score to increase speed of moving elements which are background layers, ground layers and tree logs prefab slightly. For one reason, my tree logs prefab doesn't increases the speed.
hm, everything looks fine. Dragging in the Texture2D asset should assign its sprite sub-asset to the field
i just tried doing that myself
yeah it feels right, I dont really know what is going on
What if you click the arrow to show the sub-assets and drag one of those in?
importantly, is there more than one sub-asset in there?
it ought to look something like this
there are 2 more
there's only one sub-asset here
it is a PNG so it cant be the image format
if value a = 60 so value b = 0, how do I make value b go up to 30 if value a goes to 0?
Did you try dragging this sub-asset into the field?
You can use Mathf.InverseLerp and Mathf.Lerp for this
not working
float t = Mathf.InverseLerp(60, 0, a);
b = Mathf.Lerp(0, 30, t);
do any sprites work?
InverseLerp produces a value between 0 and 1
no, no sprite
If the third argument equals the first argument, it's zero, and if the third argument equals the second argument, it's 1
and it's linearly interpolated in between
show me the script that defines the scriptable object
Is this EntityData object also an asset?
i.e. you used the create asset menu to make an instance of it in the project window
use triggers or perhaps Overlapsphere/box
you mean this?
Yes.
the strangest part is that when I assign the image in the gameObject directly it works
you mean when you assign it to a SpriteRenderer's sprite field?
yeah
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(fileName = "New Character", menuName = "Character")]
public class EntityData : ScriptableObject
{
#region CharacterStrings
public string Name;
public string Description;
#endregion
#region Sprites
public Sprite CharacterSprite;
public Sprite BulletSprite;
public Sprite ShieldSprite;
#endregion
#region damageParameters
public float meleeDamage;
public float bulletDamage;
public float bulletSpeed;
public float punchDuration;
public float ammo;
#endregion
#region moveParameters
public float moveSpeed;
public float jumpNumber;
public float jumpForce;
public float weight;
public float dodgeTime;
#endregion
#region health
public float health;
#endregion
#region boost
public float MaxBoostQuantity;
public float WhenHitAdd;
public float boostMultiplier;
#endregion
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
okay, so there isn't anything that could be modifying those fields
at this point i'd restart the editor and see if it starts behaving properly
okay lets see
not working
what version of unity are you using?
How do you make it so your player instantly stops when releasing the movement key in 2d instead of deaccelarating till stopped, do you need some kind of code or just change something in the rb
2022.3.19f1
!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.
Set the velocity to 0 when you're not pressing a move key
I see no reason for a type mismatch to happen here. I guess I'd whack this with the "delete Library and reimport everything" stick at this point.
But that's the thing my horizontal jumping range is based on my velocity x so if I would let go of my movement key mid jump the jump would also stop
oh, how can I do that?
close your project, navigate to your project directory, and delete the Library folder
you can also delete the Temp folder
don't delete anything else (especially not the Assets folder)
Reopen the project and Unity will reimport everything. This can take a while.
It'll forget which scene you had open, so you'll need to go to file -> open recent
can you try keeping the rigidbody's x velocity while it's midair and applies the 0 only when it's not midair
You would get a type mismatch if the type was previously different. Deleting the reference and reassigning it should be the fix
hm, yes, i should have suggested clearing the field..
So basically I would use if(isGrounded = false && input.getkeydown(horizontal)
{Rb.velocity.x = 0} would this work
close, but you can't assign to the x field on rb.velocity
store the velocity in a variable, modify the variable, and store that back into rb.velocity
deleting the reference in code?
Is isGrounded = false the same as !isGrounded
not working
since = is the assignment operator
so the field went from "Type mismatch" to "None"
Oh yh obv
based on what you assigned it to
and then you reassigned something and it went back to "Type mismatch"
yeah, I then reassigned it and isnt working
well, go ahead and do this, then
lets see
Oh nvm I can just use my movespeed variable instead of rb velocity since earlier in the script I did rb velocity * speed and times 0 = 0
it didnt
it didnt work
Add another field that references, say, a Material. Does that work?
do you have any errors in the console? @ionic zephyr
not reallty
Alright I got a question for you guys, I'm stumped.
Right now I'm accurately finding the corners of a rectangle by simply just getting the objects position (center) and just adding half of its x scale and half of its y scale for each corner. So basically for a 2x4 rectangle, one corner is the center position + 1 to x and 2 to z etc. Like so:
Vector3 size = unityObstacle.transform.localScale / 2.0f; // half size for offset
Vector3 center = unityObstacle.transform.position;
// Calculate the corners of the base of the rectangle
Vector3 corner1 = center + new Vector3(-size.x, 0, size.z);
Vector3 corner2 = center + new Vector3(-size.x, 0, -size.z);
Vector3 corner3 = center + new Vector3(size.x, 0, -size.z);
Vector3 corner4 = center + new Vector3(size.x, 0, size.z);
Simple enough. However, here is the conundrum. When I rotate the object inside the editor. It's x and z scale is still the same obviously, but it's rotated 90 degrees for instance, so it won't work anymore. How can I instead find the corners for any rotation? Best case would be to find a solution that works with any rotation, however I can live with 90* rotations.
Itโs a type mismatch on an asset trying to reference another asset. Very odd.
it works with Material
Maybe there is a way of doing it the same way, as if it wasn't rotated. Then use some mathematical formula that rotates the whole thing in the code as well?
its just the type mismatch
this can get really simple, actually
Oh eager to hear it
transform.TransformPoint(new Vector3(-0.5f, 0, -0.5f));
This computes the point at [-0.5, 0, -0.5] in the transform's local space
the result is a world-space point
This will account for position, rotation, and scale.
do you have a class named Sprite, by any chance
Oh SHIT
There it is :p
I got fooled by the icon
and I was not expecting the assignment to be even permitted in the first place
Hm not sure I follow. The object is created in the Editor not in the script. So the only coordinate I have is just the center position. The four corners I just get through using its .x and .z
But are you saying the .x and .z would be different in world scale?
.x .z in scale that is
ah, this isn't an object in the world
You can still do something similar.
You can construct a Matrix4x4 from a translation, rotation, and scale. Then you can use it to transform points.
var matrix = Matrix4x4.TRS(center, Quaternion.AngleAxis(angle, Vector3.up), size);
var result = matrix.MultiplyPoint(new Vector3(-1, 0, -1));
(i forgot you had divided the size by 2 already; i think you can just use [-1, 0, -1] here)
and actually -- use MultiplyPoint3x4 instead
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
[Header("References")]
public Rigidbody rb;
public Transform head;
public Camera camera;
[Header("Configurations")]
public float walkSpeed;
public float runSpeed;
[Header("Runtime")]
Vector3 newVelocity;
// Update is called once per frame
void Update() {
newVelocity = Vector3.up * rb.velocity.y;
float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
newVelocity.x = Input.GetAxis("Horizontal") * speed;
newVelocity.z = Input.GetAxis("Vertical") * speed;
rb.velocity = transform.TransformDirection(newVelocity);
}
}
MultiplyPoint3 works for any matrix. MultiplyPoint3x4 works for simpler matrices, including this one, and it's a lot faster
Is the rigidbody kinematic by chance?
yeah
And also, for next time, !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.
Can't set velocity of a kinematic body
So yeah, that is the issue
Either use MovePosition or set it to dynamic
ok
I think i saw it earlier
!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
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
beat me to it
Does anyone have a good tutorial video on coding movement for a 2d space ship that follows the direction of your cursor and buttons for forward and back.
Can't seem to find one
how specific
Yeah I'm trying to peicemeal it together but I am a super coding beginner
well start with one step at a time then
get the direction part sorted first
I've been trying to make an object flash white upon collision with a bullet. This code used to do it until I tried to make it better, which failed, and now I've gone back to the old code where it used to work, and it doesn't seem to work anymore. This is the same script where an object is assigned health, loses it, and destroys itself upon running out, which is why the rest of the script is there. Here is the code: https://hatebin.com/bpvnrgeddn
does anyone know what is going wrong here?
That makes sense I tend to jump on everything all at once. Direction will be tonight's goal
show where you put this script
best way to approach anything big, is breaking it down to smaller and easier to solve problems
Ty
The bullets collide fine, the health works perfectly, it just doesn't flash
what about the collider
its on and working
oh sorry
I have a small game for a small project, i can run the entire game smoothly in unity itself. but once i try to export i get a lot of errors. I myself havent typed the script that gives error, it was already in unity. Does anyone know what the problem is
alright now what about the bullet
whats SceneTemplate asset
please dont crop, need to see whole inspector / components clearly visible
No clue, i just made a 3d game. added hdrp and 3 scenes. I havent created this code I think its part of the hdrp import
no rigidbody ?
here's proof the collision works
the color changing is activated in the same collision thing as the health
does bullet have a script to move it ?
that would be the object being shot upon reaching 0 health
doesn't destroy itself otherwise, which is why it occurs in the same function
and does that run the coroutine ?
i will check?
the script you showed doesn't destroy the bullet though thats why i asked
the bullet destroys itself on collision with an enemy in its own script
debug log says IEnumerator runs
it is also running so many times
once per hit
five total
object has 5 health
which i might have failed to show that i set in the inspector
oh wait
ur changing the wrong color
the material might be white but your Renderer is still red
no need to worrie about it anymore
script happend to do nothing
deleted it all
game runs perfect
build does too
should be GetComponent<SpriteRenderer>().color = Color.white; instead
you should just cache that component anyway
[SerializeField] SpriteRenderer spriteRenderer
how do I set transform.rotation.y to t
transform.Rotate
it should only spin on Y
are you sure ur pivots are correct?
also make sure ur lerp is correct (though should not affect x,z)
what is wrong?
!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
make sure to configure your editor first, it will show all the underlines red
doesn't seem this is the script with error, or you never saved new changes
I saved
but I dont know where is misstake
the "SerializeField" is no green
and things like "Vector" too
this causes the x to be 180 instead of 90, any ideas
Quaternion rot = new Quaternion(0,0,0,0)
why are you doing Quaternion rot = new Quaternion(0,0,0,0)
quaternions don't have 90
the x/y/z/w components of Quaternion are not euler angles
quaternions are 0-1 values
use Quaternion.Euler to construct a rotation from euler angles
whats "everything" ?
link us to the instructions you followed.
why are my collisions not working? sorry for the sound btw, don't know where it comes from
you aren't using that variable
when you don't use a variable it will result gray
so what I must do?
nothing, if you won't use it at all just delete it, if not just wait till u use it
but it will not cause any errors if you don't use it
but I want to use it
so use it, there's no problem
Hi, I tried (using a tutorial on yt) to make character movement but it isnt working :(
can anyone tell me if theres something wrong here?
this is the unity screen, idk if the problem is code or here
first thing, you havent specified what the actual issue is. But also this code is very bad, maybe find a new tutorial
it just not working ๐ (i press awsd/arrow keys and it does nothing)
ill search a new tutorial then
thanks
:)
moveSpeed is not initialized or I'm trippin?
what debugging steps have you taken? Look specifically at isMoving
you dont need to initialize a bool declared outside a function
uhm... none
probably
moveSpeed is float and he's using it so basically moveSpeed is 0 and he is using it as a multiplier for the speed
well start debugging, but also think about it logically. What code can run based on isMoving? None if its false
How does it get set to true, if the coroutine is running.
no, it is public and thus shows in inspector
moveSpeed is basically always zero, so if he uses it for the speed it will always result zero, he didn't assigne a value to it
ohhhh
I didn't see the inspector lol
sorry my bad hahahaha
just saying, their screenshot also shows its set to 10
Hi I am working on a pick up and drop object script and I wanted to make it so if I fling the camera before dropping it, it throws the object with the force applied to it but I don't really know how to do this properly yet.
I tried it this way:
Vector3 desiredPosition = holdArea.position + holdArea.TransformDirection(objectOffset);
Vector3 moveDirection = (desiredPosition - heldObj.transform.position);
heldObjRB.velocity = moveDirection * pickupForce * Time.fixedDeltaTime;
and objectOffset is defined like this:
objectOffset = holdArea.InverseTransformDirection(pickObj.transform.position - holdArea.position);
and it wasn't the best solution because it just keeps getting close too my face if I run, what could I do to make it stay more in place on the holdArea?
how can I face the creation of different habilities in different characters
Does anyone have an idea why the projectiles are off when shooting at 90 and 280 deg angles? At 0 and 180, the shots are spot on. No clue, because the code is really simple.
Any reasoning why my public variables aren't showing on my scripts. And why they are grey? No errors in the console other than some Syntax errors (I swear I am not ignoring, just ported over the work using UVC to pick back up).
if you have compile errors the variables wont show cause scripts cannot compile
how can I do a follow bullet?
did you try type that in google?
also, how can I do that each character in my game has a different hability although they have common scripts?
is there a really good way to face it?
I thought of using a character ID
and depending of it trying one thing or another
i am setting up multiplayer rn
well, did you read the error
what exactly
I rewrote the line. I went to where it said the error was but there was nothing in that line.
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;
public class ConnectToServer : MonoBehaviourPunCallbacks
{
private void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
SceneManagement.LoadScene("Lobby");
}
}```
is your ide configured?
has to be troll, this happened last time too
(update, changed the code completely, its much much simpler now and it works)
yea like wtf
same tutorial
probably the tutorial has wrong code xD
im using visual studio 2022
honestly this makes no sense
not what i asked
how do i find if it is configured
!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
they all have the movement script, health script, shot script
but how can I make different habilities
i have the visual studio with unity hub
the new brackys 
not what i asked
again
configure your IDE, then you will have your error underlined in red
I click the link and configure it?
well, try it and see lol
alr
what does this have to do with anything? take a moment and think about what you're doing and what a "hability" is
thing of it as an special boost
oh, like an ability?
i am telling you to take a moment and think about it, what is a "special boost" code wise
for example, my idea is that one of the characters shoots a bullet that follows the target, how can I make that possible only if it is one charcater who is using it
do you actually read what @eternal needle is writing to you?
๐คทโโ๏ธ i dont know if we're being trolled or if i need to go to sleep. all of these recent questions make no sense lol
yes bro
ok bro
IDE configuration has nothing do to with this error, as it's unrelated to compilation.
there are many ways to get this error, but an educated guess is that you have your own script called SceneManagement somewhere and the complier is getting confused, that or unity version might be wrong.
try to use a fully qualified name and see if that helps. UnityEngine.SceneManagement.SceneManager.LoadScene("Lobby");
How would I instantiate these objects in a certain range?
I have
public float range = 90;
And here I would like to instantiate that range
GameObject[] gatesTrackEMPTY = GameObject.FindGameObjectsWithTag("gatesTrack");
foreach (GameObject position in gatesTrackEMPTY)
{
Instantiate(gatesTrack, position.transform);
}
@sly wasp Random.InsideUnitSphere * range
I think it's called that
Look up tbe docs for Random
does anyone know the reason my units can travel through this building asset i got from unity asset store? what do i need to add in the inspector?
What exactly does that mean?
then make it whereever you like https://docs.unity3d.com/ScriptReference/Object.Instantiate.html pass in the exact position you want instead of doing it by parenting
Itโs kinda hard to understand without more context, but essentially what you need to do is scale a vector.
Something like this:
// get a vector pointing from this object, to the object in question
var directionOfSpawnPoint = (position.transform.position - this.transform.postion).normalized
// scale the vector to be the correct โlength / rangeโ
var pointWithinRage = directionOfSpawnPoint * range;
// get the final position by starting at โthisโ then walk to the spawn point
var spawnPosition = this.transform.postion + pointWithinRage;
Instantiate(gatesTrack, spawnPosition);
I hope that makes sense ๐
How are your units moving?
You most likely need to add a collider to the building
they're going straight through it like it's nothing
But how are you moving them
The unit should have a rigidbody and a collider, and the building needs a collider too
If you are using rigidbodies, that is
Or is it just navmesh agent?
I have different prefabs that instantiate the track object in any empty game object with a certain tag, I need it in a length because I know how long the prefab is, if I just instantiate it will do it on previous prefabs
I actually mean a length not a range
Yep make sure the building has a collider and bake the navmesh again. Assuming that the navmesh surface is using colliders, not renderers
Are you trying to spawn these objects like in a row, next to each other?
Oh track objects, so like pieces of road?
Tracks werenโt a very good example
Let me describe it differently
Make a Vector3 before the foreach loop and add an offset to that vector every time you spawn one
Ok letโs think of it like this
I have different โchunksโ that are spawned, they are prefabs that contain empty game objects with certain tags for different obstacles
So I was using the code at the bottom to instantiate them. It worked, only problem is that it generates in previous โchunksโ too, so I need it to only generate them in a specific length
worked thnx
I'm trying to port the following HLSL code to C#
void Hash_Tchou_2_2_uint(uint2 v, out uint2 o)
{
// ~8 alu (2 mul)
v.y ^= 1103515245U;
v.x += v.y;
v.x *= v.y;
v.x ^= v.x >> 5u;
v.x *= 0x27d4eb2du;
v.y ^= (v.x << 3u);
o = v;
}
for this line v.x ^= v.x >> 5u;, I'm getting the following error:
I think Unity.Mathematics has a method for this but I don't know what this operator is
Didn't we literally solve this exact error on basically an identical script yesterday? Where did you find this? Is there a tutorial that has SceneManagement on it?
v.x >> 5 should be fine there
uint >> int
I'm wondering if there's a difference when converting that int to a uint
Ideally I'd like the code the behave the sameโasking just in case
v.y ^= (v.x << 3u); also had that error
uint is just unsigned, you can use larger numbers with it but not negative. doesnt matter in this case
!collab
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
๐ 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.
also you arent converting the number to int, it is just the shift count
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#shift-count-of-the-shift-operators
purpose: click on icon in the UI and should produce unit (ignore icons being same im too lazy to fetch 3 other icons)
problem: when i first select the building, the highlight doesn't appear, and each button produces the same unit (this is what it shouldn't do). when i deselect and reselect, the highlight appears and each button produces a different unit (this is what it should do).
my question is, why is the first part occuring?
just finished the junior programmer thing on unity learn ๐
thanks for the resources, I'll definitely check them out ๐
i shouldve quoted but the only part of it that really mattered was
For the built-in shift operators <<, >>, and >>>, the type of the right-hand operand must be int or a type that has a predefined implicit numeric conversion to int.
so, you're supposed to be able to click on the building and highlight it then a unit from the bottom, which i assume spawns different types of units, correct?
yep the bottom is the UI, each button represents a different unit, and should produce that unit, problem is this spawns the same unit when i select on the building first
and its only when you highlight the building first?
when i select building second time, green circle appears like this #๐ปโcode-beginner message
and everything works fine
ye
there's no green circle when i select first
can i see some code?
Trying out events/listeners like is outlined here and hitting a confusing hurdle. https://gamedevbeginner.com/events-and-delegates-in-unity/
Basically hitting a UI button should trigger an event that the dice objects are listening for, and they then call their DiceRoll.RollDie public method. This all worked fine before using events, but for whatever reason the various public functions don't populate as options here. No idea why. Any suggestions?
Ex of what I'm expecting to see:
i think this error is quite tricky idk if u cant solve it's fine ill work my way round it
huh
ok it works when linking the gameobject to the script attachment, but how would that even work for like dynamically created objects during runtime
the code looks airtight to me, if i had to guess, you would have to do some digging in your hierarchy to see if you have anything significantly different from your first building or something
like the menu itself or how you would go about making the menu load certain scenes?
You can't assign persistent events using dynamic objects. You have to use AddListener in code
is IsInteracting triggered by a mouse click on the building?
I had a question. So I am making a top down 2D game. For my movement script, I am just setting the velocity, rather than using AddForce. I did some research and I found that it varies from game to game and what you want (whether you want a more realistic movement system or a more arcade snappy feel). I do want the latter, but when adding in features such as knockback should I maintain consistency and set the velocity for a duration or would it be fine to use both AddForce/velocity setting.
yeah
depends on how u have it.. but most likely ur velocity is gonna override ur addforce.. u can add and subtracted the forces from the vector ur using for ur velocity.. before you pass it into the function
what does the script that spawns units look like?
//set ur up forces from ur inputs..
//add or subtract any knockback or dash forces
//pass in the final result as ur velocity
can't you use .AddForce anyways even if everything else uses velocity?
yea if they're different objects.. u start mixing them on teh same object is when u run into issues
do you think its spawning the same unit because its just spawning whatever's first in the spawn order?
Could get around it with statemachines or timers/coroutines
Disable velocity when doing addforce
i clciked on every button and it spawns the same unit, only when i select the building first time and no highlight appears
got any ideas why the highlight doesnt appear first time round tho?
no clue honestly
probably bc u set a bool and then read from it immediately
probably, this is the whole script for it
idk how your troop selection system works but the spawner you showed me just spawns the first troop in the array from what i saw
its supposed to change the highlight once i interact with building
ye it's like that
that's exactly what I'm trying to do, though. listener script attached to each instance of the object sets up the listener
nah that doesnt seem to be the case there
b/c u call the Highlight function on interact
That looks like a compiler error. !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
yeah, i can show you more info it might solve idk tho
the building and player units both use that interactable script i showed u, when i select the units first time round they are selected just fine
Note that listeners added by AddListener will not appear in the inspector.
why my ''on click'' appears like this??
Presumably your inspector is set to Debug mode
thaaaankssss!
I wasn't getting any errors, though, just couldn't figure out how to link the scripts and objects together properly
well it's ok now, thanks
i see i see. would you recommend that i switch off velocity setting and use addforce then? is there a way i can get that same snappy feely as velocity setting while using addforce?
Since it's a networking issue, try in #archived-networking
Generally people get worried seeing someone in code BEGINNER asking about multiplayer
Same difference. Belongs in #archived-networking
{
if (other.gameObject.tag == "Checkpoint")
{
Debug.Log("Checkpoint");
lastCheckpoint = other.transform.position;
}
}```
So this code should be debugging when the player (what this script is on) touches an object with the tag Checkpoint. I have checked that the tag is spelled right, and that the object with the tag has an ontrigger collider, but nothing. Any idea why?
Add a debug log outside the if statement and see if there is a collision at all(and with what)
When i put a debug above the if statement it also doesnt fire
Then your collision doesn't work. Does one of the objects have an rb?
No. It's required for a collision.
Take a screenshot of both of the object's inspectors.
You're dealing with 2d physics, so the callback also needs to be 2d:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
for the following code I'm getting an error that a uint cannot be multiplied with a float
o = (r >> 8) * (1.0f / (float)(0x00ffffff));
if I cast the float to a uint, it gets rid of the error, but that messes up the output
What are you even trying to do?
the original hlsl code looks like this:
o = (r >> 8) * (1.0 / float(0x00ffffff));
convert an hlsl function to c#
it's Unity's built-in voronoi shader code
What does that particular line do? It might be simpler to rewrite it from the meaning rather than convert directly.
I don't know what it does to be honest
but I've successfully ported over several hlsl functions by simply fixing the syntax
cast the uint to a float?
o = ((float)(r >> 8)) * (1.0f / (float)(0x00FFFFFF));
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
!ide
Seems unconfigured
At least the formatting is awful
Makes it really tough to parse
Im completely new, followed a tutorial. I havent ran into IDE yet, ill look into that. thank you
uints can't be converted to floats unfortunately
An IDE is the thing you write code in
Looks like vs code in your case?
oh yes, VScode
script for player turn
You'll need to figure out what it does, because there might be hlsl code that is not directly convertible to C#.
I'm so sorry, it was a uint2 this whole time! Casting to a float2 seems to get rid of the error
@summer stump thank you!
!cs
this might be the place to be, unless there is a unity related question coming up
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
i know how to do ui
A bit embarrassed but how can I simplify the below? I know I must not be doing this right
I had a lot of redundant code written below:
{
standing = true;
movingNeutral = false;
movingLeft = false;
movingRight = false;
movingDown = false;
movingUp = false;
movingDrag = false;
standing = false;
standingDrag = false;
hoppingStraightUp = false;
hoppingUpSide = false; }
if (standingDrag)
{
standingDrag = true;
movingNeutral = false;
movingLeft = false;
movingRight = false;
movingDown = false;
movingUp = false;
movingDrag = false;
standing = false;
hoppingStraightUp = false;
hoppingUpSide = false;
}
that I wanted to replace with using the function below:
{
var current = currentMovementState;
movingNeutral = false;
movingLeft = false;
movingRight = false;
movingDown = false;
movingUp = false;
movingDrag = false;
standing = false;
standingDrag = false;
hoppingStraightUp = false;
hoppingUpSide = false;
current = true;
currentMovementState = current;
}
```
So I can do this:
if (standing)
{
DisableAllMovementStatesExcept(standing);
}
if (standingDrag)
{
DisableAllMovementStatesExcept(standingDrag);
}
if (hoppingStraightUp)
{
DisableAllMovementStatesExcept(hoppingStraightUp);
}
if (hoppingUpSide)
{
DisableAllMovementStatesExcept(hoppingUpSide);
}```
a bitmask is the first thing that pops in to my mind. but that might be a bit confusing if your not familiar with bit logic
you should break stuff into states more
rather, you're depending on flags more than the state that they are in
just gotta make the script
but it looks like you only ever want one of them to be true / active at any given time? then a simple enum should fix everything
if (standingDrag)
{
standingDrag = true;
movingNeutral = false;
movingLeft = false;
movingRight = false;
movingDown = false;
movingUp = false;
movingDrag = false;
standing = false;
hoppingStraightUp = false;
hoppingUpSide = false;
}
In this example, when you go into an idle state such there has been no input, you shouldn't care if you're moving in a direction nor need to read any input for it knowing that state.
And, for a moving state, instead of having 4 different direction flags, consider an enum for the direction
I'd recommend formulating the entire problem / question all at once. it's hard to parse what your asking if you don't do that, so your not going to get good answers.
ok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Caculate : MonoBehaviour
{
public TextMeshProUGUI Result;
public TextMeshProUGUI Input1;
public TextMeshProUGUI Input2;
public TextMeshProUGUI DropDown;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
when i try to add a input field in unity it wont let me
and a dropdown to
nvm
That makes sense but for this game, the player is sort of drifting in space by swiping him around. So after a while of floating to the right when velocity slows down, he goes into the idle movement state. Its not really input driven
This makes a lot of sense. And sorry but I meant to ask why does my function to simplify it not work though. Something must be wrong with it
well.. if you break down the function you posted. let's just remove the setting of all variables to false for readabiliy.
the logic you have is this:
public void DisableAllMovementStatesExcept(bool currentMovementState) {
// set the local variable 'current' to be equal to currentMovementState)
var current = currentMovementState;
// ignore the last line and set it to 'true'
current = true;
//now set the local parameter 'currentMovementState' equal to true.
currentMovementState = current;
}```
so, I'm not sure what you wanted it to do, but rn, it's not really doing anything. except set all of these to false:
movingNeutral = false;
movingLeft = false;
movingRight = false;
movingDown = false;
movingUp = false;
movingDrag = false;
standing = false;
standingDrag = false;
hoppingStraightUp = false;
hoppingUpSide = false;```
How could you tell its unconfigured just by looking at it?
and where you call DisableAllMovementStatesExcept(standingDrag); c# has no concept of the variable standingDrag like it does not understand that that's the same variable inside DisableAllMovementStatesExcept, since standingDrag is a value type, not a reference type. you're just telling it the current value (true or false) of standingDrag
https://medium.com/@dev.msalah/value-vs-reference-types-in-c-573e3cf6c5bf
this might clarify the issue.
In this article, we will explore the different categories of C# data types. We will take an in-depth look into the distinctions betweenโฆ
The colors, and everything was shifted left and right from where it should be
Thanks! I'm going to try to configure it later tonight. I appreciate the input
and you could force c# to work the way you expect here by using the ref keyword
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
No problem! Good luck!
Thanks! I didn't realize making a tic tac toe game was going to be such a challenge LOL
@summer stump I've asked chatgpt for help and while it's helpful, I'm still lost on how to write "check for winner" script. I've watched some tutorials as well but still lost at where to start. Might ya have an area where I could start?
My tic tac toe game works and the restart button works (I got way too excited when the button worked) but I want the game to be able to keep score
hey, having a small conceptual issue with physics. im using a basic rigidbody capsule 3d for my character with a capsule collider and some basic box colliders as platforms.
when moving along a flat platform, works perfect as intended. when moving along an inclining or declining platform, our speed collides against the object and creates some y velocity which then pops our character up. does rigidbody just do this naturally? and are there some settings i can use to turn this off?
Ah~! Thank you. I knew it was most likely me just making copies of variables and changing them lol
I think I will use an enum going forward for this instead of flags
thanks so much. it works as expected when actually passing around the reference
im tryin to set the status in my game
but it wont come up when i start the game
public class BattleHud : MonoBehaviour
{
[SerializeField] TextMeshProUGUI nameText;
[SerializeField] TextMeshProUGUI LevelText;
[SerializeField] TextMeshProUGUI statusText;
[SerializeField] HPBar hpBar;
[SerializeField] Color psnColor;
[SerializeField] Color brnColor;
[SerializeField] Color slpColor;
[SerializeField] Color parColor;
Pokemon _pokemon;
Dictionary<ConditionID, Color> statusColors;
public void SetData(Pokemon pokemon)
{
_pokemon = pokemon;
nameText.text = pokemon.Base.name;
LevelText.text = "Lv " + pokemon.Level;
hpBar.SetHP((float)pokemon.HP / pokemon.MaxHp);
statusColors = new Dictionary<ConditionID, Color>()
{
{ConditionID.psn, psnColor},
{ConditionID.brn, brnColor},
{ConditionID.slp, slpColor},
{ConditionID.par, parColor},
};
SetStatusText();
_pokemon.OnStatusChanged += SetStatusText; //SetStatusText will be called when status is changed
}
void SetStatusText()
{
if (_pokemon.Status == null)
{
statusText.text = "";
}
else
{
statusText.text = _pokemon.Status.Id.ToString().ToUpper();
statusText.color = statusColors[_pokemon.Status.Id];
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConditionsDB : MonoBehaviour
{
public static void Initialisation()
{
foreach (var kvp in Conditions) //kvp(key,value,player)
{
var conditionId = kvp.Key;
var condition = kvp.Value;
condition.Id = conditionId;
}
}
public static Dictionary<ConditionID, Condition> Conditions { get; set; } = new Dictionary<ConditionID, Condition>()
{
// All condition's logic
public enum ConditionID
{
none, psn, brn, slp, par
}
Anyone?
where the debug log at
where you call it?
enum with flags
[Flags]
public enum States
{
A = 1,
B = 1 << 1,
C = 1 << 2
}
To set the flag you can just do this : muEnum |= States.A; then later on check for the flags
also, thats alot of bools you got there ๐
the last 2 lines
โ๏ธ
but do you is the question
first instinct is to log stuff not working and just make sure it's being set and you've nothing setting it incorrectly.
because you want to first make sure it's not your logic that's wrong, but a problem with unity
nope
no suggestions
what does it mean?
some of the other functions haev it as well
My guess is it's suggesting some naming convention, otherwise maybe the null-check operator is unnecessary
๐
is this the right place to ask for insight on a UI/scripting problem I'm stuck on?
and if not can someone direct me to the right channel?
I'm looking for someone who understands the UI elements better than I do (specifically the coordinates systems)
right, but some servers will ban you for posting in the wrong channel
without details can't even suggest channel
Fair enough.
I have a GameObject that is in a GridLayoutGroup. I want to, when you hover over its container object, to create a duplicate of that object on a separate canvas(so that I can move it's position despite the GridLayoutGroup). I'm using Vector3.Lerp to move it's position every frame. The problem I have is that it's not actually moving.
this is on a script attached to the container obj
the log is running ? btw if you're getting RectTransform might want to move AnchorPos