{
transform.rotation = Quaternion.LookRotation(transform.position - CameraControl.hitDist);```
this script makes my object face the direction I want it to face but
```void FixedUpdate()
{
cj.targetRotation = Quaternion.LookRotation(transform.position - CameraControl.hitDist);```
doesn't. cj is a configurablejoint and angular drive is 10000. anyone know why?
#💻┃code-beginner
1 messages · Page 27 of 1
sorry where am i using that?
where you intend to start the Mark coroutine
Guys I just upgraded my TextMeshPro to version 3.2.0-pre.6 but I got this error Library\PackageCache\com.unity.textmeshpro@3.2.0-pre.6\Scripts\Editor\TMPro_CreateObjectMenu.cs(339,31): error CS0117: 'Object' does not contain a definition for 'FindFirstObjectByType'. And when I checked inside the script that line and many other lines is white color. Definitely there's something wrong here but I just have no clue.
which Unity version are you using?
I'm using Unity 2020.3.38f1
Hmm, docs say it should be there
What should be there?
FindFirstObjectByType
Yea but that's the issue. Starting from Object is not there. Also GameObjectUtility. Basically I was just upgrade and import TMP essentials. Then I got that weird error
Help
Don't crosspost. No one would be able to help you if you don't provide details.
can someone help me understand wwhy this sends my camera to the moon
Hey im looking for some help, im using Mirror and SteamWorks so i can play with some friends once me and my boy are done with the game. I just got done setting up the Player Model and animating it.
for some reason the transform.position.y in the inspector is constanly changing values same happens with the rotation.y which makes my camera turn by itself.
Also whenever im standing the characterController.isGrounded is constantly returning false for some reason which makes my player go into a part of the jump animation, and when i jump characterController.isGrounded is true and goes back to false...
Code:
https://pastie.io/hncegw.cs
Any help is appreciated
you are adding 5 to the Y of position every loop
Options.SetResolution (System.Int32 resolutionIndex) (at Assets/2D/Scripts/Options.cs:51)``` what does this mean
oh its a loop?#
what did you think LateUpdate was?
idek
Try reading some docs then
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class Options : MonoBehaviour
{
/// <summary>
/// - Manages the options menu
[SerializeField] private AudioMixer audioMixer;
[SerializeField] private TMPro.TMP_Dropdown resolutionDropdown;
Resolution[] resolutions;
// Resolution Options
void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionsIndex = 0;
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionsIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionsIndex;
resolutionDropdown.RefreshShownValue();
}
public void SetVolume(float volume)
{
audioMixer.SetFloat("Volume", volume);
}
public void SetResolution(int resolutionIndex)
{
if (resolutions != null)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
}
}
public void Quit()
{
Application.Quit();
}
}
well why is my resolution list null
Not sure why you delete your answer but not problem. Okay so I've tried to regenerate the project files. I also even rebuild the solution lol(I have no idea why am I doing this). But still no luck 😢 . Re import also didn't help
Odd, I didn't delete my answer. Can you screenshot your complete VS window
my visual studio window?
yes
Anyone can help me look into this it's the only thing im lacking in regards to the player movement :/
like this?
your IDE is not configured
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Oh that's weird. I've been using it for a year since the last update. Will check it asap and be back soon
And you never noticed? ;-;
This is the giveaway. It should read Assembly-CSharp
I never know the difference in my IDE till he mentioned it 🤣🤣🤣 that's a new important tiny thing for me! Thank you @languid spire !
what is the easiest way to generate/make getters for all my private variables?
[SerializeField] private ItemTypeSO itemType;
I got a whole bunch of these and want to be able to only read the value from other scripts
I'm using Visual Studio
I've been looking at properties vs fields a bit, but don't really understand when I should use each
Is this how I create a property that is read-only?
[SerializeField] public Sprite Sprite { get; }
Is there any reason I shouldn't be doing this?
You can't serialize properties.
You can serialize their backing fields if they have a setter, but it's generally best to do it separately.
Choosing one over the other... Use a field when you're serializing something. Generally that's private. Then use a property where required to control access from the outside and to add validation.
Though, properties are slightly slower than fields, so sometimes people avoid them in high performance situations. There are caveats
when/why would I want to serialize something?
So you can set it in the inspector
Also when you want the data set in inspector not to be discarded
so I need to do it like this?
public Sprite Sprite { get => sprite; }```
how would it be discarded?
Well, when selecting another object to be inspected, or entering play mode for example
That is one way, yes. The C# standards have private variables prefixed with an underscore, but that is preference
It is never a good idea to have variable names the same as class names
so I should use something like itemSprite instead?
yes
public Sprite Sprite { get => _itemSprite; }```
ew need to change the property name too
no it was the variable Sprite you should not use sprite is fine
Hey, somehow my Player cant really move, the CapsuleCast doesnt really seem to work, either for the radius I guess, but it should be right. Can you help me?
{
//Collision detection
float moveDistance = movementSpeed * Time.deltaTime;
float playerRadius = .5f;
float playerHeight = 1.5f;
bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, moveDir, moveDistance);`
**More code```
ah so my code is good like this?
no
[SerializeField] private Sprite sprite;
public Sprite ItemSprite { get => sprite; }
"doesnt really seem to work" is not really enough info
what is happening or not happening? any errors? what is supposed to happen?
No errors, the player supposed to have a hitbox, but instead, it gets move blocked from the air
But the height and the radius should be right
whats up with the ItemSprite { get => sprite; } does it do anything different than just ItemSprite => sprite;
They are the same
aa ok
void Start()
{
backendActive = true;
StartCoroutine(TickUpdater());
}
IEnumerator TickUpdater()
{
while (backendActive)
{
if (active)
{
TickPing.Invoke();
yield return new WaitForSeconds(1 / TickSpeed);
}
}
}
trying to make a tick event, I'm subscribed to it in another script but it doesn't seem to work. anyone know why? backendActive is only there to avoid a while(true) loop
If backendActive is true and active is false you have an infinite loop
Also, waitforseconds will wait and then occur on the next available frame, so this is an inaccurate way to make a tick
Look at the pinned messages, as directed
ok thx
yeah but i like uh
want someone to teach me
reading isnt my profesion
no?
Then pay a tutor or take a course
i have no money!
@languid spire So I've read the IDE Configuration and checked if it was configured. I checked both via UnityHub and manually. And turns out I actually already did that. I even updated the packages. But still no luck.
I'm gonna report this as a bug I assume?
No. Does the IDE look configured when you look at your own code (not text mesh pro's code)?
Also not in your screenshots is the external tools setting in Unity's editor preferences
hey i actaully like this https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
Yeah I guess. I saw my assembly there. While the TMP one is Miscellaneous Files
Then it's configured
This right?
Yup
BRO
Yea. Then it's a bug
c# is 10X easier then i thought
What is a bug? It's configured
can you open the solution explorer and screenshot that
I meant this error haunt me for hours. If it's configured then it should not like this
Your Unity version musn't be compatible with that version of the package
There are tons of them. Which one do you want?
Some name is confidential
why does this just keep loading
string myFriend = "GreenX";
myFriend = "Ezra";
Console.WriteLine(myFriend);
just wanted to see which projects are in your solution
Ohh it could be that. I'm gonna find out what version of Unity compatible with TMP 3.2.0-pre.6
the accuracy isn't all that important in this project, I just need a custom update loop because I don't want to loop through a list of 7000 elements too much
it is ok, I checked for you
You meant this?
yep, TMP is not there
Damn right, must be the version problem
I can't find the articles about unity version compatibility here https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2/manual/index.html
but
https://forum.unity.com/threads/3-2-0-pre-4-release-now-available.1376289/ I assume it needs higher unity version in pre 6. So yeah unity version need to be upgraded
why does this websites code tab so slow https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/hello-world?tutorial-step=3
Case closed. Thank you guys! You're awesome
just keeps loading
BRO
its still loading
why
@north kiln
my thing wont load
DDEWvugjergejr
can someone just help me 😭\
bro
@fickle plume
can you help me?
@sacred cradle Don't ping people into your questions. And don't ping moderators with non moderation issues.
Read #📖┃code-of-conduct
oke
read #854851968446365696 and think before you ask something
how do you expect anyone to help you with the information you have provided us?
ok ok sorry its just late at night and idk what im doin
ig ill just figure it out by myself god damnit 😦
Well, this isn't even Unity-related at this point
im tryna learn the thing but its not loading
Well, that's Microsoft or your wifi, we can't help
, _ ,
Hello I am having an issue with changing the transform position of a gameobject. we are supplying a direction for the gameobject to move in, and for how many steps (think sort of like chess). The for statement in the "Move" function is being called, but the game object is not being moved. if anyone could help that would be great! thank you!
p.s the code is a hellscape cause this is for a uni game jam and we are in crunch mode rn: https://pastebin.com/ZFDRMWJe
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I am getting no errors in Unity, or my IDE. Sorry, I should have stated before
Oh sorry that was for me, not you. Lol
oh gahaha my bad
Trying to determine if there have been any new options for IDE since VSCode had been fully dropped at this point
is there a way to calculate the velocity from a collision or would it be too difficult since it looks likes the velocity keeps decreasing over time
start by logging the values passed into Move
It's the opposite. VS Code has just started properly being supported again.
wait nvm
Wait for real? I thought they had just "fully dropped support" recently. I know the debugger extension had been dumped like a year ago, I didn't hear anything about fixing support
Yes. They moved to the C# Dev Kit https://unity.huh.how/ide-configuration/visual-studio-code-configuration
Thank you, I'll take a look through this
The values that I am passing through are accurate to what I expect. (e.g direction(-1.00, 0.00) time: 3)
what about gridSize. Check the inspector not the code
The grid size value is what I expected (since the grid we are moving on has a scale of 0.9, it is set to 0.9). We have tried increasing this value but it has no effect
Okay so I'm not a Unity beginner but I am a VR Beginner, I'm starting a VR project and I was wondering if Unity or Unreal is the better engine. The specifics of my project is for it to run efficiently and reliably on low-end devices with a lot of content, multiplayer (on my own server), and an entire storyline. No biased answers, please.
screenshot the inspector that this script is attached to
Of course please bear with
Here you go, I also included the console because despite me printing the values of the directionhalf, and timehalf arrays, they don't update in inspector (confusing since in console the output correctly)
Are you sure you are calling the script on the correct object?
post code where you call it
{
private ParticleSystem particle;
void Start()
{
particle = this.gameObject.GetComponent<ParticleSystem>();
particle.Emit(1);
}
void Update()
{
if (!particle.isPlaying)
{
Destroy(this.gameObject);
}
}
}```
hey, I made this script to put on a prefab that instantiates at the position that a raycast makes contact with something. problem is, the animation doesn't play. also is there a more efficient way to do this?
low end devices with lots of content makes this unity or nothing situation imo, ue5 pros over unity is from its monster graphics you wont use, development will be slower as well, u should research such important question on ur own noone can give straight answer tbh
also higher floor overheads and u need that fps for vr
I am calling the Move() function from the InterpretMorse() function which is called from an external script called InputMachine. Here is the where I am calling it:
if ( pI > 3 ) {
playerController.InterpretMorse(ControllerArray);
pI =
if (pI == 3) {
...
}
MorseReset();
}```
the `ControllerArray` variable is an array that is updated with values that change depending on which type of morse code symbol they type.
Tbh, I think the only things Unreal have over Unity is that Unreal has Nanite and Lumen; also the fact that Unreal allows you to create AAA games as an indie developer in no-time, but I will say it def makes games look more bland. I think I will go with Unity but the only reason I am considering Unreal because of the recent trust breach and the fact that a massive amount of Unity developers are switching to unreal.
the controllerArray is parsed into the InterpretMorse() function in the other file (that has the broken code) and is being split into two 2-digit arrays, the direction, and time arrays which are then parsed into the Move() function
here is the InputMachine code if you need it: https://pastebin.com/dnWvL2VF
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How does it allow you to make AAA games? Does it create a multimillion company for you and promotes your title to worldwide renown?🤔
And the playerController variable is set to the PlayerAgentController component from PlayerAgent gameobject in the inspector?
indeed
AAA Quality games. With Nanite and Lumen it's just the Asset Store + Nanite & Lumen, also the FPS template and easy-to-use multiplayer functionality, it's not very difficult.
I'm not saying you can create a AAA game in Unreal as an indie dev, was more using that as an expression or whatever. Just saying that it's much easier to implement quality un Unreal.
I see you also have a PlayerAgent prefab, are you sure you used the GameObject from the scene not the prefab?
yes
AH!
Fixed it!
Thank you so much Steve
I plan on programming my own server functionality but I want to use a third-party server as well. Are there any 3rd party servers that can give me manual server-client-server responses that allow you to program implementation manually? Or do they all have custom libraries?
Humour me. Debug.Log GetInstanceId() in your PlayerAgentController script
I fixed it man
it somehow decided to work when I changed transform.position += new Vector3(...); to transform.position = new Vector3(...);
can anyone help me with a script? i want to child an object to a child of the collided object on trigger
Odd, that should make no difference
it somehow fixed it? it boggles me too
Let’s say I wanted to access different weapon objects on the ship. Would it be better practice to give each one its own serialized field (more fields) or to have an array of them (less descriptive naming when accessing them since indexing)
you can have both. Use an Array and an Enum for the indexer
okay
Or a Dictionary
ohhh snap!
What did I do?
we went from an array + enum to a dictionary. what will we see next?
the options are endless . . .
[2D] yo, i implemented a jump mechanic that uses a raycast for a ground-check. Now im watching a guide on wall-jumps and they use empty transforms positioned right (or left) of the player. Obviously this works but i'm trying to understand why use this approach and not a horizontal raycast? Can i use this method for ground jumps too? is one better than the other?
You can do it many ways, but the empty transform way gives some better debugging visuals probably
Empty transforms? Or two colliders on each side?
oh yeah they probably have colliders^
Cause a empty transform wont do jack
yeah, they probably have colliders on them . . .
uh they have a field of type Transform and they place a new Empty to the right side. They do have colliders yeah mb for poor word choice
Well if anything a box collider is a bit heavier collision calc than a raycast
Maybe they want some thickness due to gameplay reasons, but then there is box cast
it depends on the amount of coverage you want/need for your game. a collider will be a larger volume/area of space to check (when jumping) hitting a wall, as a raycast is a single ray shot in one direction. you can shoot multiple rays in an arc to search a greater range for a wall as well . . .
yeah it seems weird not to just use a raycast to e
I wouldn’t call it weird. It all depends on what you want
all i need is "am i touching a wall" (so not a ledge smaller than the player)
Does using the collider have a clear benefit over the raycast
coverage
but then i can just increase the ray size no?
It does not and for your ledge case a raycast might be better. I would even do 3 raycasts and make sure all of them are hitting the same object, that way you can calc the step hight too
nope, a ray is basically a single line in space with a distance . . .
Rays are rays they dont have a size. A thick raycast is a sphere cast or a box cast
mm right
Well they dont have thickness they have a length
Does this look ok/good?
{
List<Item> itemList = character.Equipment.GetEquippedItems();
foreach (Item item in itemList)
{
characterArmor += item.BonusArmor;
characterMinDamage += item.BonusMinDamage;
characterMaxDamage += item.BonusMaxDamage;
}
}```
It's kind of a trip to go from CombatScript -> Character -> Equipment -> Item to get the bonus stats
ye
this looks fine, but it really depends when and how often this is called. you could update your stats when any item is equipped on the character. this seems like it'd be done after an equip session is complete . . .
yeah not gonna call it every frame 😛
i'd invoke an event after an item is equipped to update the stats . . .
I'll look into that
currently working with pre-equipped items, there's no actual item-equipping yet 😦
then you actually only need to run this once, when loading, just figure out every state change you may have on those items and only then execute it
spoiler alert if u plan on having debuffs on those stats and unequipping at any point it will be hard asf to handle all the cases without just recalculating each frame
or that was skill issue on my end idk
there should be hundreds of tutorials on it on YT
nahg
its undertale like
and collision is kinda weird idk why am i make it weird
and i have issue at making player can slide when walking toward wall
i fixing it rn
Top down pov?
this is one perk of having automatic garbage collection
ah, you're doing the movement for the combat segments
So the problem is that you can't slide when moving diagonally against a wall?
yes
How are you doing movement? You can show us your !code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
how to show
see the bot message
its to much character in the code
you'll want to use one of the pastebin sites.
I like https://gdl.space
paste your code in, click the save button, and copy the link
like this?
i have not much time left
i going to sleep
and also this script https://gdl.space/muyonowuco.cpp
That looks like a reasonable approach. But when does CollisionDetector.isOutsideBox update?
I think you need to check if you're outside the box after each attempted movement
It sounds like you're only checking once per frame
How does it work?
ah, so it's using a trigger collider
I would suggest using a Bounds instead.
You can ask if a point is inside of a Bounds.
Hey, does someone know how could I do that kind of animation to the icon of my game in unity?
So you can just check if the player's position is inside a rectangle
how?
actually, Rect would be more appropriate for 2D
im new
I would put down two empty objects at the top left and bottom right corners of your play area.
Is the problem like the player cannot go right next to the wall because of collision boxes?
dm me the answer i dont want the answer to gone and i need to scroll up when wake up
im going to sleep
public Transform topLeft;
public Transform bottomRight;
Rect bounds;
void Awake() {
float width = bottomRight.x - topLeft.x;
float height = bottomRight.y - topLeft.y;
bounds = new Rect(topLeft.x, topLeft.y, width, height);
}
void Update() {
if (bounds.Contains(Vector2.zero)) {
Debug.Log("[0,0] is inside the rectangle");
}
}
Here is an example.
Dude just save as notes
oh
I don't want to DM people. You can just search for this mention tomorrow @formal bolt
how?!?!?!
Also don’t demand things from other people when they are the ones helping you
This will let you check if the player is in bounds whenever you want.
ok.
That way, you can check if your horizontal move was okay, then check if your vertical move was okay
Another option would be to just use Bounds
bye bye
ima sleep
this can just snap you back in bounds
Then sleep
Hey, does someone know how could I do that kind of animation to the icon of my game in unity?
https://hatebin.com/lszsdtmkfo
I have this rotator on my player. Whenever I enter trigger that is either called rotator 1 or 2, player turns that way. But the thing is. When I fall off the platforms. The character just rotates without entering trigger. Can someone point why this happens?
I can post a video if needed.
Could you post a video
Of course.
how does your player move? this could just be because you're using a rigidbody that has unlocked rotation
i see a rigidbody is involved
Yes with rigidbody
Yeah that was what I was going to say
And lock it afterwards
The part where I fall down the platforms.
no not really
Make sure you aren't just hitting a trigger you forgot about
I'm positive there is no trigger in there
In the method where it creates the game to end (like death screen or the what causes the end screen to pop up) just set the player velocity to 0
Using updates
Okay, but have you proven it?
Log every time you enter a trigger.
I'm positive about a lot of things until I'm not (:
Casaken there has to be some sort of trigger because how would you trigger the death screen?
oh, look at this
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("RotatorLeft")&& canRotate)
{
diff = Quaternion.Euler(0, -90, 0);
canRotate = false;
StartCoroutine(EnableRotationAfterDelay(.4f));
}
if (other.CompareTag("RotatorRight")&& canRotate)
{
diff = Quaternion.Euler(0, 90, 0);
canRotate = false;
StartCoroutine(EnableRotationAfterDelay(.4f));
}
_rb.rotation *= diff;
_rb.velocity = diff * _rb.velocity;
}
this unconditionally causes you to rotate every time you enter a trigger
Oh actually
it doesn't matter if the trigger doesn't have the appropriate tag
you're right the base ground
You should return early if you didn't hit a valid trigger
hmm
Yes so recheck the method of the base ground
So the base ground which is a fail condition trigger. Causes me to rotate cos im triggering rotator regardless of its name
Right.
Can you tell me how it does that unconditionally? I have the rotator names in the if parameter?
How can i access a variable from another script in a prefab script
You could either redefine the methods used to rotate so they are specific to axis or you could make it so when it hits the death trigger it will set rb.velocity = new Vector2(0,0)
Vector 3*
Read your code from top to bottom.
And make the methods that move the player disabled
ahh these?
Hmm all right
- If you hit "RotatorLeft" and you can rotate, set
diffand disallow rotation - If you hit "RotatorRight" and you can rotate, set
diffand disallow rotation - Rotate the player
The third point is not conditional.
You should bail out immediately if the tags aren't right.
maybe
Either bail out or set a bool for "If dead" or the like
if (left) { ... }
else if (right) { ... }
else { return; }
_rb.rotation *= diff;
_rb.velocity = diff * _rb.velocity;
I would call this an early return
returning early can be useful for a method that does a series of checks and, if they all succeed, runs some more code
you just return if the condition is not met.
all right
Doesnt he want to update velocity even if either left/right is conditional?
To that method add another condition like a bool like “Dead” and if true disallow the movement code
If its false you allow it
This would just mask the problem.
Any other trigger would be able to cause the bug.
You should fix the root cause (touching any trigger makes you change direction), not the symptom (touching the death trigger makes you change direction)
I told him to either fix it entirely or just do something like that
Put a bool for the _rb.rotation inside the left/right check?
how can u make a prefab access another variable without it being on the screen
i cant reference
Np
Prefabs cannot reference scene objects, if that's what you're trying to do.
I've got a slider which isn't interactable, I've already researched about it on the internet, but none of the fixes I found worked
Whoever spawns the prefab should assign the reference.
i make a raycast going right or left, depending where im facing, for a wallcheck.
void OnJump()
{
if (IsNearWall() //???
{
}
if (IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
else if (canDoubleJump)
{
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed * doubleJumpMult);
canDoubleJump = false;
}
}
private RaycastHit2D IsNearWall() // Other return type maybe?
{
Vector2 facingDirection;
if (transform.localScale.x < 0) facingDirection = Vector2.left;
else facingDirection = Vector2.right;
RaycastHit2D hit = Physics2D.Raycast(hitbox.bounds.center, facingDirection, 0.1f);
return hit;
}
What's the better approach here?
- Should
IsNearWall()return the direction of the hit wall to its callerOnJump()OR - Should
OnJump()do the direction check and tellisNearWall()which direction to check for by passing aVector2
when installing new unity version, it asks me to install vs 2019. but i already have 2022 version. can i untick 2019 and just use 2022 with game dev for unity workload?
Yes, unless you are installing an ancient version of unity it should work with 2022
All LTS versions should support 2022
Hello! is me again... https://hatebin.com/aqvnooukeg
https://hatebin.com/cvmmkgdzaq. These are my player controller and player triggers scripts. I am trying to disable movement on death. Taking the isDead bool from player triggers and putting it in the if condition on FixedUpate. I thought It would not run the codes in there if player was dead but it does not seem to be working.
Do you need the direction the wall is later on in OnJump?
only to know which direction to jump away from
Please Debug.Log() the isDead state on FixedUpdate and check if its actually dead
Is it like a wallrunning thing? Or why do you jump away from the wall when the player just jumps
oops i wanted to use a gif as exmple
yeh its supposed to be a walljump
Then I would output a tuple of (bool hasLeftWall, bool hasRightWall) from IsNearWall
public void Test()
{
var (a, b) = IsNearWall();
}
public (bool, bool) IsNearWall()
{
return (true, false);
}
tht makes sense. Can you compare it to this for me please and tell me why yours is better
private Vector2 forward;
bool IsNearWall()
{
//Perform raycast to forward vector
}
void OnJump()
{
if(isNearWall())
{
//Jump code
}
}
void Flip()
{
if (movementInput < -0.01f)
{
transform.localScale = new Vector2(-1, 1);
forward = Vector2.left;
}
else if (movementInput > 0.01f)
{
transform.localScale = new Vector2(1, 1);
forward = Vector2.right;
}
}
I will do it sorry I have to eat. Will get back asap.
I mean its just the way i would prefer it, I would not say its better, just preference
ah gotcha. i thought maybe it matters performance wise. in past experiences (not gamedev) ppl advised against tuples unless they were single use discard type things
Im using it for my shooting script
add a delay between
Look for yield new WaitForSeconds coroutines
If you are already using DoTween the DoVirtual.DelayedCall might be an option too
no
o
you need a coroutine
ah okay ty
void Update()
{
if (Input.GetKey(keycode) && canShoot)
{
//shoot
StartCoroutine(Cooldown(shootSpeed));
}
}
IEnumerator Cooldown(float delay)
{
canShoot = false;
yield return new WaitForSeconds(delay);
canShoot = true;
}```
Tyvmmm
private void FixedUpdate()
{
if (!playerTrigger.isDead)
Debug.Log("Is not dead");
Move();
if (canJump)
{
Jump();
//set it to false after jump because we dont wanna go flying upwards.
canJump = false;
}
else
{
Debug.Log("Is Dead");
}
```
It keeps saying is dead.
does not see the if above.
refering to this
Let me fix your indentation so you can see the problem
private void FixedUpdate()
{
if (!playerTrigger.isDead)
Debug.Log("Is not dead");
Move();
if (canJump)
{
Jump();
//set it to false after jump because we dont wanna go flying upwards.
canJump = false;
}
else
{
Debug.Log("Is Dead");
}
}
I put every curly brace you put in the code you showed
okay the log works now but I still got movement.
private void FixedUpdate()
{
if (!playerTrigger.isDead)
{
Debug.Log("Is not dead");
Move();
if (canJump)
{
Jump();
//set it to false after jump because we dont wanna go flying upwards.
canJump = false;
}
}
else
{
Debug.Log("Is Dead");
}
}
after death that is
Are you sure that movement is coming from here
this is the whole thing now
and yes this is where I do the movement
the only thing thats coming from another script is isDead
yes
so that velocity still exists
I made this
Ahh so. After setting the velocity once, It does not matter if i keep setting it in fixed? Thats why it keeps moving whether player is dead or not?
Newton's First Law of Motion
An object at rest remains at rest, and an object in motion remains in motion at constant speed and in a straight line unless acted on by a net force.
wohhh thats cool
I don´t think they teach basic physics in school anymore
why would a boolean affect a Vector3?
"Dead" is just a concept that exists in your head. It doesn't mean anything in code that you don't specifically tell it
Like if isDead is true then it would stop the Move function resulting in stopping.
I mean true
I understand now
Thanks guys.
how exactly would i get the first thing in the list in another class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[Serializable] public class PickMoveset : MonoBehaviour
{
public string moveset;
public List<string> moves = new List<string>();
public void PickGravity()
{
moveset = "gravity";
moves.Add("push");
moves.Add("pull");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves);
}
public void PickLevitation()
{
moveset = "levitation";
moves.Add("levitate");
moves.Add("float");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves[0]);
}
}
like i want to get moves[0] but in a different class
so lets say i wanna use serialized references do i gotta serialize my string and list
and would i use serialized reference
your string and List are already serialized because they are public
ok so in another class how would i refernce them sorry if im not understanding
first get a reference to the GameObject the script is on
second get a reference to the script
third access the variable
.moves[0] oughta do it
yeah i know for that but i need to get the class or smth right
You would need to know which PickMoveset you want to get the moves[0] from yes
alright thanks
this is my code what its meant to do is set text to those variables but it doesnt
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ChangeUIText : MonoBehaviour
{
public GameObject Text_Move1;
public GameObject Text_Move2;
PickMoveset pickMoveset;
TextMeshProUGUI textmeshpro_Move1_text;
TextMeshProUGUI textmeshpro_Move2_text;
// Start is called before the first frame update
void Start()
{
textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
textmeshpro_Move1_text.text = pickMoveset.moves[0];
textmeshpro_Move2_text.text = pickMoveset.moves[1];
}
}
anyone know what im doing wrong
First off why are you serializing game objects solely to get components from them. You should just make the TMP variables public and drag those in
Second where do you assign pickMoveset
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PickMoveset : MonoBehaviour
{
public string moveset;
public List<string> moves = new List<string>();
public void PickGravity()
{
moveset = "gravity";
moves.Add("push");
moves.Add("pull");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves);
}
public void PickLevitation()
{
moveset = "levitation";
moves.Add("levitate");
moves.Add("float");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves[0]);
}
}
I don't know what you're showing this
This has nothing to do with either of my questions
thats where i assign it isnt it
this is just a script
This is what the class PickMovement is
no, thats where you declare it
ah
I'm asking where you assign the variable pickMovement inside ChangeUIText
here??
declaring and assigning are confused to be the same thing, but they are different.
Where do you assign that
At what point do you tell the code which PickMoveset you put in the variable named pickMoveset
i dont think i did that lol no clue what that is
assigning is usually done with = , unless it was done in the inspector
Which PickMoveset do you want to get the moves from
i think you dont know what variable=something is called, but you have used it, the = is assigning something to the variable
theres only 1 pickmoveset though
And how does the code know that
there could be one
there could be seven trillion
So how do I tell it the right one
which one do you want to use
The one I have 😂
So tell it that
How are you telling it which Text objects you want to use to display the text?
thats how i think right
Yes. So do that
How
Drag it in
Guys, how do i make it so perlin noise would only generate a few stone blocks here and there instead of layers of blocks
bloons is never assigned
bloons is null because you never assigned it
no you're only assigning dmg from towerData.damage
That is a declaration
Assignments happen in the inspector or with an = sign
just make it public and assign it in the inspector
same way you did BaseTowa
so?
make aprefab
which object has bloons script and which one has ProjectileDmg
What IS Bloons? You want that to be the single bloon that should take damage?
I'm confused by the goal with this script? If you want the balloon you hit, use the collision passed in from OnCollisionEnter
dont you want the one from the collision ?
Which bloons do you want to call TakeDamage on
Collision2D collision your parameter has that info
You should use getcomponent or trygetcomponent to get the bloons script from the collision through the collider or something
you already check that object for a layer
instead look for the component you want, bloons
google what a NullReferenceError usually means, from there it's pretty clear that something isn't initialized. Then you search how to initialize that variable with a target in Unity.
if you configure your IDE properly that helps too with suggestions as to what could be going wrong.
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
yeah this is good, would be better to write something more robust with TryGetCompnent
if one is not found somehow
it doesnt break yes
if (collision.gameObject.layer == LayerMask.NameToLayer("Balloons"))
{
if(collision.gameObject.TryGetComponent(out Bloons bloons))
{
bloons.TakeDamage(dmg);
}
Debug.Log("Bhealth");
Destroy(gameObject);
}``` @lament kernel
https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
I'm experiencing some issues getting a character to properly orient towards my player. Why is my character rotating off axis? I thought LookRotation was supposed to only rotate around the given axis?
var lookRotation = Quaternion.LookRotation(LookAtTarget.position - transform.position, transform.up);
LookAtTarget and transform.position are both at the same height (y), so I wouldn't expect this tilt to occur?
using UnityEngine;
public class RotationMotor : MonoBehaviour
{
public Transform LookAtTarget { get; set; }
private void Update()
{
var lookRotation = Quaternion.LookRotation(LookAtTarget.position - transform.position, transform.up);
if (Quaternion.Angle(transform.rotation, lookRotation) > 5f) // 5f is the tolerance angle
{
transform.rotation = Quaternion.Lerp(transform.rotation, lookRotation, .1f);
}
else
{
enabled = false;
}
}
private void OnDisable()
{
LookAtTarget = null;
}
}
chances are the pivot of your duck is slightly higher than the penguin
so it tilts up
you can make a new V3 look target not include that axis
ah you're right, they're both at 0 in pause, but my navmesh seems to adjust the duck to 0.08 y on start.
hmm the lerp isn't correct
https://unity.huh.how/programming/specifics/lerp/wrong-lerp
iirc because it snaps on a navmesh
you could use this also
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
Thanks, this works fine for now
private void Update()
{
// Calculate 2D target diff in X and Z
var diff = LookAtTarget.position - transform.position;
diff.y = 0;
// Find the rotation that looks at target
var targetRotation = Quaternion.LookRotation(diff, transform.up);
// If the angle difference between these rotations exceeds tolerance
if (Quaternion.Angle(transform.rotation, targetRotation) > _angleTolerance)
{
// Lerp towards target rotation
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, _smoothingSpeed);
return;
}
// Disable once target rotation has been reached
enabled = false;
}
hmm as long is works ig lol very strange code..lerp is still wrong..
gpt strikes again
so i did that by using the GameObject thing what do i do for a script
Hello people, i need help. Im doing a follower of the camera but the camera is blinking
pls help me 😦
this is my code
!code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
That's not how you lerp
The value needs to go from 0 to 1
But you are multiplying a set value by a value that goes up and down but is generally a tiny fraction like .06. Which won't work
where?
Where what?
Thanks 😄
anyone know how i can attach a script to a script component
hoping someone can point me in the right direction. im trying to clean up my code but i have hit a snag
right now i have all these fields im trying to compact down, they are set via the inspector and need to continue to be so
[BoxGroup("Buttons")] [SerializeField] private TextBlock useEquipText;
[BoxGroup("Buttons")] [SerializeField] private UIBlock2D combineButton;
[BoxGroup("Buttons")] [SerializeField] private TextBlock combineText;
[BoxGroup("Buttons")] [SerializeField] private UIBlock2D discardButton;```
So im moving them into a seperate class, each containing one UIBlock2D and one TextBlock (These are novaUI classes, monobehaviors)
``` [Serializable]
public class NovaUIButtonCombo
{
public UIBlock2D button;
public TextBlock text;
}```
then im testing with
``` [SerializeField] public NovaUIButtonCombo TestButton;```
issue is that its not showing in my inspector at all. I need both the button and text to be serialized but they arent i dont even see just a single field for the entire object. how can i get this working? it would make my code a lot more organized...
dotnet version doesn't have much to do with your IDE configuration but you do you
like how i have those 2 objects attached to it
does it also work for movetoward?
might be a good usecase for Scriptable Objects instead.
The same thing but use the scripts type
nvm figured it out its monoscript
what i do is value = mathf.lerp(value, goal, 1f - mathf.exp(-sharpness * time.deltaTime)) where sharpness is how fast you want the lerp to be
what?
well they are in scene references, so i need references to objects
Thanks 😄
You can lerp any number your heart desires
so it still doesnt work i attached the PickMoveset script to it and now im using that but .moves is errored
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
public class ChangeUIText : MonoBehaviour
{
public GameObject Text_Move1;
public GameObject Text_Move2;
public MonoScript Moves;
TextMeshProUGUI textmeshpro_Move1_text;
TextMeshProUGUI textmeshpro_Move2_text;
// Start is called before the first frame update
void Start()
{
textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
textmeshpro_Move1_text.text = Moves.moves[0];
textmeshpro_Move2_text.text = Moves.moves[1];
}
}
I understand
heres where i attached it
ah fair. i think you might have to write a custom editor script then, i don't think you can show sub-fields in a serialized class. i might be wrong though
not sure if thats waht you meant to do or not
dang was really hoping to not have to do that lol, okay thanks
actually I might be wrong here
I was trying to ask chatgpt but it kept running me around in circles, i have roughly 0 esperience with editor scripting lol
MonoScript does not have anything named moves
No, it doesn't
yep
Show me where in the documentation for MonoScript there is a property named moves
and my IDE (rider) does say that its serialized but its not in the inspector
doesnt adding this make monoscript that instead
No
then how do i do what you said to do
it may be because the stuff in the Serializable class has to be Serializable for it to show up.
what type do i use
if you're manually picking in Unity, then you doing it wrong
The type you want
aka UIBlock2D and TextBlock have to be serializable themselves @desert wedge
so does this work
public PickMoveset pickmoveset;
i mean i can set them in inspector now if they are outside of that class
so there are no errors but the text is still new text
Show the current code
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
public class ChangeUIText : MonoBehaviour
{
public GameObject Text_Move1;
public GameObject Text_Move2;
public PickMoveset pickmoveset;
TextMeshProUGUI textmeshpro_Move1_text;
TextMeshProUGUI textmeshpro_Move2_text;
// Start is called before the first frame update
void Start()
{
textmeshpro_Move1_text = Text_Move1.GetComponent<TextMeshProUGUI>();
textmeshpro_Move2_text = Text_Move2.GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
textmeshpro_Move1_text.text = pickmoveset.moves[0];
textmeshpro_Move2_text.text = pickmoveset.moves[1];
}
}
So either you are getting errors or the text you're changing is not the text you're looking at
oh i get this
and this is how it looks in IDE
So maybe you should check before you say there's no errors
my bad
Look at the line the error is on. Something there is null but you're trying to use it anyway
that's odd. I don't know the origin of TextBlock etc so I'm not sure what the issue is there.
maybe just restart the editor haha
textmeshpro_Move1_text.text = pickmoveset.moves[0];
this is the line
hmm dang, alright thanks
So either the text mesh is null, pickMoveset is null, or moves is null. Try logging them to find out which
it's weird because if I try this it appears outside and inside
but if I remove that Serializable above SomeOtherObject it dissapears both inside and outside the test object
hmmmmm
yeah idk i just backtraced the UI blocks and it turns out they arent monobehaviours? but they do attach to game objects like mono behavious. but at no point could i find them inheriting from monobehavior
ok so pickmoveset and moves are both null because it seems it doesnt save it
might be some funky serialization setup in that framework then. i think you're better off asking on a forum dedicated to that ui framework, sorry bud
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PickMoveset : MonoBehaviour
{
public string moveset;
public List<string> moves = new List<string>();
public void PickGravity()
{
moveset = "gravity";
moves.Add("push");
moves.Add("pull");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves);
}
public void PickLevitation()
{
moveset = "levitation";
moves.Add("levitate");
moves.Add("float");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Debug.Log(moveset);
Debug.Log(moves[0]);
}
}
why does moves not save?
its okay thanks for trying so hard
Where do you set moveset
If you load a new scene all your variables are reset, if that's what you're asking
okay extra weird
i made a New Class with a UIBlock2D and 2 floats and made it serializable, in that one it shows up for some reason
in Pickmoveset
^
So, what specifically was null, you said pickMoveset but you showed moveset
moves is null
but pickmoveset is moves and moveset so if they are null then so is it
moves isnt null at first it shows what it is the very first time then its null
the debug that says what it is in Pickmoveset says what it is but the debug in CHangeuitext has it as null
No, if pickmoveset is null then what moves and moveset are is a fundamentally nonsensical question
So, is pickMoveset null inside ChangeUIText
Yes
i think thats this
public PickMoveset pickmoveset;
And where do you set it
wdym
Where do you set the variable
thats in the ChangeUIText
where do you say which PickMoveset you are putting in the variable pickMoveset
here?
Yes, so, that's an object in your scene, correct?
Show the inspector for that object
No, the PickMoveset
there is no pickmoveset object
Then what did you drag in
the pickmoveset script
That's not a PickMoveset that's a script file
So you don't have any PickMovesets in the scene
ah ok i think i got it now
so now i just got this
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Then you're trying to get an index from moves that doesn't exist
So I add 2 moves to it and I try and get 2 moves
Not sure how it’s outside the index
so yeah it doesnt seem to save it or whatever
cause getting moves[0] says it outside of it
Nice. Maybe could be because you didn't have the class in a separate file?
so it turns out im an idiot and was editing the wrong script lol
Show the inspector of PickMoveset
it gets stuff added to it when you press a button on the start screen
How does that happen, and when does that happen
so it happens in the pickmoveset script
where
Ah, I see now
its in a differnt scene
Okay, and do you click this button before a single frame has had a chance to render
dont think so lol i aint that fast
So, when the first frame renders, it runs update
which is looking for the first two elements in moves
which don't exist
because you haven't clicked yet
well changeuitext doesnt start happening till you enter that next scene i think
cause its not in a scene besides that one
So then how does the PickMoveset in the new scene get anything added to its moves list
isnt it the same as the pickmoveset in the old scene
no, why would it be
Have you done anything to make it so?
and i also have it change scenes first then add stuff
so wouldnt it be doing it for the scene your in
It'll change the stuff on this instance, which is the one that is in the scene that no longer exists
so how do i fix this
You have two PickMovesets. One in the old scene and one in the new scene
how do i have them be the same and sync
Make the earliest one a DontDestroyOnLoad but then you'll need to find a new way to reference it
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
now i gotta figure out how to fix the text cause rn its super scuffed
what part of it is scuffed? to big? 😄
the fact that the text isnt centered
make the text-element canvas the same size as its parent and then in the text option you can use the center option
I assume the background thingies are their parents?
yeah they are
they are all under 1 canvas
so the 2 background lines is one image? or are there 2 images?
Did you actually put the text in the center of the canvas
yeah but since the text changes you can center it right
Yes, just click the button for centered alignment
and make sure the rect for the text spans the whole area you're centering it on
where is that
The row that says "alignment"
ah ok thanks
https://img.sidia.net/ZEyI5/wovoQUPo76.mp4/raw This is how i center text relative to its background
depending on if you want the same height, you can also use the bottom right in the first panel
works now thank you very much this helps so much
script 1: Enemyhealth (screenshot 1)
script 2: ProjectileBehaviour (screenshot 2)
i am trying to figure out How exactily my projectile behaviour deals damage to an enemie and how those 2 objects interact. And WHY it works because i really dont understand it
What i understand is that i have a maxhealth, and currenthealth.
looking at the script the currenthealth should reflect the same amount of maxhealth, though i dont know why, and wouldnt this then imply that in theory, if i made a heal item, theres actually no limit to the nemies health ?
Then i see that if the "takedamage" is being used it will subtract the same amount of the value to "damage"
Since damage is a public in projectile behaviour, this is what causes the script being able to "communicate with eachother" and i am therefore able to call upon "damage" it will subtract the amount listed with damage value.
If the value of current health reached 0 then a "event" called die should take place wihich is then destroying the game object.
But in projectilebehaviour, under check if the collision is with an enemy, i dont really understand this part. and why i have written EnemyHealth and enemyHealth and there is nothing in between, what does this do ?
Would the first one be a direct representation of "Enemyhealth" sccript ? i figure that "enemyHealth" is just the action of which is defined below in an if statement which calls upon takedamage and the value damage to deal damage to enemie.
I see that in the getcomponent it references the EnemyHealth script and looks for a object that has a collider and contains a Enemyhealthscript ?
- Game starts, you spawn and current health gets set to the value of max health ONCE
- A projectile is presumably fired
- The OnTriggerEnter2D on the projectile detects, that it touched the player trigger
- The projectile fetches the player health instance from the touched player
- The projectile reduces the fetched player health by its damage amount through the
TakeDamagemethod
thanks this was helpful! i notice EnemyHealth is is a class, i need to figure out what that is to figure out why its written before the variable. But i think i can google that so i dont spam this channel too much, thanks agai !
Don't know what channel this fits in, but i can't figure out basic first person character controls. I tried to follow a tutorial but it didn't work and had no error messages. Can someone send me a project file with a standart capsule that has first person character controls set up? I'm using unity 2022.3.11f1 btw
What did not work, did it just not react to anything you do?
Yes
Can you paste us the !code ?
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
EnemyHealth doesn’t sound like a good component. I would probably define an EnemyState component, to hold different sorts of mutable data about an enemy
that way it can hold more than just health
Splitting up state like that can have its reasons, for example that you can have inanimate objects that do not have health, get a healthbar by just attaching that one script (e.g. you can now shoot that door to get through it)
in that case it would be a HealthBar class, which reads from a generic enemy state script. Just looking at futureproofing
It was the default preset from the asset store.
The ''tools'' section didn't appear on my toolbar
So i couldn't set it up properly
I tried to do it manually
void OnJump()
{
Debug.Log("Jump");
if (IsNearWall())
{
if (movementInput != 0 && (Mathf.Sign(movementInput) == Mathf.Sign(forward.x)))
{
float launchDirectionX = -forward.x * 4;
Vector2 jumpDirection = new Vector2(launchDirectionX, jumpSpeed * wallJumpMult);
Debug.Log($"Launching to {launchDirectionX}");
rb.AddForce(jumpDirection, ForceMode2D.Impulse);
Debug.Log("Walljumped!");
}
return;
}
if (IsGrounded())
{
Debug.Log("Grounded");
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
// else if (canDoubleJump)
// {
// rb.velocity = new Vector2(rb.velocity.x, jumpSpeed * doubleJumpMult);
// canDoubleJump = false;
// }
}
private bool IsNearWall()
{
Debug.Log($"Raycast to x {forward.x}");
RaycastHit2D raycastHit = Physics2D.Raycast(hitbox.bounds.center, forward, 0.5f);
if (raycastHit.collider != null) Debug.Log(raycastHit.collider);
else Debug.Log("No wall detected");
return raycastHit;
}
void FixedUpdate()
{
rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);
if (!canDoubleJump)
{
if (IsGrounded())
{
canDoubleJump = true;
}
}
}
Hi, hours later im still stuck on the walljump. every msg log happens, it even logs the "launching" msg with the correct Vector values, but i dont actually jump off the wall. all i see is vertical gain. What am i missing?
i disabled dbl jump on purpose to test this btw
You overwrite horizontal velocity on every fixedupdate
The first line of FixedUpdate sets the velocity to whatever you're holding on the joystick
i thought that was the issue, but every solution i thought of didnt work
what do i need to modify so it doesnt override it?
What do you want to happen if you walljump away and hold a direction in the air?
besides i did expect the velocity change from the walljump to affect that things value
so ur supposed to hold the directional key towards the wall, then pressing jump will "knock" you off it
up and awy from the wall
Okay, so, what do you want to happen if you, for example, immediately switch to holding the other way?
Do you want the direction held to have any affect on air movement or do you want to just cancel out any sort of lateral movement until you land?
At what point can inputs start working again?
if u switch it before jumping, nothing, if after, the usual knock
i guess moving in the air should count
but i do like the thought of being able to jump climb up a wall
Hey, im trying to make a grenade but do I need to just attach an explosion force to the grenade or would i have to get all the rigidbodies in the area and affect and add explosion forces starting from the grenade position?
You would probably get some sort of overlap sphere to find all rigidbodies in a radius of the blast and add explosion force to all of them with the grenade's origin point
rb.AddForce(jumpDirection, ForceMode2D.Impulse); my main confusion is why this doesnt override it. Like, my fixedupdate is reading velocity which should have been affected by this previous update call
gotcha thanks!
Let me phrase it this way:
int x = 7;
x += 14;
x = 3;
Debug.Log(x);
What is this log going to print?
So why would your velocity be any different?
velocity = MovementInput;
velocity += wallJumpForce;
velocity = MovementInput;
rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);
The X component of this velocity is movementInput times moveSpeed
Neither of which has anything to do with your walljump velocity
right im seeing
the thing is
if i make my current velocity part of that ill just speed up a lot over time
So you could use AddForce and then clamp the speed to some maximum value
AddForce for normal movement
the sad thing is ive been coding in c# for yrs but this physics stuff stvll confuses me
Clamp the magnitude after you set it
hold on
When I have a function that takes parameters that can be null do I have to say "MyFunction(X = null, Y = null, Z = null, ActualParameterIWantTouse)" or is there a simpler way?
You could make the nullable parameters optional, by putting a default value for them and putting them at the end
void MyFunction(ActualParameter, X = null, Y = null, Z = null)
My ActualParameter is nullable too
But if you actually want that parameter, don't make it optional
I dont always want it im just asking for cases when I do
You can still pass a null, but if you want to be able to ignore it, you need it to be optional and after any required ones
so i have this now
void FixedUpdate()
{
//rb.velocity = new Vector2(movementInput * moveSpeed, rb.velocity.y);
rb.AddForce(new Vector2(movementInput * moveSpeed, rb.velocity.y));
if (!canDoubleJump)
{
if (IsGrounded())
{
canDoubleJump = true;
}
}
}
i still struggle to understand what i should clamp tho
sorry if im being sloww, my brains fried
I think I may be confused but the way I currently set it up is with several Nullable parameters but if I want to use one I also have to specify that any that come before it are null right?
After you use AddForce, slap one of these on the velocity and cap it to your maximum speed:
https://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html
Obviously I can ignore it when im not using any of the nullable parameters just in the scenario I want to include one and not the others
If you've included all the required parameters, you can add any optional ones by name:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#named-arguments
im still lost. i do this in a new line? how will that stop the previous from going too far
rigidbody.velocity = clampedValues
After you add force, clamp the magnitude of the velocity. Meaning if the magnitude is higher than some value, it'll reduce it to that value
ok i get what it does but not where it should go
After addforce
Like... the line immediately after
OH
Because that is where it may be above the max speed
Ahhhh brilliant thankyou! This will save me some time
i thought i had to calc the clamp at the same time but its supposed to cut it off
just to confrm
Vector2 movement = new Vector2(movementInput * moveSpeed, rb.velocity.y);
rb.AddForce(movement);
rb.velocity = Vector2.ClampMagnitude(rb.velocity, moveSpeed);
Yep that should do it
Is moveSpeed the max speed you want?
yes
but it didnt work
my jump height is much lower than it was now and movement acceleration and decelration is super slow. Not even walljumping

You've just made a pretty significant change to your movement system, you're gonna need to mess with numbers.
You might also want to consider clamping just the X component instead of the whole thing
that makes sense 
clampMagnitude expects a vector tho, how am i gonna clamp only the x
Instead of using ClampMagnitude, just use a normal clamp
I don't know why but my visual studio keeps breaking, I cant put a method undernetth void update or have void update under other things. its missing them dotted lines and unity is reading it differently to what im seeing. Can someone clear up what I might be doing wrong? I have a feeling its using tab to move code to the left but also feel its not that?
i "cant clamp the x value of a Vector cuz its not a variable". i can only clamp it bforehand which doesnt solve it
showw the top of ur file
you cant clamp the x value of velocity because it's a Property
why i can't build the game to IOS?
yes i know
its derived
you need to configure your !IDE
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
You cannot both get and set the X value of the velocity in one line. Put clamp around the movementInput * moveSpeed in your new Vector2
that doesnt change anything. My jump launches me to the sky, and horizontal movement has vry slow acceleration and deceleration
Again, you're gonna have to play with the numbers. You'll probably need less vertical force, more horizontal
Followed the top link and got it installed, reopening the script results in the same issue
You'll probably need to have a different value for how much you add and your top speed
did you follow every step?
you don't just install the editor
you also install a package, and then configure Unity to use that editor
the issue is caused by a syntax error. configuring your IDE will not fix it, it will just highlight it so that you can fix it
how am i supposed to clamp smth AFTER the addforce when the addforce requires said clamped vector?
this feels like a recursive circle to me
unless im just really bad at english
Ah, right, you wouldn't want to clamp that before the add force
So, what you need to do is get the velocity into a variable, clamp the x value of it, then set the velocty back to that variable
ooohhh I see the mistake I made, I was trying to change a value for a int but stupidly put the access modifier at the start when it was in void update
and this happens after addforce yes
ok that makes more sense. ty
correct. now make sure that you get your IDE configured as it is a requirement to get help here
Alright, I'm having a weird issue with VSCode set up... It's a new project, I only have 2 scripts right now. The first one I made, everything is highlighted correctly, intellisense seems correct, but the second script in the exact same location, syntax highlighting is off, and intellisense is spotty...
Has Unity reloaded since you created the second script file?
It needs to recreate the project files before you will get any intellisense (beyond text-based suggestions)
It's recompiled, but I haven't fully closed it... I dont' think
Recompiling should be enough.
Close and reopen VSCode. If it's still happening, then show us what the editor looks like with the broken file open.
Yea it's not doing it. I've recompiled, closed VSCode and "Open C# Project"
Oh, wait a minute, got a version error for Visual Studio Editor when re-opening this time. That's new. I'll update that real fast. 1 min
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
the instructions require updating the Visual Studio Editor package to 2.0.20 or later.
Yea, I missed the update apparently. Still, that didn't seem to do it. Here's the comparison. They're at the exact same path.
since you were missing one step, you should really make sure you haven't missed any others.
go through this from top to bottom.
Hi again, sorry to bother,
but in my enemyhealth script i am trying to detect collision with "player" which has a Playerhealth script that should allow it to take damage but when doing debug.log on the collision in enemyhealthscript. Nothing comes out, Any idea why ?
ive checked the collision matrix. Everything is colliding with everything.
Player has a tag "Player"
both has rigidbody2d on it and collision components.
istrigger is unticked, both has colliders approperiately sized.
on enemyhealthscript i use the collision detection from my "projectile" and it works perfectly, the enemy dies when hit by projectiles.
but my player doesnt take damage when enemy touches it. Any Ideas?
the link below contains 3x script.
1st: PlayerHealth.CS - not taking damage from Enemyhealth
2nd: Enemyhealth.cs - not detecting collision with player using debug.log
3rd: Projectilebehaviour - this one collides and detect properly with enemye, but why doesnt this same script work on enemy vs player?
share your !code correctly, please
Posting code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
one sec
i dont really understand this comment, can you give me an example?
Yea, I don't see any other missed steps here... I restarted unity and VSCode again after updating that package and checked all the extensions to make sure they're all up to date
Wait, what the hell??
Uhh... I fixed it. Lmao...
Use one of the linked paste sites and put the links here
thanks i will do moving forward
I moved the script window from the docked view to the full view and it's all working now... Lol
this didnt work for me, also note i use a projectile with the exact same portion of the script which does work (ontriggerenter) really appreciate the suggestion though! 😄
You said you unticked "isTrigger" right? On both colliders?
If that's the case, I'm curious how you're still getting trigger events
Yes thats correct, Ive edited my post containing all 3 scripts.
the projectile vs enemyhealth works.
enemiehealth vs playerhealth doesnt.
all 3x objects has "is trigger" unticked.
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt Not tick
isTriggeron either - Thou Shalt have a 3D Rigidbody on at least one of them
3d collider? i mean why is bullet vs enemye working then i am so confused right now xD
OnCollisionEnter is for 3D collisions
Do you have 3D colliders?
Oh actually i think it was a suggestion from someone higher up and it didnt work so forgot to change back xD the original was a direct copy of ontriggerenter2d which works on projectilebehavioru
lemme fix it and try again
nope still nothign
Show updated code
Okay, so, show the inspectors of the two objects involved in this collision
My bad, I syhoulda been specific. There's a 2D variant
does OnPointerEnter only work on canvas elements? it doesnt seem to be working at all for my object.
screenshots of enemy and player inspector
ffs... it doesnt previiew ? (using snipping tool)
it looks like you've removed the extensions from your image files
I just used copy paste from snippingtool really, did it again with 1 image, now it works dunno why xD
Neither of these are Triggers
but this one works: and its set up the same way, i dont understand
This bullet is not a trigger, but that little highlight there means the prefabs (likely the ones you're spawning in as you play), are triggers
If you want to use OnTrigger___ then at least one of them needs to be a trigger
oooooh so making a prefab automatically makes it a trigger?
No
Just the fact that you've changed the one in the scene
The bold text means you have modified that property.
But did not change the prefab
ohshit,,, i put in a new prefab,, ur right, it is a trigger
damn... so i need to use one that doesnt require a trigger (dont want trigger because it makes enemy and player phaze through eachother
If you want to detect a collision, use OnCollision
thank you for the pointer and helping me on this, sorry im thick as brick when it comes to this stuff
now i need to google how to use oncollision xD
YESSSSSSSSSSSSSSSSSSSSSSSS its workign !!!!!!!!!!!!!!!!!
@polar acorn
@swift crag
@slender nymph
Thanks guys !!!!
Hello everyone,
In this scenario I have, switch_controllable(GameObject) is declared in CAMERA CONTROLLER. How can I call this function from other scripts?
I tried using delegate/event, but the way I see this is not a good case for that.
Is there a better solution than what I am doing now?
Without using the UI reference please
why not
I try at max to keep stuff in code, just in case I delete a gameobject from the scene and to add it back I have to look at all the references it needs and drag them again
In the prototyping phase that I am right now, this happens a lot
Setting references in code is just as vulnerable to that
You could still be attempting to reference something on an object you've deleted
Very true
Is this "design" I showed in paint unpractical?
Should I approach this from another angle?
I don't really know what the image is indicating, honestly
Three separate scripts, I want the ORANGE and BLUE to be able to call the method SWITCH_CONTROLLABLE that is declared inside the RED script

Yeah, so, having them reference the red script and call it is the way I would go about that
why not a simple singleton
Will look into that
on camera controller, u can do stuff to it from anywhere then
Nice, will try that
If I declare the switch_controllable as static, is that a specific programming pattern?
Just that method would be static
just declaring method as static isnt suddenly some pattern
singleton isnt about methods u looked up something else
Have the bullet keep a list of cookdowns
That's probably easier if you don't expect the bullets to hit them again at some point (bouncing bullets)
hey if i need to hold on to three sets of key-value pairs, what is the best container to use, an array of Dictionaries? I'm having trouble with the syntax.
private Dictionary<string, int>[] appearanceData = [new Dictionary<string, int>(), new Dictionary<string, int>(), new Dictionary<string,int>()];
well it doesn't really need to be key-value pairs, i just need the values, the keys are fixed
Looks overly complex. What are you doing in particular?
but i don't want to access them with magic numbers
character customization for three characters. I need to move their appearance data from the scene where they are created in the UI using Images to the gameplay scene where they use SpriteRenderers. The values are things like shader values, etc.
I have a sword as a child of the player. I want the sword to move in relation to the player, but its just going to a specific x and y in the map.
public class SwordController : MonoBehaviour
{
public Transform swordCursor;
public Vector3 defaultPosition;
public Quaternion defaultRotation;
public float rotationSpeed = 5.0f;
void Start()
{
defaultPosition = transform.position;
defaultRotation = transform.rotation;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (swordCursor != null)
{
//Point towards SwordCursor Object
Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
else
{
// Smoothly move back to default position and rotation
transform.position = Vector3.Lerp(transform.position, defaultPosition, rotationSpeed * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, defaultRotation, rotationSpeed * Time.deltaTime);
}
}
}
i guess a 2d array of ints accesed using an enum would work actually
So currently.. it would seem you've got an array of three dictionaries of type string/int. What's the string representing? The int? And why an array? (is this for a particular reuse pattern?)
Maybe modify local position rather than world position.
yeah forget the dictionaries i think i was overthinking it. I can just use an array like appearanceData[0, Appearance.Skin] or similar
where the first field is the player index
and the second is an enumerated set of fields
no
Er, how could one do that? Sounds like exactly what I need tbh
transform.localPosition
maybe when spawning weaker enemy pass into it reference of bullet which killed stronger one and ignore that bullet in ur take damage method
In Unity, 1 unit is 1 meter. So, if I want a 1.7m character, I can create a cylinder with scale 1.7 in the Y axis?
assuming the cylinder's height at the default scale is 1 unit, yes
This does not appear to be the case.
(for the default Cylinder object, at least)
it has a radius of 0.5 meters and a height of 2 meters
I am having a problem with my terrain. As you can see there are weird lines in my terrain, they came out of nowhere and I do not know how to fix it. I am using a material called FixGaps that prevents from screen tearing so I do not even know if the material is the problem or the terrain is.
Can someone please help?
Doesn't sound relevant to this channel.
That material uses a standard shader, so I don't think it's relevant.
What does seem relevant is probably that your sprites overflow into adjacent tiles.
I have the main camera separate from the player, so when my camera moves vertically, the sword doesnt stay in the middle of the screen
how can i make it follow the vertical movement of the camera?
public class SwordController : MonoBehaviour
{
public Transform swordCursor;
public Vector3 defaultPosition;
public Quaternion defaultRotation;
public float rotationSpeed = 10.0f;
void Start()
{
defaultPosition = transform.localPosition;
defaultRotation = transform.localRotation;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (swordCursor != null)
{
//Point towards SwordCursor Object
Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
else
{
// Smoothly move back to default position and rotation
transform.localPosition = Vector3.Lerp(transform.localPosition, defaultPosition, rotationSpeed * Time.deltaTime);
transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, rotationSpeed * Time.deltaTime);
}
}
}
What's the difference between void start and void update?
You can read about all of the messages here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
notably
Since you're saying void. I will also say that void is simply the return type. It means it does not return anything. When talking about methods, you don't need to include the return type. Just say Start and Update
right
int Foo() returns an integer; string Bar() returns a string
and void Baz() does not return anything
the methods are named Foo, Bar, and Baz, respectively
👍
yeah, i don't have a return type either . . .
We don't know that for sure. You might be lying.
that could be true. i can be overriden though . . .
But if you're overriden, the signature must stay the same. We wouldn't even know you were replaced by a different person.
exactly . . . 😉
Hey guys I was wondering if someone could point me in the direction to make an inventory. For functionality I'm trying to have 3 slots that you can equip in fps fashion.
YouTube I guess. There are plenty of tutorials on inventory systems there. Or just google. There are so many ways to implement it, that there isn't one particular resource to point to.
See what there is and choose the one that suits you best.
Gotcha, I was thinking I should try it out first but seeing as I've no clue on how to even start that's probably the best idea. Thanks!
Using an AnimatedTile, need to pause the animation and saw I could do so with something called a TileAnimationFlag.(https://docs.unity3d.com/ScriptReference/Tilemaps.TileAnimationFlags.PauseAnimation.html)
I can't find any information on how to use it, and as expected doing tile.TileAnimationFlags.PauseAnimation() only results in errors stating
"'AnimatedTile' does not contain a definition for 'TileAnimationFlags". Help is greatly appreciated!
You'd use these flags in AddTileAnimationFlags and other similar methods of the Tilemap:
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html
Good timing, I just figured out I need to to be referencing a Tilemap. Now I have this issue: " 'Tilemap' does not contain a definition for 'AddTileAnimationFlags'"
TileAnimationFlags is an enum. you need to select one of the enums: https://docs.unity3d.com/ScriptReference/Tilemaps.TileAnimationFlags.html
Which seems to go directly against the Tilemap public methods api
the above message
You might be able to set the tile flags directly too:
https://docs.unity3d.com/ScriptReference/Tilemaps.Tile-flags.html
Unless it's only a getter. The docs don't reveal that.
didn't work- my guess as well
Are you sure you're using the correct type?
What didn't work? Error?
Yes, I have an array of Tilemaps I assign in the Inspector
this is the line:
animatedTiles[0].AddTileAnimationFlags((-22, 4, 0), PauseAnimation);
I realize I need to convert the ints into a vector
Still doesn't recognize the method however
Is animatedTiles an array of tiles or tilemaps?
