#š»ācode-beginner
1 messages Ā· Page 93 of 1
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
You can still rename it to .cs and send it. :p
Most people on pc can view it.
But it can get so long as some point that discord will cut it off anyways.
is the interface in a namespace you haven't added a using directive for?
it should tell you why it doesn't work if you hover over it
oh thanks
it worked
In unity's input manager package, it had a binding to mouse delta. It doesnt have it now. Why and how can I replace it?
!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.
oh thanks didnt know
Hey, I need help. I've got a player that moves, and when i change the movement direction, he faces it straight away. what i want to do is like in mario games, that he starts slowly facing that direction and drifting towards it. (like leaning to it). i dont care about rotation right now just about movement.
my code is this:
private void HandleMovement()
{
moveDirection = new Vector3(cameraObject.forward.x, 0f, cameraObject.forward.z) * inputManager.verticalInput;
moveDirection += cameraObject.right * inputManager.horizontalInput;
moveDirection.Normalize();
moveDirection.y = 0;
if (inputManager.moveAmount > 0)
{
if (isSprinting && inputManager.moveAmount > 0.5f)
{
moveSpeed = sprintingSpeed;
}
else
{
if (inputManager.moveAmount >= 0.5f)
{
if (!isSprinting && moveSpeed < maxSpeed)
{
moveSpeed = maxSpeed;
}
}
else
{
if (moveSpeed > walkingSpeed)
{
moveSpeed = walkingSpeed;
}
}
}
moveDirection *= moveSpeed;
}
else
{
moveSpeed = 0;
moveIncreaseSpeed = 0;
}
if (isGrounded && !isJumping)
{
Vector3 movementVelocity = moveDirection;
playerRigidbody.velocity = movementVelocity;
}
}
here
sorry
what exactly are you trying to achieve? is this a platformer?
third person platformer, yes
aha, and what exactly do you want the movement to do?
lets say im facing forward, and then i turn the joystick right-up. now, he just keeps moving in that direction. i want him to slowly face that direction so the turn will be more rounded (sorry if my explaining sucks, if you still dont understand ill try to explain better)
so you want your camera to align or better word recenter to the direction you move to correct?
I have no idea im new here
i see someone has sent here screenshots in the past so i will asume you can
videos and screenshots of your issue are wanted
they're useful and help get the point across better than words
I see, how about for turning left and right you rotate
slerp your movement direction and rotation toward your input
or that
isnt slerp just for quaternions? sorry im new to unity
so would it be like this?
moveDirection = new Vector3(cameraObject.forward.x, 0f, cameraObject.forward.z) * inputManager.verticalInput; //front and back
moveDirection += cameraObject.right * inputManager.horizontalInput;
moveDirection.Normalize();
moveDirection.y = 0;
moveDirection = Vector3.Slerp(moveDirection, moveDirection + cameraObject.right * inputManager.horizontalInput, 2f);
i guess not because its not working... did i do it wrong?
first thing i notice is that your t parameter for the Slerp call is 100% incorrect
here's how that t value works: https://unity.huh.how/lerp/overview
oh so i need to multiply it by Time.deltaTime?
well that depends on how you want to handle it. technically that is wrong, but may lead to results that are close enough to what you want
t is like how much time the lerp takes, right?
surely you read the page i linked?
now i did
can the assumption be made that awake has been called on every scene components at the time of unity's sceneloaded callback?
probably, i just tested it and Awake was called before the sceneLoaded event was invoked. but i honestly wouldn't count on that always being the case
is this better?
moveDirection = new Vector3(cameraObject.forward.x, 0f, cameraObject.forward.z) * inputManager.verticalInput; //front and back
moveDirection.Normalize();
moveDirection.y = 0;
if (driftTimeElapsed < driftDuration)
{
float t = driftTimeElapsed / driftDuration;
moveDirection = Vector3.Slerp(moveDirection, moveDirection + cameraObject.right * inputManager.horizontalInput, t);
driftTimeElapsed += Time.deltaTime;
}
else
{
driftTimeElapsed = 0;
moveDirection += cameraObject.right * inputManager.horizontalInput;
}
tried it
made a modification
ill edit the message
so it kinda works
its lerping correctly
but when its done, it resets and does it again
this shows an example
https://unity.huh.how/programming/specifics/lerp/coroutines
because the player can always just change the input
oh you have input in there..
Im trying to instantiate a player and enemy prefabs at the start of the game session, somewhy there's an error stating that prefabs are inactive, even though as prefabs they are saved as active
Instantiate(playerController, playerController.transform.position,
playerController.transform.rotation);
Instantiate(enemyPrefab, enemyPrefab.transform.position,
enemyPrefab.transform.rotation);
yeah exactly
!code @bold nova
š 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.
thats the problem
yeah I never used that inside lerp so I'm useless here xD
oh ok thx. anyone else?
I'd like to teleport my player upon death but I get syntax errors, I don't know how to fix them...
this is not how to set position
how do we assign things in code ? š
again.read the bot
#š»ācode-beginner message
oh, backquotes..
yea my bad forgot the equal sign... Stil doesn't work tho
close
what is error is saying
what is target
postion is a vector3
That's not how you make a vector
public void StartSession()
{
loseMenu.SetActive(false);
Instantiate(playerController, playerController.transform.position,
playerController.transform.rotation);
Instantiate(enemyPrefab, enemyPrefab.transform.position,
enemyPrefab.transform.rotation);
playerController.GetComponent<PlayerController>().StartIntro();
enemyPrefab.GetComponent<Enemy>().StartIntro();
enemyPrefab.GetComponent<Enemy>().StartShooting();
spikeSpawner.gameObject.SetActive(true);
gameIsOn = true;
which one is spawning disabled?
and show the prefab of such object
You are calling StartIntro and StartShooting on the prefabs, not the objects in the scene you just made
they are both set to active, if thats what you want to know
read this, its important
What is the actual error you are getting
Coroutine couldn't be started because the the game object 'Player' is inactive!
Instantiate returns an instance. You give it a prefab, it gives you something you can use at runtime. You need to capture that and use it. You're not doing that here.
yeah, i've assigned prefabs, now everything seems to work now
Probably because you're trying to start a coroutine on a prefab that doesn't actually exist
Hi again !
i've found this command in the unity API ScreenCapture.CaptureScreenshot and from what i understood, this takes an entire screenshot, but from which camera ? is there a way to choose to camera that takes the screenshot ?
probably the one that is active
yeah that what i tought indeed
if you want a specific camera you'd have to use Render Texture and just save it manually
You want to take screenshots at runtime or in the editor, whats the purpose?
at runtime
So when trying to teleport my player upon death, it gets teleported for 1 frame to the right location then is right away back where it was. I am using characterController to move the player. Any fix ?
There's most of an example of how to use a disabled camera with Camera.Render in the docs to make a 'screen shot' https://docs.unity3d.com/ScriptReference/Camera.Render.html
I am thinking of moving it with a vector between spawn location and player location with characterController.move, but I'd like an easier way
Character controllers don't like being teleported. It keeps its own internal copy of where it should be and moves the object there every frame. You can tell it to throw out it's copy and get a new one after the teleport by calling Physics.SyncTransforms()
ok, i've figured it out. I wanted to locate those prefabs on the dafault point, when player clicks replay button. Now everything works, but is if someone knows better way, im opened to suggestions.
Vector3 enemySpawnPosition = enemy.outPoint.position;
Vector3 playerSpawnPoint = playerController.spawnPoint.position;
playerController.gameObject.transform.position = playerSpawnPoint;
enemy.gameObject.transform.position = enemySpawnPosition;
playerController.StartIntro();
enemy.StartIntro();
it works, thank you very much !
just had to disable character controller as well, it's what is causing the issue
yes it says so in the instructions lol
thats because character controller overrides transforms so it saves its own internal position
if you move manually , the next frame will just return back
There's no off topic here. Move on.
Hey there I have a question. I start a coroutine in another coroutine using yield return StartCoroutine(CoroutineTwo()); This should first finish that second coroutine before moving on with it's onw code if I remember correctly. The problem is that everything after the CoroutineTwo() doesn't get called anymore. Can anyone help me find the problem? Here is my code for the first Coroutine:
{
if(activePlayerPowerupState == newPowerupState) yield break;
isPoweringUp = true;
yield return StartCoroutine(animationController.PowerupAnimationCo(newPowerupState, activePlayerPowerupState));
//THE CODE BELOW DOESNT GET CALLED
if(activePlayerPowerupState.powerupSize != newPowerupState.powerupSize)
{
if(player.IsDucking())
{
SetCrouchSize(newPowerupState);
}
else
{
SetBaseSize(newPowerupState);
}
controller.CalculateRaySpacing();
}
activePlayerPowerupState = newPowerupState;
isPoweringUp = false;
} ```
Here is my code for the second coroutine:
{
if(activePowerupState.powerupSize == PlayerPowerupState.PowerupSize.Small)
{
if(newPowerupState.powerupSize == PlayerPowerupState.PowerupSize.Large)
{
Vector3 startScale = transform.localScale;
string animToPlay = CheckAnimationState();
SetAnimator(newPowerupState);
PlayAnimation(animToPlay);
transform.localScale = new Vector3(startScale.x, startScale.y / 1.2f, startScale.z);
float newYScale = transform.localScale.y;
SetSpriteOffset(newPowerupState);
float yOffset = (startScale.y - newYScale);
transform.localPosition -= new Vector3(0f, yOffset, 0f);
yield return new WaitForSeconds(0.1f);
transform.localScale = new Vector3(startScale.x, startScale.y / 1.3f, startScale.z);
newYScale = transform.localScale.y;
SetSpriteOffset(newPowerupState);
yOffset = (startScale.y - newYScale);
transform.localPosition -= new Vector3(0f, yOffset, 0f);
yield return new WaitForSeconds(0.1f);
}
}
} ```
!help
he needs a blood sacrifice, but Iām all tapped out
one of us
Oh sorry do I put the code in there and post it here again?
yeah. itās tidier, and on mobile, your code looks like this
Ah I see, I'll do it rn. Thx for letting me know!
i assume this is for the mario project, right?
itās not relevant to the discussion. just asking
i saw the video, your code, and your name. put two and two together lol
Oh okay, well yeah I'm basically overhauling the thing ans starting over
Okay how do I send the filled in hatebin thing?
link at the top
i wonder if the issue comes from the second coroutine coming from a different class.
Well I have done some testing with a coroutine in the same class and it does the same so I dont hink that's the issue
you could try making the second coroutineās IEnumerator private, and give a public method to start that coroutine. I assume the second Ienumerator comes from a class derived from monobehaviour?
Yeah it's a monobehaviour
iāve done it before too, but i donāt recall doing that within a Coroutine
Hi hi, i want an animal to eat another. My idea is to add a collider to the eaters head and "eat" anything, that collides. I already have a collider on the game object tho. Can implement collision or trigger methods for individual colliders or is this approach over the top?
ok, try making a public method in the second class that starts the coroutine
btw, you probably want to save a private variable for the coroutine to make sure you donāt have two running at once.
Oh okay I'll try that
Thanks
But can I then still yield return it? As it's wrapped in a method
public void TryStartPowerupAnim() {
if (poweringUpAnim == null) poweringUpAnim = StartCoroutine(MyCoroutine());
}```
and MyCoroutine sets poweringUpAnim = null at the end
oooh, the formatting was so strange, I didnāt understand why it wasnāt working
i didnāt realize you were yield returning StartCoroutine
what is the method if I want to make my player object child of a platform so that it moves with it ?
Oh is that why it doesnt work?
so, how is it supposed to work?
Coroutine 1 code block 1, Coroutine 2, then Coroutine 1 code block 2?
Yeah
ooooh. Ok, so we donāt want to start coroutine
fellas i need help my script does everything i want BUT it does not let me look up or down not sure what im doing wrong here
or rather, we donāt want to start the second ienumerator as a separate coroutine
we want to manually enumerate through it.
yourTransform.parent = platformTransform;
I'm assuming you want to be able to look up or down
Oh okay okay
yes
which makes it not doing everything you want
true i guess my cylinder has a stiff neck
I forget the exact syntax, but in the first coroutine, you need something like;
IEnumerator powerupAnim = PowerupAnimationCo(ā¦);
while (powerupAnim.MoveNext())
yield return powerupAnim.Current;
i need to check what the methods are called for IEnumerator, but you want the first IEnumerator to enumerate through the second one, partway thru
the system running the coroutines is probably extremely confused that you yield returned an object of type coroutine
Okay I see
Lol I remember doing smt similar in the past where it did work, but might be wrong
ok i think the syntax I gave you is roughly right
anyone able to tell me WHY this does not look up or down https://pastebin.com/viSWvV3Q
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.
Nice I'll try it and do some more research, thanks for the help!
good luck
Thx
You use Vector3.up for both mouse x and mouse y
Camera.main.transform.localRotation = Quaternion.Euler(newRotationX, 0f, 0f); spot the mistake?
i feel like i should but i dont
transform.Rotate(Vector3.up * mouseX);
transform.Rotate(Vector3.up * mouseY);```
Why are you rotating on the y axis for both mouse input axes?
idk i have been trying to fix it for a while so kinda just copied the same thing but changed x to y
is there a way to get the object name a character controller is standing on ? like characterController.isGrounded but for the name of the object
I would say your most likely issue is some improper setup in the scene, as well as that double Rotate line
Are there any errors in console?
You'd have to use either https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnControllerColliderHit.html
or a raycast
Hey so I don't know if this is normal or not but my update function does not work
define ānot workā
I might of fixed it
another happy customer
nope it still does not work
if the monobehaviour enabled, on an enabled gameobject, and timescale > 0?
I am adding the listnener in the code above
if you only say something doesnāt work, understand it is impossible to help fix
is giveitembutton null?
No I assigned it
give the button many different colors for the different states
Is your button even responding to the mouse
like for highlight, select, normal, etc
Do you have an event system in the scene?
give the button all different colors for selected, highlight, etc to see where the problem is
that is what i missed
Thanks
easy one š
var entry = character.FakeCharacter.SpriteCollection.MeleeWeapon1H.SingleOrDefault(i => i.Name == itemSO.SpriteName && i.Collection == itemSO.CollectionName);
How do I replace MeleeWeapon1H by my itemSO.CollectionName variable?
Use a Dictionary
SpriteCollection would need to have a Dictionary<string, whatever type MeleeWeapon1H is>
heh? no I'm calling this line of code with multiple different itemSO.CollectionName's and I need the MeleeWeapon1H to change to the variable value
And I'm telling you how to do that
C# is not Python or JavaScript
we cannot simply substitute strings for variable names willy nilly
CollectionName is an Enum
ok then
Dictionary<ThatEnumType, Whatever>
you will need a dictionary or a switch statement basically
SpriteColection is "external" code - I can edit it, but would rather not
so I guess I just use a switch statement then?
You can use a Dictionary or a switch
either way
you can build a function:
public Sprite GetSpriteForWeapon(WeaponType wt) {
// return the corerct sprite for the weapon type
}```
you can implement this function with a Dictionary or a switch statement
I'm guessing at the types here
you'll have to fill in the correct parameter and return type
A better option than all of this might be just to have a direct reference to a ScriptableObject that has the sprite on it
There's too many unknowns in the example you provided to get very specific here though
well basically I need to do this:
var entry = character.FakeCharacter.SpriteCollection.Helmet.SingleOrDefault(i => i.Name == itemSO.SpriteName && i.Collection == itemSO.CollectionName);```
But I don't know if it will be MeleeWeapon1H or Helmet up front and theres 15 other types
You really should write shorter lines of code
this is all šµāš«
Anyway I explained what to do
You can tqake it or leave it
Can i have multiple colliders on a GameObject "A" and have only collisions to a specific collider of "A" execute a methode?
Whatever SpriteCollection is needs to have a function on it to get a sprite for a given equipment type
Put the separate colliders on separate child objects
and put scripts on those sepearet children
This would be it. Thanks
alternatively, if your script has references to those colliders, you can check which one it is in OnCollision callbacks
case "MeleeWeapon1H":
var entry = SpriteCollection.MeleeWeapon1H.FindSomething();
Equip(entry, itemSO.EquipmentPart);
break;
case "Helmet":
entry = SpriteCollection.Helmet.FindSomething();
Equip(entry, itemSO.EquipmentPart);
break;
}```
There must be a better sollution for this over writing 15 of these?
I simplified the code to better show my question
Yep - as mentioned - a dictionary
or just a direct reference to a ScirptableObject where this is preconfigured
instead of using a CollectionName
I think the former method suits my purpose better, because i want the additional collider only for triggers
like I said, it refers to external code that I would rather not edit
I don't understand how a dictionary would help?
and there's no way to add a direct reference to the sprite, it's not referencing a sprite but an object defined by the external code
this would be sooo easy in PHP, does C# really not have a solution for this?
Is this the same?
GameObject go;
if (go)
{ //Do something; }
-------------------
if (go != null)
{ //Do something; }
yes
if(!go)
is also the same as == null?
Yes
Note this is only specifically for things that derive from UnityEngine.Object
this is due to operator overloading for that type, not anything built into C#
got it thanks
can i receive help for this?
but the problem is im constantly checking for an input
Why is that a problem?
i mean right now im running it in fixed update, and any time there is a change to the joystick it recognizes it, would that work in a coroutine?
Thats not a problem, in fact you should check for input in Update
so like this?
IEnumerator DriftToDirection()
{
if (driftTimeElapsed < driftDuration)
{
float t = driftTimeElapsed / driftDuration;
moveDirection = Vector3.Slerp(moveDirection, moveDirection + cameraObject.right * inputManager.horizontalInput, t);
driftTimeElapsed += Time.deltaTime;
}
else
{
driftTimeElapsed = 0;
moveDirection += cameraObject.right * inputManager.horizontalInput;
}
}
Coroutine without any yields?
this will be a compile error, and also makes little sense
yield return null?
Why is this a coroutine
That makes it yield the main thread for one frame
There are multiple kinds of yield though
to stop it from running again and again
That's not what a coroutine does
i only want it to run when input direction changed
Then you should make this a normal function, and call it when the input direction changes
i was relying on navarone
it would need to be looping if you intend to make it a coroutine that you only call when input changes
https://gdl.space/xedupovutu.cpp https://gdl.space/nosirihita.cs https://gdl.space/erirutujuf.cs https://gdl.space/howepatazi.cpp Hey guys, I was wondering if someone might know what I'm doing wrong here, I'm getting a null reference error. All of my inventory itself and items are setup as scriptable objects, Getting a null reference error on the GiveKey() method
What is the error
what line
29 on howepatazi
where do you assign to cKey
cKey is null
object reference not set to an instance of object
like this worked but after it lerped my current direction to the wanted one, it reset me to my last direction and did the lerp again
cKey is private and not serialized, so how do you assign it. I don't see it anywhere there
Im unsure on why my code is not working. It does not drop the item when the enemy is killed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DropBrain : MonoBehaviour
{
public Transform transform;
public GameObject Dropear;
public float vida = 1f;
void Update()
{
if (vida >= 0)
{
void die()
{
Destroy(gameObject);
DropCerebro();
}
}
}
// Update is called once per frame
void DropCerebro()
{
Vector3 position = transform.position;
GameObject Cerebro = Instantiate(Dropear, position, Quaternion.identity);
Cerebro.SetActive(true);
Destroy(Cerebro, 10f);
}
}
You have a function in your function
Where do you call die()
i swear, the guy in the tutorial did it like that and it worked š
Show the tutorial
Link to it
No.
In this video I walk through a code I wrote to make Coin Drop Effect In Unity.
Background Music By Lakey Inspired - https://soundcloud.com/lakeyinspired
1:35
is there a simpler way to fix this which im just not seeing?
Well I'll be damned. One of the actual cases of this being true. Congrats on being the fifth ever:
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 138
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2023-12-7
You should probably delete everything this tutorial told you to do and find one that isn't terrible
YEAAA!
Do i get a high five?
BTW. I was also like "this guy created a void inside a void? it works? huh" so i was not sure if i was tweakin or not.
You get immortalized as one of the single-digit number of people who have managed to find a broken tutorial
horrible
It's legal C# code, but it is almost never what you want, and you'd still need to actually call it
Is the tutorial that bad? im going to search for another one either way.
If a tutorial is willing to put blatantly non-compiling code in the tutorial and not mention it you can assume the rest of it is low effort and not worth following
how would i check if the left stick has moved since the last frame? using new input system
seriously i would take something down if it was like that
You can maybe get some of the concepts, but don't use any code from it, make your own
I mean. Fair enough, but sometimes i find tutorials that has code that breaks a little, i fix it or maybe change it a little bit and keep on my day.
but anyways, thanks.
the best way honesstly is watching many different people doing it without copying , just learn and compare from each small bits ... after put your own system together
this actually sounds like a great idea
this way ensures you pretty much know your own system if something goes wrong..
I love and hate coding
otherwise its like blindly following someone in the woods until they leave you stranded
Sometimes im happy because i make stuff works, or i get errors and i know how to fix em. But sometimes i just wanna take my own face off.
can i get help?
the more experience you gain solving problems, the less frustrating it will be
by the way, they're not called "voids" -- void is just the return type of the function
void Foo() { }
int Bar() { return 3; }
Store the value from last frame, check the current value this frame. If they aren't the same, it's been moved
yes but how do i store the value from the last frame so it doesn't change every frame
You can indeed declare a function inside of another function
void Foo() {
void Bar() {
Debug.Log("Hi");
}
Bar();
}
This would log "Hi" if you called Foo.
The reason that the example in the tutorial was bogus was because it tried to put an access modifier -- public -- on the local function
Store it in a variable, and check the variable before you change it
An access modifier only makes sense when declaring members of a type. Local functions don't exist outside of the function they're defined in, so it makes no sense to put public there.
reworded my question
Store it in a variable, and check the variable before you change it
yes but the variable im storing it in will be updated every frame to the new input - how do i stop that?
This is the first time i see it.
It's not very common.
Why would you do it tho? In which cases?
I only do it when I have some logic that:
- I need to use many times in a function
- I won't use anywhere else
Could yall help me ? My 2d character cant start the runinng animation unless it jumps first
not enough info
I set 4 states idle, jump running and falling. I used animator for trying to make transitions
Do i have to uncheck exit time?
yeah probably, also sounds like you put the transitions wrong
not sure where the code part comes in
you have to send that and show your transition conditions
if this is an animation question, ask in #šāanimation . please show us your animator controller when you do so
!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.
Question: How does the scaling get from top to bottom when attaching the player to the "attacher" empty with (1, 1, 1) scaling. The Player was (1, 1, 1) before.
I need the player to stay uniform.
Hi guys, not sure if this belongs here or in #āļøāphysics is honest as it's a bit of both, but I'm having a bit of brain fog.
I have a player shooting at a door, the door then explodes into bits and I want the 'bits' to be pushed away from the direction of the shot that destroyed it (using the physics system.
I'm getting the direction of the shot with.....
Vector3 shotDirection = (explosionPoint.transform.position - playerFiringPosition.position).normalized;
and I know that I have to apply a force to each of the 'bits' but getting the direction of the force (opposite of my 'shotDirection' variable) is eluding my addled brain.
this is the code that happens, when i touch the mover.
I believe it's because the transform is in World Scale?
because the scale becomes relative to its parent
yeah i know why, but what does it calculate. can i reverse that?
also you might not want to parent it to a non-uniform scale
wdym what does it calculate ?
if you rotate your platoform you're gonna get weird skewing on it or player
your platform isn't uniform btw
im not sure what happens here. i know it has something to do with the non uniform scale of the moving platform.
You know what gravity should we use ?
i want to know what happens when i parent to something non uniform. how does unity get to those scaling numbers on the player.
probably. idk fully what you're asking.
attaching anything to non-unform causes weird distortion
plus what force should we use for a 2d game
well, what's the scale of the "Attacher" game object?
math
It will attempt to change the player's scale so that the apparent size of the player doesn't change
This can't be done in many cases.
yeah, i know that it is math obv š
Is the player parented to something before touching the platform?
nope
oh, wait
MovingPlatform is scaled, right
It doesn't matter that the Attacher object is uniformly scaled
it is numbers given above
Its parent is not. Therefore, the player's local scale will have to change when you parent the player to Attacher
If you scale the parent, that affects all of its children, too.
You should rearrange it like this:
Moving Platform <- [1,1,1] scale, player attaches to this
Surface <- any scale you want, has the renderer and collider
Attacher > Moving Platform and Player
i know, but how does unity get to those numbers.
I don't know exactly how it works, because it's non-obvious for rotated objects
An object whose parent is non-uniformly scaled gets distorted as it rotates.
If the parent scale is [5,1,1], then the player is always being stretched 5x in the parent's X direction
this is interesting. thx for that answer.
So as the player rotates, different parts of the player get pulled
whatever is lined up with the parent's X axis
I guess Unity tries to approximate a scale for the player that minimizes the change as you go from no parent to distorted parent
If the parent is uniformly scaled, it's easy
if you reparent to something at [2,2,2] scale, your local scale halves
your local scale is [0.5, 0.5, 0.5], which perfectly cancels out the parent's [2,2,2] scale
i see. thx ill fix that. was just curious what happens under the hood š
!collab
We do not accept job or collab posts on discord.
Please use the forums:
⢠Commercial Job Seeking
⢠Commercial Job Offering
⢠Non Commercial Collaboration
how can i make it so my character cant jump in the air? only until it hits the ground?
hi my problem is the next i try make when i push a button he be retired of my list and a other random button be add at the list but currently when i push my button that just remove without adding a new one why? my code:
{
if(boutonController.boutonListe.Contains(1))
{
boutonController.boutonListe.Remove(1);
int random = Random.Range(1,9);
while (random == boutonController.boutonListe[0] | random == boutonController.boutonListe[1] | random == boutonController.boutonListe[2])
{
random = Random.Range(1,9);
if(random != boutonController.boutonListe[0] && random != boutonController.boutonListe[1] && random != boutonController.boutonListe[2] )
{
boutonController.boutonListe.Add(random);
score++;
}
}
}
}```
Look up grounding. There are multiple ways. I generally use one or more raycasts pointing down and when they hit the ground, I set a bool called grounded to true
If it's false, you disable jumping
@swift crag fixed it š player stays uniform after leaving the platform. thx for your help
and this is the error i got : ```ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <6073cf49ed704e958b8a66d540dea948>:0)
bouton5.OnMouseDown () (at Assets/bouton5.cs:41)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
that is a weird piece of code
Then you're trying to get an element from a list with an index that is either negative or greater than the size of the list
It's a pretty clear error.
did you use | on purpose or you meant ||
(just asking, this is not related to the index out of range error)
there's no way it's on purpose
i use | for or
Options:
- Use OnCollisionEnter/Stay to detect collisions, and filter the contents to specifically detect ground.
- Use GetContacts to get all the contact points for your collider/RB, and filter to see if you have a valid ground contact.
- Raycast/BoxCast/Cast/CapsuleCast downward, and check if you hit ground.
- Have a separate collider below character as a trigger, and use OnTriggerEnter/Stay to look for ground.
- Define a region under your character mathematically. Then call Physics2D.OverlapAreaAll to check if any valid ground is found there.
why
why not
Because || exists
because || is boolean or
because it has a different meaning
what is the diference with | ?
| is bitwise or
| goes through each bit individually and gives the or for each in the final
if you want a boolean or you use ||
oh ok i see
so 0011 | 1000 makes 1011
| also works with booleans, it's just less efficient because it does not short-circuit
It's not bitwise in this context
it's only bitwise with numerical arguments
how isn't it bitwise or?
Because the parameters aren't numeric
Because this is a different context
but im talking in general
This is one of the reasons to avoid it by the way
because it behaves differently depending on whether your values are numeric or boolean
but no :( i have the right number of element in my list and i dont got negative number
In a conversation about something specific...
int x = 5;
int y = 6;
int result = x | y; // This is bitwise or
bool x = false;
bool y = true;
bool result = x | y; // This is logical or
It depends on the argument types
ik
| does not mean "bitwise", it's just how numerical types override this operator to make it bitwise
If that were the case, you wouldn't be getting the error. Try logging the length of the lists on the line before you attempt to access them
@summer stump please how can i block you, you're just a trolling clown
Gets so mad all the time lmfao. Really embarrassing for you
I'm sure thinking I'm a troll or clown will make you feel much better about being a bully
Typical behavior
Click my profile, then the three dots and click block
ok done lmao
It's best to avoid giving "general" information about a specific topic when the general information does not apply
š¤
my list is on public so i can see what i have in my list and i only have 4 value and 3 when i click
Doesn't matter log it anyway
you can see a list in the inspector
idk i didnāt realize | was even implemented for bools
but that might not be this list
why?
since people explicitly use | |
Because every single instance of this script has their own list
|| is almost always preferred.
i assume because of operator order
nothing to do with that. || skips the second expression entirely if the first one is true. It can therefore save performance. | always evaluates both operands.
is there a good tut to make game hub in unity where u can choose ur game
Because it is a 100% free minor performance boost and unambiguously ensures you're doing a boolean operation
oh. i didnāt realize | wouldnāt short circuit for bools
Probably just some buttons that change the scene or something
But not that I know of
That seems like a very project-specific feature so it's unlikely to find a tutorial for that specific thing
x || y will never give a different result from x | y. The difference is if you do x | SomeExpensiveFunction() vs x || SomeExpensiveFunction(). In the latter case, the expensive function can be skipped if x is true.
ok
ty
The only reason you wouldn't want to skip SomeExpensiveFunction is if it had some other side effect besides returning a bool
makes sense. I assume || also has a much higher priority when it comes to order of operations?
They ahve the same priority
so i have print him and he say me 4 :(
thatās unexpected
NVM I'm wrong, | is actually higher priority
Is that the last log before the error? Share the code again with the log in it to see where it is
idk if Iām reading it backwards. shouldnāt = have very high priority?
this is the code ```if(boutonController.boutonListe.Contains(1))
{
boutonController.boutonListe.Remove(1);
int random = Random.Range(1,9);
while (random == boutonController.boutonListe[0] || random == boutonController.boutonListe[1] || random == boutonController.boutonListe[2])
{
random = Random.Range(1,9);
if(random != boutonController.boutonListe[0] && random != boutonController.boutonListe[1] && random != boutonController.boutonListe[2] )
{
boutonController.boutonListe.Add(random);
score++;
}
}
}```
and in the log i got this : ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <6073cf49ed704e958b8a66d540dea948>:0) bouton3.OnMouseDown () (at Assets/bouton3.cs:41) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
nvm itās like the opposite
Where is the log
what you calling log?
Do I need "using System.Diagnostics;", because when I am using "Debug.log()", it gives me error CS0104 with "using UnityEngine;"
Ty for the help (I am very new to Unity)
that you said you added
No, remove it
oh the print message?
no you don't want System.Diagnostics
Debug.Log is in UnityEngine
so why it is there? isn't it by default?
No, it isn't
That will cause an error of ambiguity if you also have using UnityEngine
your IDE added it automatically when you typed Debug and you accepted it
Debug is also a class in System, which can be confusing
oh my bad ;p
Another one that may get you is using System.Numerics
UnityEngine has its own Vector3, and if you have that it can cause an ambiguity error
but obviously if youāre using Unity, you want Debug in UnityEngine and not in System
i just turned off all automatic using namespace things
VS kept adding the most random shit to my code, making it fail during build
why are you looking for specific entries in the List without first checking if those entries are actually in the List?
if i have procedurally generated terrain, how would i go about making the nav mesh
now i have CS0117 (Debug does not contain a definition for log)
Because it doesn't
Log not log
There's no such thing as Debug.log
how would i bake it through script after i generated map
Debug.Log
In this recorded live training session we show how to work with Unityās Navigation tools at runtime. We will explore the publicly available Components for Runtime NavMesh Building and look at how we can use the provided components to create characters which can navigate dynamic environments and walk on arbitrarily rotated surfaces, including ene...
build at run time
thanks
wait its removed
does the version of C# supported by Unity allow Records? I have been struggling with those.
anyway is dead simple
just bake it from the NavMeshSurface
It worked! I don t have errors but it doesn t print what i want to
if i have like a building system in the future
like when i place a wall
do i need to bake the nav mesh surface again?
thats kind of performance heavy
Show the code. Hard to help without seeing
if you have a dynamic environment with walls, obstacles etc, then yes
the whole nav mesh?
You can rebuild small portions
how can i insert it here like this?
no
yeah thats what i meant
so its possible
alright
i just want check if the first second and third value are not the same of the random number
!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.
Is that attached to an active gameobject in the scene?
... I don t think so
How to do that
Then it will not run.
You just drag it onto and object.
Or click addcomponent at the bottom of the inspector for an object
I recommend taking the pathways here
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
I did it with the main camera and now it worked on a capsule, thanks
ill take it ;-;
but you do not know if there even are a first, second or third value
I asked them to log it but I never got an answer back on that
typical
is it normal for a wire arc to have these like points
like its not a perfect circle
yes it's normal
it's made up of line segments
oh alright
so is this why i cant connect these lines to it?
technically its correct
we just cant see it?
Seems plausible
what does that mean
It's possible you're correct, but based on just eyeballing this it's also possible your lines/positions/math are slightly off
it looks good though
alright
could you check if i've done it wrong
just in case
its not that long
Hey, guys! Does dropdown panels have OnClick event cuz I can't see them, I can only see On Value Changed (int32)?
or maybe I cant add this event somehow?
There should be OnPointerClick in script
or any of the Event Triggers could work
Oh, ok thanks!
Yes but on pointer click is a class.
I mean if there is any method that does that
is a method*
been learning the unity input system and set up a way to rebind keys is there a way i can set a refrence to an action in inspector instead of making a ton of lines an going playerInputActions.PlayerMovement.action for each line. i was looking around and it seems like theres a way everting i found looks very convoluted
just use EventTrigger component
its in there
use the IPointerClick interface
or that
What is the event trigger?
its a component
will "random.range(1, 10)" generate numbers from 2 to 10?
no 1-9
alright thanks
Hey all!
https://pastebin.com/yXk6u2kS
can someone help me figure out why this thing (the raycast) detects the player (that's on the default layer), instead of the specified groundLayer?
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.
I tried bitshifting the layer that I wanted, I tried checking everything it collides with and comparing the collided obj's layer
I tried the using the log to get the ground layer
are you sure player is on default layer ?
yep, 100%
oh, how do you know its hitting player
I think I checked at least 50 times by now lol
debug.logs
on line 71
it says player
show the ground layer in the inspector
oh ok and how about your hierarchy
1 sec
and the player's inspector where he has the collider component attached to
what's the player's layer
default
can you show it
I really feel like it should be an obvous fix, bit I just can't seem to find it
Collision matrix is checked too
oh
i got it
it seems like that it did collide with it
Debug.Log(m_GroundHit.collider);
yep
seems like m_GroundHit.transform.... returns the object the script is attached to?
which kinda makes sense
but also doesn't
well, then I dont know why m_GroundHit.transform.gameObject would return the Player
maybe you have another script somewhere thats stuck on default š
well I have to check that, but I highly doubt it lol
yeah not sure lol im try to test it
i always use collider
and now that I've restarted unity it doesn't return the player at all
are you sure you weren't looking at some old logs or something
is case better than just a bunch of if's stacked?
naah, I always delete or comment out my logs after I'm done using them
Even made this scene to just have the player and the ground
you meanswitch vs else if
if you have bunch of if stackeds (like 5/6 if else statements) then you can surely improve your architecture
yea
to maybe use a dictionary or something else
you never use a real life dictionary ?
its the same thing
key : value pairs
serialized dictionaries will become your best friend
the documentation?
just type in "Unity dictionaries" or "C# dictionaries" into youtube
just google it
real quick, how would I check if the current gameobject is already destroyed? doing gameObject == null returns a missingref exception
assuming it does that because this.gameObject calls a backing field that tries to invoke the actual logic, but i want to check for null
i was thinking of a weird hack like caching the local gameobject instance, maybe that would work?
what do you need it for
you could make the variable nullable
so if its destroyed, and you set it to be null when it's destroyed
with like an event or something
you can do stuff
but if you use an event on destroy, you probably dont even have to check if its null
since the event would fire when it gets destroyed
If the object is never disabled, you could do a hack by checking if activeInHierarchy is false, since queueing an object for destruction immediately disables it
But that's assuming it's either active or gone. This won't work if being disabled is a normal condition for it
what exactly are you trying to do? we're just shooting in the dark tbh
It could be that when I opened unity for the first time (when it still logged the player as being the object detected) it console logged some sort of memory error with the editor
maybe that's what was causing it
Cause I just can't recreate it now
i'm certain it was an old log
But I made this scene just to test it
its literally just the player script running along with the input manager
that doesn't necessarily mean logs got cleared
How many do you need to check? Another option is to have an event that fires in OnDestroy
But that really depends on the use case
I set my console to clear the logs every time a scene runs
the object is destroyed
so its always cleared
It is a method that runs once
like I said, you could just fire an event when it gets destroyed
also the problem is that some code is running due to unitask, and it runs until even after the object is destroyed
explaining the use case would prob help get better solution
Yeah, once you call Destroy on it, it'll deactivate it right away, but the actual destruction happens later. If it's never disabled other than this condition, you can check for it being disabled. If it is, then it's in the process of being destroyed
explained above a bit more of why its happening
Can you link to it? I never saw it
the unitask explanation
heres the code
this runs at some point, but then something else triggers this gameobject to destroy earlier, but this is still running
i might just be able to cancel the task though tbh
maybe try/catch in this case?
alternative solution
i think this should hopefully work?
without the need to set a flag in ondestroyed
dejavu
looking into this more and found this https://forum.unity.com/threads/get-reference-to-an-inputaction-by-action-name.1020280/ which would work but is there a way to just select the action insted of this
Hey guys, I have this code that makes my enemies move.. but it seems that in diagonal they are faster even using normalized. Why is that? ```cs
private void Move(){
Vector3 MoveDirection = _player.transform.position - transform.position;
MoveDirection.Normalize();
_rb.velocity = MoveDirection * data.speed;
} ```
hmm should still work like this though iirc
normalize should handle magnitude
yesterday I was having the same prob with my player mov and I fixed like that: ```cs
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector2 vector = new Vector2(horizontalInput, verticalInput).normalized;
transform.Translate(playerSpeed * vector * Time.deltaTime); ``` here I go same speed even in diagonal
no clue about rb methods though
But now I need the same for the enemies but they use rb.velocity
that might work ?
I'm trying to select my button via script, but aren't working "OnEnable"
Only works when "Start"
I'm doing something wrong?
I attached a box collider to the bottom part of my player. I'd like to make the player object child of a moving platform when this specific collider is in collision with the platform (player standing on it), but I get some syntax error....
because it doesnt take BoxCollider as the parameter
btw you can just do _contentPanel.Select()
you can call Select() on any Selectable
actually it's probably OnTriggerStay I need, since I only use the collision box as trigger
Trying to instantiate this cs [SerializeField] private BulletBossTwo[] _bullet; but not being able. I get the error . I cant instantiate things inside an array ?
wdym instantiate things inside an array?
you want to add them into the array after instantiating?
no, I can do it another way but just wanted to know if I cant do it, because I get this error and not sure why.
but what are you trying to do
basically each bullet will go to a dif direction
show the code
and it is 4 bullets using the same prefab but the mov is inside the bullet script and I am instantiating it inside the boss script.. so I created an array to make sure they are 4 dif things . But I can try to do differently.
private IEnumerator shoot(float waitOne, float waitTwo, float waitThree, float waitFour){
while (true){
Vector3 _posRight = new Vector3(transform.position.x + 7.5f, transform.position.y, transform.position.z);
Vector3 _posLeft = new Vector3(transform.position.x - 7.5f, transform.position.y, transform.position.z);
Vector3 _posTop = new Vector3(transform.position.x + 6.9f, transform.position.y, transform.position.z);
Vector3 _posBotton = new Vector3(transform.position.x - 6.9f, transform.position.y, transform.position.z);
_bullet[0] = Instantiate(_bullet, _posRight, quaternion.identity);
yield return new WaitForSeconds(waitOne);
_bullet[1] = Instantiate(_bullet, _posLeft, quaternion.identity);
yield return new WaitForSeconds(waitTwo);
_bullet[2] = Instantiate(_bullet, _posTop, quaternion.identity);
yield return new WaitForSeconds(waitThree);
_bullet[3] = Instantiate(_bullet, _posBotton, quaternion.identity);
yield return new WaitForSeconds(waitFour);
}
} ```
movement of the bullets ```cs
private void Move(){
Vector3 _directionOne = new Vector3(_bossTwo.transform.position.x + 7.5f, _bossTwo.transform.position.y, _bossTwo.transform.position.z);
Vector3 _directionTwo = new Vector3(_bossTwo.transform.position.x - 7.5f, _bossTwo.transform.position.y, _bossTwo.transform.position.z);
Vector3 _directionThree = new Vector3(_bossTwo.transform.position.x + 6.9f, _bossTwo.transform.position.y, _bossTwo.transform.position.z);
Vector3 _directionFour = new Vector3(_bossTwo.transform.position.x - 6.9f, _bossTwo.transform.position.y, _bossTwo.transform.position.z);
if (_bullet[0] != null){
_directionOne = transform.position.normalized;
_bullet[0].GetComponent<Rigidbody2D>().velocity = _directionOne * _velocity;
} else if (_bullet[1] != null){
_directionTwo = transform.position.normalized;
_bullet[1].GetComponent<Rigidbody2D>().velocity = _directionTwo * _velocity;
}else if (_bullet[2] != null){
_directionThree = transform.position.normalized;
_bullet[2].GetComponent<Rigidbody2D>().velocity = _directionThree * _velocity;
}else if (_bullet[3] != null){
_directionFour = transform.position.normalized;
_bullet[3].GetComponent<Rigidbody2D>().velocity = _directionFour * _velocity;
}
} ```
you should try to learn to use for loops
there's no point in having an array if you do everything manually like this.
Isn't working :/
Aren't selecting :/
exactly, imagine if you have 20 bullets array, or 100 bullets
The code are getting the right object
True.. I know for loops haha I just didnt think about them. Normally for works great with arrays..
but my question was, I cant instantiate things inside an array ?
is BulletBossTwo a MonoBehaviour?
Anyway your error is obvious. _bullet is an ARRAY of things. Which makes it both:
- A very poorly named varialbe
- Not something you can call Instantiate() on
You can Instantiate an individual "BulletBossTwo"
but not an array of them
if you want to do something for each member of the array, use a loop.
ok thank you
As general advice, any time you find yourself "numbering" your variables or class names, such as:
_directionThree._directionFouretcBulletBossTwo_bossTwo
That's a STRONG indicator you should really be using arrays, lists and loops
or dictionaries! š
collections in general, and loops
Got it, thank you guys.
once i've discovered serialized dictionaries i can't dev without it
my serialized dictionary keeps breaking my data that I got from the forums
Debug.Log are retrieving the object, but aren't selecting in the screen
I've just been loading the data manually at startup
i can recommend the GenericDictionary
available on github free to use
I set a coroutine and it's works \o
Just need to wait 1 frame
Hey guys, I'm thinking about a Save System for my game.
I was thinking about making an interface to implement to every gameObject that needs to save / load data. Then, when saving the game I collect all items in the scene that have inherited the interface and call the save method.
I now have the data for all the scene, the thing is, to keep track of the data from other scenes I'll make an static persistent gameObject that contains all the variables to be saved from all scenes.
My doubt is the next. If I'm in a scene and I navigate to another for the very first time I would firstly save the current data in that static script and then when entering the other scene I would load the data I have in the hierarchy of that scene. If It's the first time I'm in that scene It would load uninitialized variables to the scripts in the scene.
To fix this I thought about doing a dictionary that tells If I have previously visited a scene, if so, then I can load, else not.
However I think I'm overthinking all this, could you bring me some light?
how do you get a public variable from another game object in a script ?
Reference the instance and get the variable.
Drag and drop reference if you can
Ooooooh thats what they meant
You could do a static variable, but be very careful, most of the time it's not what you want
That would mean a single instance of the variable, and modifying it anywhere will modify it everywhere

Found this error and am stunted;
"A local or parameter named 'obj' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter"
Pls explain
with this magnitude should work?
iirc thats how it was done
which line, show code
Looks like obj is already used in an enclosing scope. You can't use the same variable name twice, or it won't know which variable to use.
Hi there. Got a simple question because im in lack of knowledge. Im rotating an NPC towards another object which works well. I just wonder which value or calculation could be use to check if the rotation towards the target is acually done.
float singleStep = 1f * Time.deltaTime;
newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
transform.rotation = Quaternion.LookRotation(newDirection);```
drag and drop doesn't work, it seems to only add the transform component of the other object
I actually want variables contained in a script attached to the object
but when I try to use target = GameObject.find() and then do target.variable, it doesn't work
It will add the type you chose
Show the variable you tried to drag it into
For example, if you drag an object with script Foo on it into:
public Foo foo;
It will reference Foo
If you drag it into
public Transform foo;
It will reference the transform
if it doesn't work its either the wrong type chose or its a prefab and the object is part of the scene
the said platform is part of the scene, and the player is a prefab
if i do:
if(value >= 5)
{
//do something
}
else if(value >= 2)
{
//do something 2
}
let's say the value is > 5, will it only run the If, or will it also run the Else If?
is there a way to add script instead of Transfrom in the box "movingPlatform" ??
cuz I can only drag from the hierarchy with all objects and it's what it does
Only the first if, because the else will only be reached if value < 5
public int time_seconds = 5;
public List<spawnWhenCalled> objects;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
foreach (spawnWhenCalled obj in objects)
{
obj.Spawn();
for (int i = 0; i < time_seconds; i++)
{
foreach (spawnWhenCalled obj in objects)
{
obj.Despawn();
}
}
}
}
the obj.Despawn();
lol thats a lot of loops
so I just change name
I know lol
whats the point of this cursed code?
I explained exactly how to right here
Oh, if the player isn't in the scene at runtime, you need a different reference method. Grab it from wherever you instantiate it
well I know I must very dumb but cant figure out the right line for that (this one doesn't create a field in the inspector)
No, it will take the first statement which is true.. xd
First create a list of game objects each with a script attached( this is so I can access the script) and then if player collide it will ativate the objects and after a number of time deactivate the objects
But that if/else statement still does not make sense.
You should use If (value >= 2 && value < 5) {} elseif ...
How do you think I should uncurse it
using coroutine for the timer, loop through whatever scripts ig
id only need 1 loop tho š¤
coroutine has always confused me, well time to go back to the books
Why exactly might you want to save game objects and scenes? Shouldnt those things be persistent already? What changes about your scenes that need to be saved? And are you trying to save this data to file or some other way?
Yeah, I'll save it in a JSON. I want to track player's coordinates, npc's interacted, and basically all variables important for the game. Variables that tells me if an event has already happened or not. That's why I want to keep track of all data in the game and not only in the scene.
Is not gameobjects what I want to save, but some of it's variables.
Still got my math question. Nobody got an awnser ? š
Where?
Im rotating an object towards another object using: transform.rotation = Quaternion.LookRotation(newDirection);
which works well. But how can i verify if the rotation is done?
you can just use == no?
Like using the angle between the objects rotation and a vector3
afaik Quaternion overrides equality check
No, because the the other object got its own rotation which is allways differend.
Dot product between target direction, and transform.forward can do
If it's close to zero 1, then your directions are almost aligned
how do you get a vector that's relative to the world instead of a specific object ?
oh thought == does the dot product for you
transformPoint? or transformDirection :p
Do you have a short example on how to create the dot product?
might be that ty
Vector3.Dot(v1, v2)
Hey, I just really wanted to thank y'all for helping me on my project, I hope everyones having a good day :)
AIght. Thanks. That works.
Ah I see, a interface could work, maybe giving each npc, and other data you want to save an "ID" could work as well, then you only need to save the ID and the relevant data to some manager, the manager can then look for the NPC, item, etc with the ID and apply the data, unless you would rather have a different file for each NPC - you could also look into a pattern called "micro services", which could be a way to handle saving and loading without depending on game objects or scenes, and you could subscribe to scene load events to trigger the service, the service itself can keep track of what has or has not been loaded yet as well, if that is relevant - that is, if I am understanding the data your trying to save correctly
Hey, Im a bit lost right now. I'm researching about making my own libraries.
If I want to save some scripts I reuse in severa, projects, should I save them in a .dll file? Or what should I do?
You can. I honestly just copy the scripts directly over to my new projects asset folder
that or make your own packages
What's the advantaje of making a .dll file?
Sounds interesting the micro services thing, I'll research. Thanks a lot
Well, that's another option
It keeps it together, easy to move around, limits the scope, compilation won't include it
Make your own packages. That way, you can easily update and track changes . . .
Is there any way to share scripts between .dll files or packages? Or maybe between packages?
You know what I mean?
Well, a dll would kinda lock them together. You can reference things in it, sure. But it depends on your use case if that's the best way.
Honestly, I haven't done it that way before, so I don't want to lead you astray or tell you something wrong. This is all just what I've read and heard
Well, in case I would make some own packages... I guess I could have a folder with some shared scripts between all packages. Is this a good idea?
Hello, i keep getting an error code "error CS1003: Syntax error, ',' expected" but i tried everything and nothing worked
{
jumpBufferCounter = jumpBufferTime;
}
else
{
jumpBufferCounter -= Time.deltaTime;
} ```
i prob forgot something stupid ;-;
which line , which script ?
if its not underlined inside the code editor follow the guide
!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
Why does the parameter you're passing to Jump have a type included
XD
If that's not underlined in red, configure your IDE as noted above
Does jump even return a bool? Usually it would return void, as it is an action. Poor naming if not
yeah its not underlined
trying to fix that rq
then configure your IDE
i am gimme a min
is this the right method to close the game ? Didn't seem to work for me
EditorApplication.playmodeStateChanged i guess?
note that will work only in the editor and you need pre-procesor directives if oyu want to make a build with it
EditorApplication.isPlaying ?
alright thanks !
as u can see when the testVisionPosition isnt rotated in any way, the black line reaches the radius which is the white line
but when i rotate the testVisionPosition
it doesnt reach anymore
how would i make it reach?
like no matter at what angle it is
to just go until it reaches the visionRadius
does anyone here use any type of mentor/coaching service for unity development they'd recommend?
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
Self taught chest pound
alright this is what i got :P
ok good , now put something that makes sense there
š
got this error now ;-;
Error CS0029 Cannot implicitly convert type 'UnityEngine.Vector2' to 'bool'
correct vector2 is not a bool, you are using a vector2 where a bool should be
ah
How would I be able to make an object strafe arounda nother target? Similar to an enemy stalking the player around a perimeter?
thanks but is there a way I can fetch the vector?
I'm trying to use it alongside the navmesh pathfinding system
what vector
I would like the vector3 for the next position where they will move. In this case the next position to where they circle around the player. The arrow representing the movement the circle representing the target/player
if i change it into a bool it still wont work :/
what did you change to a bool
if (rb.velocity = new Bool(horizontal * speed, rb.velocity.y))
I don't quite follow. The Vector3 you pass is the position you want to rotate around
thats the thing vs is telling me to change
Do you know what a bool is
isnt it like a thing with 2 values likes (isGrounded && !somethingidk)
no
a boolean is a yes or no
RotateAround moves the transform but I only need the vector, maybe this approach is wrong actually and its more complicated than that. Im using a navmesh agent so I need the destination. Maybe i just need a position then have it curve to that pos

Does it make sense to set rb.velocity to yes
;-;
.position
no..
I would suggest going for a plain C# course before trying anything with Unity
For that matter, does horizontal*speed become "yes" or "no"?
So, you're trying to set velocity to the yes-or-no answer of horizontal*speed, neither of which make sense
fine š
a boolean is a type that can be either true or false
I was expecting either being ignored or some sort of resistance, so you actually got me there
XD
Either way, learning C# first will make learning Unity a lot easier
i was like im gonna throw myself in unity and learn everything there. XD
but yeah learning c# sound easier

!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.
im so confused on how dividing 73/100 = 0. I poll them right after each other. what the hell.
dividing an integer by an integer, will give you an integer
and it also rounds down
so 73/100 = 0.73 = 0
use floats
try casting them to float first
float myFloat = (float)int1 / (float)int2
(float)int1 is a temporary cast. It doesn't permanently change int1 to a float
int1 is still an int after the operation
i have no idea why i'm getting this or what to do about it
someone made a comment about it and i tried what i though the solution was with no improvement
you need to configure your ide. there should be red squiddles all over the text editor
You actually only need to cast one to a float. It will still do a float operation
there isnt any
the editor says its fine
Exactly, that's why you need to configure it
You can actually get a float as long as just the last value is cast to a float, so you can also do float = int / float, but both might add more readability
!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
i already did that a few days ago
If there are no squiggles, then something got messed up
@steep mistWhat is VoxelData ?
it looks like you're trying to access a type
and not an object instance
Oh, I thought it could be either. @true pasture i lied to you! Sorry
all the way back here navarone and boxfriend helped me through that so the IDE config is good
If there are no squiggles, then something got messed up
It can become unconfigured sometimes unfortunately
This is entirely unrelated to your issue btw. Your issue is probably due to lack of programming/C# basics understanding (not knowing the difference between static and instance members).
voxel data is my class that holds the shape and info for the voxel
you need to create an object instance.
I suggest you learn the basics of C#
and it doesnt probably help that i'm following along with an older tutorial
i have the basics but have never applied them in this way before
No it should be fine. You probably just missed something important in the tutorial.
Go back to where they write/explain this part of code and follow it through.
it could be as others in the comment have mention this particular area of code doesnt work. but i cannot figure out what it actually expects from me or where i went wrong. but i'll keep looking over to see. so far everything looks right.
if i still can't i'm gonna do a side by side comparison and try his github code
Share the tutorial and timestamp.
Or GitHub link(even better)
Is VoxelData a static class? (I strongly assume not) Otherwise you just need to get an instance of the class/struct
JOIN THE DISCORD SERVER!
This is part two of my tutorial series on coding a game like Minecraft in Unity. I think all the video issues I had in the first part are sorted! In this video we create our first chunk.
Any questions, feel ...
it is supposed to be a static class since it is not supposed to change after its been defined
Well I see it was haha
public static readonly int ChunkWidth = 5;
public static readonly int ChunkHeight = 15;
Make sure your VoxelData looks like theirs.
Oh haha, sorry. Laggy discord. I see that now
public static class VoxelData {
public static readonly int ChunkWidth = 5;
public static readonly int ChunkHeight = 5;
public static readonly Vector3[] voxelVerts = new Vector3[8] {
The file is not saved.
that was the first thing i checked, multiple times even
maybe i need to restart unity or regenerate the files incase it "forgot"?
maybe then i only saved the one?
(consider setting up your IDE properly)
it is, already did that a few days ago
boyfriend and navedea? helped me
It does seem configured though. I'd just blame VS code. Use VS if you want a more reliable ide.
could be
space is the only reason i use VS code
regular VS plus all the other crap i got on here takes up precious space to develop and make assets for games
I don't think it takes up that much space
a catch 22, have shitty code ide but more space for assets or less space but better code
when you save your files in regular VS, it sends a callback to unity
and updates everything
coulda sworn when unity offers to dl it for you it takes up 1-3GB
so you wont have issues like you just had
that's really hardly anything
when i'm wokring with 250 thats shrunk down to only 50 with all my art and editing software its a lot
WOMP WOMP
I see 804gb free over yonder