#💻┃code-beginner
1 messages · Page 689 of 1
- Show your code
- Make sure the script is not being disabled when you enter play mode
this is in playmode
added a debug.log in the update
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Check your console for errors too
scripts running now
i think i can fix it
probably
k fixed it
two references to the same compmonent that resulted in null reference
and stopped the rest of the code from running
not a code question but yeah that is weird. i've never noticed that before
yeah i reposted in #💻┃unity-talk
I dont know why, but the rotation of player doesnt really work
using UnityEngine;
public class TeleportTrigger : MonoBehaviour
{
public Transform targetLocation;
public string playerTag = "Player";
public GameObject ObjectToActivate;
public Transform playerObject;
public bool invertRotation;
private void OnTriggerEnter(Collider player)
{
if (player.CompareTag(playerTag))
{
float cameraX = playerObject.localEulerAngles.x;
player.transform.position = targetLocation.position;
float targetY = targetLocation.eulerAngles.y;
if (invertRotation)
targetY = (targetY + 180f) % 360f;
player.transform.rotation = Quaternion.Euler(0, targetY, 0);
playerObject.localRotation = Quaternion.Euler(cameraX, 0, 0);
if (ObjectToActivate != null)
ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
}
}
}
it is 5 am so i maybe shitcoded
my camera started jittering after i added the sprint mechanic
👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float originalSpeed = 12f;
public float sprintSpeed;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Start()
{
sprintSpeed = speed * 1.2f;
}
void Update()
{
//Code below checks is the player isGrounded
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Gravity
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
//Sprinting mechanic
if (Input.GetKey(KeyCode.LeftShift))
{
speed = sprintSpeed;
}
else
{
speed = originalSpeed;
}
//Moves the character with the character controller
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButton("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Can we use ChatGPT instead of reading the entire documentation while working on a 3d/2d game?
Who's going to stop you?
Why? What happened?
nothing, they mean there's nothing stopping you from doing that. if it works for you then go for it, just make sure to double check with the docs if something goes wrong
Ok
Can someone help please, why is transform not working
Your class isn't derived from MonoBehaviour
what?
If you don't know what that means you probably should try to follow the basic tutorials pinned in this channel
To learn how to write a script in Unity
Try doing this:public class PlayerCam : MonoBehaviour
Listen. Its been 14 months since ive used Unity
Same advice
Thank you though
any ideas?
"doesn't really work" is very vague
not really, it just doesnt invert the rotation of the player
hey, if i want to make a enemy spawn a couple of proyectiles in a row with delay, i should use a timer or a coroutine?
id start with a timer in most cases unless the logic is a lot simpler to write in a coroutine
oh! makes sense, well, thanks :3
holup, i been investigating and
what are ivokes, and why people dont use them instead of coroutines?
invoke is a string based method of calling a function. its bad because you dont want to use magic strings anywhere, and it uses reflection to call methods
theres no real need to use it
Would it be better to handle things like bullet penetration/ricochet and tumbling on the server and replicate it off to clients? Or should I simulate this on the client and hope the server also simulates something identical?
oh, so i better stick with coroutines and timers instead, isnt?
it would be better yea. Invoke is just worse in every aspect
btw, timers are better than coroutines, right?
better in a very small sense because coroutines allocate memory. this wouldnt be an issue unless you're starting a ton of coroutines. Sometimes its just way simpler to write logic as a coroutine
makes sense
especially if you have a lot of logic already happening in update, and this extra functionality needs to happen based on a condition, it can get messy
I tried to git push the Library folder in my project but it is said to be machine-specific and recommended to be ignored. Is it true?
yes
use the unity gitignore. it will be there as an option when creating a repo on the website or desktop app
there is more than just the library you want to exclude
Wow, there are really too many to include
Can also just get the gitignore from the general repo
This one is guaranteed to be up to date
im p sure unity is interpretting 99,999,999 in a float as 1e+08, which is just 100 million. is there a way to stop this?
unity is interpretting 99,999,999 in a float as 1e+08
no, that's how c# works withfloat(same for any other language using an IEEE 754 single-precision floating point number)
is there a way to stop this?
no, that's just floating-point imprecision. you could use adoublefor more precision, but unity might store it as afloatanyways.
it's adjacent to the reason this website exists https://0.30000000000000004.com
imma switch the > 999... to >= 1b in my code and it shouldn't be an issue anymore
thanks
guys can anyone tell me about this?? like am following code moneky tutorial and this is the error which is coming
Open the console window and fix any compile errors you have
Public class NameScript : MonoBehaviour
thxx guys! i smh found the fix !!
Hey guys. Im working on some kind of 3D Endless Runner (inspired by Race the Sun). I've build a system where i move the whole world around the player and not the player himself (exept for the y Axis, things like jumping and stuff). Now I switched from a Rigidbody to a Character Controller since I don't want to use unity physics anyway and the slope movement thingy is very useful for the things I'm trying to achieve.
The only thing that bug's me is that i cant lock the x and z position like I would with an rb. Sometimes when my player touches some Obstacles he gets pushed around. I tried working around that by always moving him back to 0,0,0 but tbh, I'm not very proud of this solution.
Does anyone have an idea of how I could lock my player or knows of a way to 'fake' something like that?
Any help is appreciated, thanks in advance :>
is there a way to make floats only have discrete values, for example it only changes in steps of 3 so if its value is 5.2 it snaps to 6
no, you can make that calculation yourself though
you can use unity's Snapping.Snap method to do it manually
damn i keep forgetting that's a thing
i see, thanks
you'll also want to make sure you're only using that where you plan to display the value, using it every time you change the value will mean you won't properly accumulate small changes
How do I use Graphics.DrawMeshInstancedIndirect? Currently, I'm drawing a lot of meshes by
- calculating matrices with a compute shader
- sending the data from the GPU
- using the matrices on the CPU to call Graphics.DrawMeshInstanced
This is a great little article about it https://share.google/OITG8vEP8SsFXfShI
GPU instancing is a graphics technique available in Unity to draw lots of the same mesh and material quickly. In the right circumstances, GPU instancing can allow you to feasibly draw even millions of meshes. Unity tries to make this work automatically for you if it can. If all your meshes use the same material, ‘GPU Instancing’ is ticked, y...
God I'm going to throw my phone in a river for doing this share.google nonsense 😡
Thanks. Really helped me understand what was flying over my head this whole time. Just lost power so it'll take a while to implement. Since I'm planning to use shadergraph to make this work, do you know any good tutorials on making grass?
Hi guys! I'm new to unity and I've been looking for a roblox-like camera style tutorial online but couldn't find anything or the camera didn't work for me (tried using cinemachine and scripting), and wanted to ask if anyone knows a tutorial for that kind of camera or knows how to do it themselfes 🙏
could you describe what kind of behaviour you want
you mean a third person camera?
yes
I want my camera to rotate by holding right mouse button, character to rotate in the direction the camera is rotating, and being able to scroll the camera closer of far from the character
i think there's an example asset for that on the asset store
👀
I'll check it out ty!
hmmm i know that get component is heavy but can i use it in ray casting context? like having hovering effect by getting the script component when cast mouse on it. i know IPointerEnter but i already used it for something else and there seem like no way to make it work on specific layer
getcomponent is fine and usually necessary, its just usually very avoidable via caching and easy for beginners to spam in heavy loops like update
just give usage of it some thought and if you think its the right call it probably is
yeah i heard it heavy but not sure how heavy its so i worry of using it abit
yeah people overexaggerate to drill it into beginners
hah yeah i had the feeling. thank
at most, its going through a list of components on your current gameobject. you need to use it if you want to get a component on a random object. I dont know how unitys pointer logic is coded, but you can be fairly certain unity needs to do similar logic to see if any object has a component implementing IPointerEnter. Aka GetComponent<IPointerEnter>
hi so i'm trying to figure out cinemachine, i got it installed but i cant really figure out what i'm meant to do
Why did you install it then? What are you planning on using it for?
Well, if you can't communicate your need, then naturally you won't know what you're meant to do because you'd have nothing to actually look up.
"very helpful" is very vague.
In any case, there are overview videos pinned in #🎥┃cinemachine.
Newbie question here, need help with the logic for a practice scenario, in a function that updates every frame (60fps), essentially to choreograph a 1-2 punch.
So I have something like:
public void OnUpdate(float deltaTime)
{
_countFrame++;
if (_countFrame % 60 != 0) return;
punchOne();
if (_countFrame % 120 != 0) return;
punchTwo();
}
If I’m not mistaken, punchOne occurs every second, whilst punchTwo every two seconds. How can I prevent the punchOne from occurring when punchTwo happens? I can imagine a boolean but wonder if there’s a more efficient way.
If you prevent punchOne from happening when punchTwo happens, it will alter between punch one and punch two with one second pause between them. Is that what it's supposed to do?
Yeah
How can i tell my bean to always spawn to the left of the car door no matter where the car is rotated?
if (_countFrame % 120 == 0) {
punchTwo();
}
else if (_countFrame % 60 == 0) {
punchOne();
}
Ah, simple and neat. Thanks
you should also use a timer rather than relying on frame count. you have no guarantee that this runs at 60fps
there are many ways, like you could even just have an empty gameObject be a child of this car as a spawn point. Or use something like this method https://docs.unity3d.com/ScriptReference/Transform.TransformPoint.html to go from a local position to a world position
oh yeah empty gameobject sounds goated thank you!
How can I do that? I was actually worried about framerate yea
Essentially the same way youre using the frame count, except with deltaTime
Well actually it'd be slightly different given you wouldn't want to check if it's equal to 1 second
This should be pretty close to what you're trying to do except with a timer
float timer = 0f;
int numPunches = 0;
public void OnUpdate(float deltaTime)
{
timer += deltaTime;
if (timer >= 1)
{
timer -= 1f;
numPunches++;
// check if numPunches is divisible by 2
// do your punch 1 or 2
}
}
Hey all, i need some help with transitioning to C# in unity..
for 4-5 years ive always been playing with lua in various game engines, meaning i can get a pretty nice workflow running in my head when im coding. Since lua is nothing similar to C#, i dont know where to start learning/transitioning to it. If anyone has some tips, steps, tutorials, anything helps. Thanks!
Thank you
There are beginner c# resources pinned in the channel. There are also tons of free resources out there for learning c# outside of unity. Plus !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I got it, i just dont know what key areas i need to focus on
Is it the layout? or should i learn basic keywords or whatever it is
You follow a structured course and focus on what they're teaching you. Or if youre pretty good at coding in other languages, just spend some time making console apps or random features to get used to the language. Google along the way
Thats what i did to learn lua lmao
Ill try find a decent course to get
Thanks for the help
if u interested in 2D games, in my college normally we will start with two projects
angry birds or flappy birds
dont ask why its all birds
For the punches to only happen once, I imagine id have to remove timer -= -1f; and add else if (timer >= 2) and put punchTwo in the latter instead?
no you'd constantly be punching then, since timer would always be >=1. the numPunches is how you keep track if its the first or 2nd
Hmm I don’t understand how it can limit it to just one time each
did you try implementing the logic i wrote in the comments? its identical to what you're doing with the framecount. instead of checking % 120 and % 60, you check % 2 and 1
I dont know why, but the invertion of player rotation doesnt work (it teleports the player without inverting his rotation)
using UnityEngine;
public class TeleportTrigger : MonoBehaviour
{
public Transform targetLocation;
public string playerTag = "Player";
public GameObject ObjectToActivate;
public Transform playerObject;
public bool invertRotation;
private void OnTriggerEnter(Collider player)
{
if (player.CompareTag(playerTag))
{
float cameraX = playerObject.localEulerAngles.x;
player.transform.position = targetLocation.position;
float targetY = targetLocation.eulerAngles.y;
if (invertRotation)
targetY = (targetY + 180f) % 360f;
player.transform.rotation = Quaternion.Euler(0, targetY, 0);
playerObject.localRotation = Quaternion.Euler(cameraX, 0, 0);
if (ObjectToActivate != null)
ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
}
}
}
(@eternal needle) Yeah that made sense as it would stay at timer >= 1 thus keeping them alternating.
In the other scenario where I just want them to occur once, I imagine it would be
if (timer == 2 && numPunches % 2 == 0) {
punchTwo();
} else if (timer == 1 && numPunches % 1 == 0) {
punchOne();
}
Wait that was redundant if I just needed the timer
this isnt going to work. the timer isnt going to be exactly 1 or 2, its a float. you just need to implement logic according to the comments in the example i provided
Ah
Is recoil for guns typically done with animation or through code? Because I'm thinking for consecutive shots, the recoil force should start from where the gun is, which could be mid recoil, not from it's starting position
add logs or step through with the debugger and see what these values are. if a value doesnt align with what you think it should be, you at least have more insight as to whats not working.
also you shouldnt really be reading the eulerAngles then using that to set the rotation. the rotation is stored as a quaternion, and many different euler angles can represent one quaternion. The value might not be what you expect
what is playerObject? you might be resetting the invertion with playerObject.localRotation = ...
the player itself
then yeah, that line undoes the rotation from the previous line if player.transform and playerObject are the same object
using UnityEngine;
public class TeleportTrigger : MonoBehaviour
{
public Transform targetLocation;
public string playerTag = "Player";
public GameObject ObjectToActivate;
public bool invertRotation;
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag(playerTag)) return;
other.transform.position = targetLocation.position;
Quaternion targetRot = targetLocation.rotation;
if (invertRotation)
targetRot = Quaternion.AngleAxis(180f, Vector3.up) * targetRot;
other.transform.rotation = targetRot;
if (ObjectToActivate != null)
ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
}
}
i tried this but it isnt working
what do you want to happen? this one is very different from the last one you sent
nvm, fixed it, input system was overriding the rotation value
thanks for help
aight as long as it works
I'm trying to get the angular data from the Meta Quest 2 controller, but it's not very reliable. Has anyone worked on this before?
im trying to make a projectile bounce off a wall but everytime it hits said wall it goes in the wrong direction
if (linecastHit.transform.CompareTag("BounceBox") & bulletCurrentStats.currentBounce > 0)
{
Vector2 reflect = Vector2.Reflect(bulletrb.transform.position, linecastHit.normal);
bulletrb.transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(reflect.y, reflect.x) * Mathf.Rad2Deg);
bulletrb.linearVelocity = new Vector2(Mathf.Cos(transform.rotation.eulerAngles.z * Mathf.Deg2Rad), Mathf.Sin(transform.rotation.eulerAngles.z * Mathf.Deg2Rad)) * bulletCurrentStats.currentSpeed;
print("Hit" + linecastHit.transform.name + ", " + reflect + Mathf.Atan2(reflect.y, reflect.x) * Mathf.Rad2Deg);
bulletCurrentStats.currentBounce -= 1;
}
how would i fix that
i think you're supposed to reflect the velocity, not the position?
and then you can just use that to the velocity instead of using the rotation
anyone know why the camera is not following the player?
probably needs a position control to make it follow as well as look
Cinemachine should do everything, but it doesnt work :/
It does work and quite well when you use it properly
#🎥┃cinemachine maybe for more help
ty, this helpt me realize im just stupid, working now <3
your MOVEMENTS script is trying to use the model variable, but you haven't set it
ow ok
it's pretty much just what the error said
yes, i thought the model variable is not a variable with name "model", but something different
sorry
what is generally the best way to make the light for a flashlight? if I put the light at the flashlight itself (which is in the bottom right corner of the camera), then the light doesn't illuminate the middle of the screen, which looks weird. if i put the light in the center of the camera itself, it looks weird too because the light isn't coming from the flashlight. is there a best practice for this?
This is the beginner coding channel. You should perhaps ask your light question in #💻┃unity-talk
Make sure to inform them what kind of light source you're using (directional, spot etc)
oh ty
I am wondering if doing a string comparison at start of a relatively spameable method is not ideal, would you call this an issue?
magic strings like this arent reliable. if possible use an enum instead
I am in fact, just that this method is already converting the enum into a string, since it has to display it as text
then the mapping for colour should still use the enum value
you can .ToString() when you actually need that
The enum to text is not exactly 1 to 1 conversion to the actual text I want to display
The class that instantiates this already has a switch to do the conversion to pass it as a string, should I change it to have it on this other class?
What kind of question are you asking? Is this in response to performance, design or? Relative to design, string comparison is not preferable. Relative to performance, it probably wouldn't matter - use the profiler.
Kinda both actually
Like what would be the preferred way to do this
should then have a mapping that uses the enum as a key and THAT contains the display text and colour
So relative to design, don't use string comparison. Use the enum to compare.
Alternatively, if you need more functionality or info than what an enum can do, use a scriptable object class instead
Almost anything but strings. Flexibility equates to undefined behavior and ambiguity.
Yeah, I just changed the place of enum conversion, I was just placing somewhere else since I was already using the namespace for it there lol
it shouldn't matter, strings literals are interned in most gc languages
and c++
you can use string interpolation to construct strings in a nicer way:
$"{initialAddenum}{value} {StatTypeToString(statType)}"
Yea c# will intern duplicate strings
I'd go with String.Create and spans here and get 0 alloc
Nobody said performance was an issue...
overkill much
im sure some niche situations require such measures but probably not right now 😆
Ah, does that matter much?
I just find it way easier to read this way
personal preference, both produce a new string
Its nice when doing something like $"{numA}/{numB}"
the object automatically does ToString()
completely different impl.. string interpolation should be faster in recent c# versions
with that in mind, it only matters once unity moves to coreClr
Does anyone know how to use Graphics.DrawMeshInstancedIndirect with shader graphs?
How do I get the buffer I set on my material then? I sent a list of matrix4x4 from a compute shader
Why does the jump animation behave like that? Also, the fall animation is supposed to play when I fall, but it's not happening
I think you need to do a workaround by writing the data to a texture instead of a g buffer
And use the sample texture 2D node
It's a little awkward
This is a code channel
Hey so I was working on a shooting enemy I want it to follow the player from a distance how do I go about it please
Seems annoying to have to commit all 3rd party assets to git, when you should just be able to check them out quickly with your project packages. :/
But now i'm trying to use github actions to build my project and it doesn't have things 😦
this question is pretty vague..here is a vague answer, use a pathfinding algorithm
Its a top down 2d game with basically infinite procedural generation so I don’t think it’s advisable or possible
still vague.. plenty of games made with procedual generated
so you generate it at runtime
Then take a finite part of the world. You said it yourself, that it would follow the player from a certain distance, so the search space is finite.
Either way it’ll still be jittery because my current method is basically the same thing
I’m using a physics2d overlap circle to check
check what?
The enemy checks for the player with it then when it detects the player it moves to it at stops at X distance from the player but now each time the player moves again the enemy try’s to keep up chasing jittery movement
Then move the enemy only if the player moves a certain distance away from the enemy, not immediately when the distance is larger than X.
I’ll try that and see
Or add a delay, or smooth out the movement over time.
{
Vector2 WasdDelta = inputManager.WasdDelta;
Vector3 forward = new Vector3(Orientation.forward.x, 0, Orientation.forward.z).normalized;
Vector3 right = new Vector3(Orientation.right.x, 0, Orientation.right.z).normalized;
Vector3 moveDir = (forward * WasdDelta.y + right * WasdDelta.x).normalized;
float currentSpeed = walkSpeed;
if (WhatIsGround)
{
if (WasdDelta.magnitude < 0.1f && moveDir == Vector3.zero)
{
StateMovement = MovementState.Idle;
}
else
{
StateMovement = MovementState.Walking;
}
if (inputManager.IsKeyDown(InputManager.InputAction.Run))
{
currentSpeed = runSpeed;
StateMovement = MovementState.Running;
}
Rb.linearVelocity = moveDir * currentSpeed;
} ```What could be causing the character to not stop instantly?,From what I see, it takes a while to go to idle and not because it is not instantaneous.
Idle as in stopped? Or moving at walk speed?
If no input is received, switch to Idle and stop instantly."
I don't see any logic related to this though. You still assign a walk or run speed to the linear velocity
Sorry, the last thing I did didn't work, and in the idle part when Wasd delta doesn't receive one, its magnitude will be 0 and if that happens we force it to stop
but what happens is that instead of going from Running to idle when no input is received, this happens: first it is Running, then Walking and finally idle and it takes a few seconds before being idle (a second but it is noticeable) so it takes a while to stop
how is WasdDelta set?
hey guys i just wanna ask what would be a simple way to make a drag system where i can just hold left click on a cube and drag it around
drag it around in what way ? there are dozens of ways to do something like this
easiest is probably via EventSystem callbacks, e.g. implementing IDragHandler https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IBeginDragHandler.html
i was thinking a karlson type drag
no idea what that is
do you have an example?
to click and move objects around using the mouse
GetAxis has some smoothing by default, try GetAxisRaw instead or adjust the smoothing for those axes in the input manager
ooo ok
make a bool true with the rigidbody stored when picked up you can use fixedupdate to move the cube from oldPos to newPos
ok i will try this
Is there a way to prevent Graphics.DrawProcedural and other similar functions from executing on a specific camera? I have a camera that simply renders black because of split screen.
private IEnumerator WaveFunctionCollapse()
{
while (cellsToBeProcessed.Count > 0)
{
yield return new WaitForSeconds(0.01f);
SortCellListByDomainCount();
currentCell = cellsToBeProcessed[0];
currentCell.CollapseSelf();
currentCell.changed = true;
if (currentCell.currentState == CellStateName.red)
{
foreach (var n in currentCell.neighbours.Values)
{
n.RemovePossibility(CellStateName.red);
}
}
cellsToBeProcessed.Remove(currentCell);
UpdateAllCells();
}
}
Been working on this random map generation based on the wave function collapse method, this is sort of a dumb version of that algorithm right now. I can right now create patterns such as the image, but I only have one rule, red can't be next to red.
But for example, I would want rules such as "blue must be next to at least one other blue" . But I can't really wrap my head around it, does anyone have good examples on how this is done?
unless you have a question, most messages like "hi" or "hey" will go ignored
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Interactor : MonoBehaviour
{
public float interactDistance;
public PlayerInput playerBinds;
private InputAction interact;
public Camera cam;
[SerializeField]
private LayerMask interactableMask;
private void OnEnable()
{
interact = playerBinds.Player.Interact;
interact.Enable();
}
private void OnDisable()
{
interact.Disable();
}
private void Update()
{
if (
Physics.Raycast(
cam.transform.position,
cam.transform.forward,
out RaycastHit hit,
interactDistance,
interactableMask
) && playerBinds.Player.Interact.IsPressed()
)
{
Debug.Log("Interact Successful");
}
}
}```
Does anyone have a clue on to why the if statement in Update() would cause an Object is not set to an instance of an object error?
Either cam , playerBinds, playerBinds.Player or playerBinds.Player.Interact is null
Ooooh ive worked something similar for my combat system
My solution was to make an array with 10x + y being the number the gameobject is stored in
For example if a blue tile is at (2,7) it would be myGameObject[27]
Although if you're using a 10 by 10 grid you're probably gonna have to find a different solution
hey guys, very beginner question but I'm not sure why my override method aren't being called - the base versions are instead?
oh, sorry if I'm interrupting haha
Heres 2 ways i think you could do it
- You put the different colored tiles in seperate arrays and check every single one
- You add colliders in a + shape and shoot a ray at it and check if it collides with anything (maybe add an interface to each type of tile and check for that?)
Gonna need more deets on that
I basically call a function like this unit.MoveTowardsWaypoint();
the base function is ``` public virtual void MoveTowardsWaypoint()
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Vector3.SqrMagnitude(targetPos - transform.position) > 0.05f)
{
RotateTowardsWaypoint(Quaternion.LookRotation(targetPos - transform.position, Vector3.up));
}
for (int i = vehicles.Count - 1; i >= 0; i--)
{
vehicles[i].CheckLocalPosition();
vehicles[i].vehicle.CheckCollision();
}
}```
{
for (int i = vehicles.Count - 1; i >= 0; i--)
{
vehicles[i].vehicle.MoveAndRotateTowardsWaypoint();
}
}
the override function's like this - but in-game, the stuff in the base function's being called instead
is the unit the type of class that override function is on?
this is a code design question
currently i have a join request system, backend is operational and there are no problem on sending/reciving data
however, the system is driven by two UI , one big one small
- big one can only be opened when player click on the small one, no other ways
- either of them can only exist one, no duplications
- there can be unlimited requests as long as the room is not filled
- each requests should have separated timer , terminated after 10 seconds received
my question is, with this kind of design , u must store it somewhere else when u received it right? and u need to think of what to store
yes, so there's a base vehicle unit and a child naval unit
u think i should use ..... a model class + unscaled time?
they move differently, I have a vehicle state machine with a reference to a vehicle unit it's attached to
referenced like this
Dictionary <class,float>
where model class is the response , float is the unscaled time
Hello, i am a programming beginner and I would like someone to review my save/load game script
Just to give me advice, if its bad/good.
Where could I post my code snippet?
weird function and variable names
no idea what Loc_Inv... is
make it more readable
apart from that seems okay
Oh yes I understand, yes i put weird variable names
Basically I want to use it to generate random mazes
I got something working, not perfect since it generates dead-ends but we're getting there
You don't need to check if Count > 0 inside the for loops. The loops don't do anything if the count is 0
personally i create classes and store data there, then simply serialize that class
then onLoad i grab the json file and store that into the same class
void OnSaveSystem(int index)
{
playerData.dateTime = DateTime.Now.ToString();
string playerJson = JsonUtility.ToJson(playerData, true);
File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/PlayerData.json", playerJson);
string weaponsJson = JsonUtility.ToJson(weaponData, true);
File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/WeaponsData.json", weaponsJson);
string droneJson = JsonUtility.ToJson(droneData, true);
File.WriteAllText(Application.dataPath + $"/StreamingAssets/Save{index}/DroneData.json", droneJson);
}
dont know how standard it is but works well for me
Also you can convert the keys and values directly to lists, no need to do that manually
@keen dew Is that a function or?
Becuase I use a dictionary for inventory, and dictionary cant be serialized to json
Post the !code as text, I'm not going to retype it from the screenshot
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
public static void SaveGameData(bool BASE_SAVE)
{
bool dirExists = System.IO.Directory.Exists(path);
if (!dirExists)
{
System.IO.Directory.CreateDirectory(path);
}
GameData gameData = new GameData();
GameManager gameManager = GameManager.ReturnSelf();
for (int i = 0; i < gameManager.GlobalInventoryDictionary.Count; i++)
{
if (gameManager.GlobalInventoryDictionary.Count > 0)
{
gameData.Glob_Inv_Scr.Add(gameManager.GlobalInventoryDictionary.ElementAt(i).Key);
gameData.Glob_Inv_Int.Add(gameManager.GlobalInventoryDictionary.ElementAt(i).Value);
}
}
for (int i = 0; i < gameManager.LocalInventoryDictionary.Count; i++)
{
if (GameManager.ReturnLocalInventory().Count > 0)
{
gameData.Loc_Inv_Scr.Add(gameManager.LocalInventoryDictionary.ElementAt(i).Key);
gameData.Loc_Inv_Int.Add(gameManager.LocalInventoryDictionary.ElementAt(i).Value);
}
}
if (gameManager.knownRecipes.Count > 0)
{
gameData.knownRecipes = gameManager.knownRecipes;
}
if(BASE_SAVE)
{
foreach(var FAB in SystemManager.GetSystemManager().fabricatorArray)
{
FabricatorData NEW_DATA = new FabricatorData();
NEW_DATA.isFabricatorOperational = FAB.isFabricatorOperational;
NEW_DATA.isWorking = FAB.isWorking;
NEW_DATA.storedAmountOfItems = FAB.storedAmountOfItemsToFabricate;
NEW_DATA.FAB_ID = FAB.fabricatorID;
gameData.FAB_DATA.Add(NEW_DATA);
}
}
string json = JsonUtility.ToJson(gameData);
System.IO.File.WriteAllText(path + "/gameData.json", json);
}
most object pool video i seen on youtube implement their own pooling, why is that? is unity's object pooling implementation bad
gameData.Glob_Inv_Scr = new List<?>(gameManager.GlobalInventoryDictionary.Keys);
gameData.Glob_Inv_Int = new List<?>(gameManager.GlobalInventoryDictionary.Values);
And the same with Loc_Inv_*, Replace ? with the correct types
unity didn't even have a built in object pool class until 2021
do you have any issue using it ?
no. but my point was that the reason you see so many object pool videos that implement their own is because the feature simply did not exist in most versions of the editor
Thank you
ok thanks i will stick to unity's
wont this create a shit ton of entries if he has a lot of values?
I'm not sure what you mean. It creates as many entries as there are values
The end result is the same as in the original code
yea ig
a bit out of context but where do the games on steam keep their saving files?
Wherever they want to
whats the common place I can search at?
There isn't one
Look up [Game] PC Save location on google and do that
They can go literally anywhere. AppData, Documents, User folder, Registry, ProgramData, all sorts of places
found it on AppData
thx
Next time, just google it. You'll find the answer in seconds
i have several nested if statements. if ANY of these if statements are false, i need to do something. is there a way to do this that is neater than just including else statements after every single if?
Bool variables
Show the code if you want more specific advice
Don't nest them, and use a bool flag to determine the results.
bool checkPassed = true;
if (condition 1)
// Do this
else
checkPassed = false;
if (condition 2)
// Do that
else
checkPassed = false;
// ---
if (!checkPassed)
// Something failed
why does the sprint mechanic make my camera jump sometimes
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float originalSpeed = 12f;
public float sprintSpeed;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Start()
{
sprintSpeed = speed * 1.2f;
}
void Update()
{
//Code below checks is the player isGrounded
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//Gravity
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
//Sprinting mechanic
if (Input.GetKey(KeyCode.LeftShift))
{
speed = sprintSpeed;
}
else
{
speed = originalSpeed;
}
//Moves the character with the character controller
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButton("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Can you explain what you mean by the camera jumping?
Also how does the camera move?
(one other issue - you should not be calling Move twice per frame. Sum the vectors and call it once)
thank you i mean sometimes it looks like it slightly teleports also thank you for the advice
hi guys
i have a problem
i just downloaded unity
and guider on youtube opened script with smth like that
but when i doing all the same
it opens notepad
can someone help me with that
Hi man all you have to do is download a code editor. I prefer Visual Studio Code looks like he is using Rider if you want to use that.
Develop .NET, ASP.NET, .NET Core, Xamarin or Unity applications on Windows, Mac, Linux
Thanks
Also don't crosspost you end up getting the same answer in multiple places and wasting more of people's time
!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
• :question: Other/None
Thanks
Guys, I'm going through absolute hell trying to create and IK system for my fingers for grabbing terrain. It's all kinds of uneven and I've tried different methods but they all have cases where they don't work perfectly
would a finger ragdoll system be a stupid idea in this case?
but I guess I would need gravity to be applied in self space of the hand (due to rotations)
hey im really struggling to on how to make top down melee combat are there any tutorials on this?
That's a vague question, break the problem down into smaller problems and find out which thing you don't know how to do
any guesses on why my score isn't updating? I assigned the tmp in the editor
{
private Rigidbody2D rb;
public float moveSpeed;
Vector3 lastVelocity;
private int score = 0;
public TMP_Text scoreText;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
float randomNumX = Random.Range(-1.0f, 1.0f);
float randomNumY = Random.Range(-1.0f, 1.0f);
rb.linearVelocity = new Vector2(randomNumX * moveSpeed, randomNumY);
}
// Update is called once per frame
void Update()
{
lastVelocity = rb.linearVelocity;
scoreText.text = score.ToString();
}
void OnTriggerEnter2D(Collider2D collision)
{
Scene scene = SceneManager.GetActiveScene();
SceneManager.LoadScene(scene.name);
}
private void OnCollisionEnter2D(Collision2D other)
{
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, other.contacts[0].normal);
rb.linearVelocity = direction * Mathf.Max(speed, 0f);
moveSpeed = moveSpeed + 5;
if (other.gameObject.tag == "paddle")
{
score++;
}
}
}
generally you should not set the text every frame, only when it changes
(also wouldn't you want to have lastVelocity updated in FixedUpdate?)
anyways i digress
have you tried debugging stuff? does the score actually change? is the tag check passing?
i just checked and the score doesn't increase for some reason
either the collision message isn't being called or the condition isn't passing
is there any way to make a variable visible to other scripts while not visible in the inspector for unity?
[HideInInspector] attribute
👍
or make it internal instead of public
probably shouldn't do that one, but eh just throwing it out
you should figure out if you want the variable to not be in the inspector, or not be serialized as a whole
Hello
I want to create a type that will store all colliders2D of a gameobject and its childrens. So I wanted to create a struct serializable like this :
[Serializable]
public struct PlanAttributes
{
public GameObject Plan;
public List<Collider2D> PlanColliders;
}
But, I don't know if it is better to use a class instead of a struct. I want in awake to store in the list all colliders of the plan. What is the best approach to do that ?
generally you want to use class if you have reference types in it
but really you can use both, is just that some people say and microsoft documentation, you typically would have structs only contain immutable data
What is references types and immutable data ?
A vast majority of your objects should be classes. Especially if you arent extremely familiar with coding, dont worry about structs tbh
classes are reference types, as they are like pointers to data in memory, the immutable rule is broken pretty often, immutable is typically data that don't change
i don´t think you would be so conserned, to care about wheter you would use heap or stack
unless you are planning to have hundreds or thousand of these structs
if you want to know more https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
but yeah you should not be too worried and stick to class when in doubt lol this is #💻┃code-beginner anyway
{
if (quickstart)
{
yield return new WaitForSeconds(3);
returnToWander();
}
else
{
returnToWander();
}
}```
so i want to stop the above coroutine, but my ide states that i need to call `StopCoroutine(lostPlayer());` with an argument. does it matter what i put as the argument? i mean im stopping the coroutine so it doesn't matter
StartCoroutine returns a Coroutine, use that
Coroutine myCo;
...
myCo = StartCoroutine(Whatever());
..
StopCoroutine(myCo);```
Why does my sprite pause when I click space to jump in mid air?
Im trying to recreate flappy
but I want the sprite to jump the same amount if I click space again, so how do I stop this slight pause from happening?
I feel like its trying to negate the downward force
reset its vertical velocity to 0 before applying force when you jump
why don´t you just try it out
now the sprite just slowly drifts down to the platform
read again what boxfriend said
thank you
and thank you lol
glad you could fix it
you got errors in your code, why not post some code so we can say more
Clear the console, see what errors stick around
I'm a beginner and want to to explore creating a login system. Can someone give me the name of location to store authentication data within unity? I'm happy to do my own research but I just don't know the terms to look up.
wdym a "login system" thats pretty vague.
You typically need a server for this, you wouldn't store this locally
I am referring to authenticating with a server. I'm coming from the web dev world...we have session. I don't know what unity uses.
depends how you authenticate, typically you would store a token and if done properly a refresh system for such a token
that is exactly what I would like to do
PlayerPrefs is a good location
this is also what unity uses for their auth system
I have the login scene/web requests all set
Ok great. I will research player prefs. Thank you so much for the link too. I will read it right away.
Can I just get a quick pointer on how to handle refreshing?
I assume that is not part of the PlayerPrefs system
not the savest way to save sensitive data like that
PlayerPrefs is just a location in your computer, it has 0 to do with authentication
refresh is done like every other system does it on the web
check if token exist, check the expiration date and if you auto refresh and expired, then use a refresh token
i would not recommend making your own when premade solid solutions already exist
@rich adder : Thanks
errore
you've been answered multiple times what to do and you promptly ignored it and now are asking the same thing in crossposting multiple channels..
no one answered me
🤔
what about it ? you still ignored it and posted the same thing again
what post
also what does this have to do with being in the probuilder channel
About 14 minutes before you reposted the question
ok i closed dc
you haven't even shown the actual error
how
look im new new like i dont know any thing
how do you stay alive ?
So if you literally do not understand the words people are saying, how do you expect to actually get an answer
sorry but i did not understand what did u say
ty for answer
stop what you're doing and start here
https://learn.unity.com/pathway/unity-essentials
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
thats fine but you are jumping too far ahead if you don't even know the basics of the editor, start with the structured courses on learn
🤦♂️
what now
you're showing the same image with 0 new information
you aren't giving us any info to work with at all lmao
whatya think?
ohhhhhhh
i just opened i this video and he said to open the demo and i will work or somthing
This is the final demo, where we show off the completed 1st and 3rd person controller. It fully downloadable for free, and I've made the source code available as well.
This is part of a free complete course for making a player controller, I hope you enjoy it!
··········································...
this but it gave me this error
that i showed u
what good is a premade asset if you have no idea what to do in the edtior
i just what to do a third person shooter
How I can made for my game a exit system?
so start learning the editor
Esc + exit
a "exit system" ?
explain what that means
I want to implement momentum based dashing into my game, can you guide me in the right direction on how to make that work? I'm also using the unity character controller.
I mean, if the player click a botton, the game close
Idk if i explain my self well
thank you nav soo helpful
Character Controller is not going to be very good for "momentum". You'll need to do all the math yourself.
So, basically,
https://www.mathsisfun.com/physics/momentum.html
Math explained in easy language, plus puzzles, games, quizzes, videos and worksheets. For K-12 kids, teachers and parents.
I was thinking of switching, I want to make something akin of ultrakill.
Thx
I mean..not sarcastically its been asked over and over and surely you can find many resources on this, its not something you can just explain in a discord message.. its literally an entire system w lots of math involved lol
guys, i need some help, how can i make the sliders here "predict" the color based on what the combination is? Something like how unity works?
i already have the shaders all set up, JUST 2 COLOR INPUTS , all i need is just to calculate the colors, how would i begin?
it's a gradient - for example on red, it's (0, G, B) to (255, G, B)
taking the current values of green and blue
ah that opened my mind lol, thanks
why are my animations so weird?
this is a code channel. also mkv does not embed in discord
ok thank you man
Why does my camera rotate a bit even when its rotation is 0?
using UnityEngine;
public class TeleportTrigger : MonoBehaviour
{
public Transform targetLocation;
public string playerTag = "Player";
public GameObject ObjectToActivate;
public bool invertRotation;
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag(playerTag)) return;
other.transform.position = targetLocation.position;
var look = other.GetComponentInChildren<FirstPersonLook>();
if (look != null)
{
float currentYaw = look.transform.eulerAngles.y;
float newYaw = invertRotation ? currentYaw + 180f : currentYaw;
look.SetYaw(newYaw);
}
else
{
Quaternion targetRot = other.transform.rotation;
if (invertRotation)
{
targetRot = targetRot * Quaternion.Euler(0, 180f, 0);
}
other.transform.rotation = targetRot;
}
if (ObjectToActivate != null)
ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
}
}
Should I get Altaruna or try to do my own networking thing?
Is there anything you like about altaruna in particular compared to other networking solutions?
not sure, i don't know any other networking solutions
i like that it's free for most things
gonna need more details. were there any error messages? is it within an if statement?
it'd help if you sent the !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Take a screenshot of the console error from the Unity Editor
Normally you'd need to save a copy of the position (Vector3) from the property, modify it then assign it back.
For example: cs var position = cam.transform.position; position.z = -10; cam.transform.position = position;The position property returns a copy of the position Vector3 so modifying it doesn't have any effect on the actual position. In fact, it's a value only and not a variable thus why you should be getting an error about modifying a value and not a variable or something.
ok thanks
camPOS = cam.transform.position;
camPOS = transform.position;
camPOS.z = -10;
cam.transform.position = camPOS;
Is that better?
wait nvm I got it
thanks again
Reminder that for better future support, it's always preferred to provide a screenshot of the console error rather than the error code. Nobody really remembers error codes and it lacks the extra details necessary to properly debug a problem without having the query more information.
https://docs.unity3d.com/6000.1/Documentation/Manual/Console.html
@wicked fiber
Yeah, I realized that after I sent it. Sorry
Who can help me solve this problem?Is this a lost map?
As a beginner, I don't know much about it. I checked the relevant documents, and there are maps in them, but I still don't know how to solve this problem. I hope to get your help
There's no modding discussion allowed on this server; find a tarkov modding server and ask there
Hello, I was going through this reference https://docs.unity3d.com/6000.1/Documentation/ScriptReference/MonoBehaviour.html and found this: (Image 1- Awake highlighted text). Here it says Awake is called when the script is enabled. However when I put it to test, so I created a test script with Awake function and disabled the script component, while the gameobject is active. Awake is getting called even when script component is disabled. (Image 2 - Unity editor, look at inspector, TestScript is disabled, and Awake being called in Console.)
Now my question is, how can Awake be called if the script component is disabled?
You disabled it when and where?
When the GameObject is active, Awake is immediately called . . .
Before playing the game in Inspector
So it doesn't matter if script is enabled or disabled?
From the docs:
Unity calls Awake on scripts derived from MonoBehaviour in the following scenarios:
The parent GameObject is active and initializes on Scene load
The parent GameObject goes from inactive to active
After initialization of a parent GameObject created with Object.Instantiate
Not sure why "enabled" is written in the description as it'll load without the script being enabled.
Probably something to be edited.
My apologies, I came here before going through Awake documentation.
its weird that its seperate from those 3 rules but it totally does consider script enabled afaik?
No, it doesn't matter if the script is enabled or not . . .
I'm assuming it's meant to be something like
Unity calls Awake when script instances are loaded
Unity calls Awake on scripts derived from MonoBehaviour in the following scenarios:
...
Awake is only affected by the GameObject's active state . . .
if thats true that doc just outright lies then lol
It wouldn't make sense because if you only have an Awake method, you cannot enable or disable the script, so how could it be affected by that?
Hold on, I found another one. In https://docs.unity3d.com/6000.1/Documentation/ScriptReference/MonoBehaviour.Awake.html documentation, it says (Image 1). So, can an inactive gameobject call Awake??
you can enable/disable scripts before they spawn or via inspector?
No, it explicitly states that the object must be active (which is different from a component being enabled)
Yes, but only if they have a Start or any Update method . . .
No, because it's inactive . . .
only for the inspector one right? you can still toggle script activity via code?
public class Test : MonoBehaviour
{
private void Awake()
{
Debug.Log("Hello world");
}
}```
the enabled flag appears when you use any one of the unity magic methods, awake included
You are right though, just tested it. I think that doc needs to be changed
Unity calls Awake when an enabled script instance is being loaded. is incredibly misleading
It does not appear for me . . .
its kinda like saying "fire will burn any alive person"
like yes that is true
but fire absolutely burns dead people too
on what version of unity? That's so strange
didnt pop for me until update
huh
im assuming the rules apply to start too so it only really shows up for update
Can you try on a empty gameobject?
It's always been like that for me. I'm currently on 2022.3 . . .
works on my machine lol
Same, i'm also on 2022.3.40
I'm on unity 6, maybe it changed then
No, Start will allow you to enable/disable a MonoBehaviour script . . .
I ditched 2022 as soon as 2023.1 came out
I tried it for a game jam and the new Awaitable class was too good to live without
death to coroutines ✊
They are different, but I typed the wrong thing. I should've written the script (MonoBehaviour) . . .
but... but... I kinda like coroutines..🥺
async/await is the same but better in every way 🙂
I'm not on the latest Unity 6 but perhaps it may just be with the current latest release 
Relative to the enable component checkbox and Awake
instead of
IEnumerator WaitForThing ()
{
yield return new WaitForSeconds (1);
Debug.Log("aaa");
}
void DoSomething ()
{
StartCoroutine(WaitForThing);
}
```it is now
```cs
async void DoSomething ()
{
await Awaitable.WaitForSecondsAsync(1);
Debug.Log("aaa");
}
``` no more StartCoroutine, you don't have to be on a monobehaviour (or using a singleton runner) for everything you want to happen over time
and you can use async methods in await
and you can return values
re: not using monobehaviours, do all the old things that needed coroutines work for that too?
and it has cancellation token support, so you can cancel them
iirc coroutines are on the main thread whilst async and await are not.
Btw what would be a good channel to ask this in?
we have WaitForSecondsAsync, FixedUpdateAsync, EndOfFrameAsync (lateupdate), NextFrameAsync, then new BackgroundThreadAsync and MainThreadAsync to easily switch between threads
wrong 🙂
oh actually do awaitables/async auto die with monobehaviours in this comparison or do you need to manage that yourself
if you use the Awaitable class it's all on the main thread
unless you explicitly call BackgroundThreadAsync
you manage it yourself
I'd say that's a notable con but still excited to mess with that eventually
Ah right, this would only be true if you're starting a new task..
Only if you use the specific API for doing it; which you just wouldn't do
if you're familiar with cancellation tokens it's pretty straightforward
void OnDisable ()
{
_cancellationTokenSource.Cancel()
}
it's a little bit extra sure
but the benefits vastly outweigh that imo 😂
and coroutines are still there if you enjoy putting StartCoroutine everywhere 😉
you would use the destroyCancellationToken if you already had a MonoBehaviour
oh wow I didn't even know that was there
that's excellent
yeah in that case all you need to do is cs await Awaitable.WaitForSecondsAsync (destroyCancellationToken);
(or any of the other awaitable methods)
this one feature alone made 2023/6 worth the upgrade 😂
I can't tell you how much I hated having wrapper methods that just StartCoroutine a different method, and/or a singleton to manage them for when I needed them in a static or plain C# class
I can't say async/await is easy for beginners sadly, it's very easy to make mistakes that silence exceptions or leak your tasks into edit mode
tasks shouldn't leak into edit mode if you use awaitable, right?
they don't for me any more
but once you get past those few things it opens up into being able to do practically anything
but yeah, that's valid
I have no idea, I use UniTask
Awaitable had a bunch of weird bugs and stuff last time I touched it
I think they're ironed out now, the only thing that is missing is WaitForSecondsRealtime really (and you can work around that)
I would presume it would still run across the playmode barrier
if you use Awaitable, they are correctly cancelled when leaving play mode 🙂
at least on Unity 6 and 6.1
im currently using the default input axis controller for my cinemachine camera, but am running into an issue with disabling/enabling certain action maps. because im using a generated class and creating an instance of my input action asset, disabling and enabling those action maps dont end up affecting the input for my cinemachine camera. i was wondering if there was a way for my input controller to reference the input action instance. the input action instance is created in an input reader scriptable object.
Hey, i know this is gonna sound REALLY Dumb but i recently got into Coding and am trying to make a Guessing Game... Can someone Help me find a Good Tutorial For How Do Input Fields Work? I Cant Find Any
what specifically about input fields are you struggling with?
Ive tried multiple times trying to get the text from the field and checking it, like a code system but it runs the debug for when its wrong, even though i write the correct Answer
you would need to show us your code etc
and your debugging attempts
btw, make sure to keep this in mind
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
Hey i have a small problem i'm trying to make a kind of active ragdoll using configurable joint and i'm doing this
void Update()
{
for(int i = 0; i < ragdollBody.Length; i++)
{
ragdollBody[i].targetRotation = animatedBody[i].localRotation;
}
}
The way this works is the ragdoll set the target rotation to the one of the animated body
and everything work right until i rotate more than 2 axis cause then instead of matching the rotation it rotate differently.
I don't know if it's using quaternion or something else but i really need some help to make this match the rotation perfectly
does anyone know when unity's summer sale is?
nope and #💻┃unity-talk
Can you describe how it rotates differently?
wait i'm gonna make a video
And i have a guess why it do that but i tried so many thing and it just doesn't work, tried using euler angles tried changing the anchor which change the outcome but never go as wanted
I guess it must be using quaternion but it's such a bitch to use that i'm gonna go crazy
So, can you describe how it rotates differently?
It's shown on the video, it rotate fine on the x axis and the z axis but once i rotate the Y axis it just turn based on the world Y if that make sens
Wait shit i found something When i turn the Y rotation it change the rotation for all of them
and i believe the configurable joint don't like that at all
So, I'm not able to understand the video at all. Given the code, I'm going to assume ragdoll is a list of Animator components and that you're assigning the target rotation of each Animator instance the value specified by some local rotation (likely the object you're directly moving in the scene/video). Maybe serialize two lists of quaternions/eulers and verify if the data truly matches (they likely should, minus root motion physics etc)
Well that the full code
[SerializeField] ConfigurableJoint[] ragdollBody;
[SerializeField] Transform[] animatedBody;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
for(int i = 0; i < ragdollBody.Length; i++)
{
ragdollBody[i].targetRotation = animatedBody[i].localRotation;
}
}
I'm just taking the transform of the body i want to match and the configurable joint of the ragdoll and telling it to match
And i do that for all of my body part in order
Do you have the "Configured In World Space" option enabled on your joint? If not, you should use world space position, then translate it to local space of the joints transform, or you could try enabling it, and directly using position, but this would mess up if the 2 weren't in the exact same position, but it's a test you can run to figure a bit more out about the problem
Wait it's not activated but i'm gonna test
How could i translate it the world space position to local space of the joints transform?
thanks
You'd use it on the joint transforms, just to clarify
Well using in on the joint transform doesn't change anything
but i'm gonna try it on the other transform
You know what for now i'm just gonna stop all of that It's been multiple day of barely sleeping trying to get that shit out of my mind i can't anymore
need some rest
but atleast i have some clue on what's the problem so thanks a lot dude
at the start should i keep using a game engine or is it better to get a feel of the language to fully code it all and not rely on an engine (i know the basic fundamentals of coding, so understanding isnt a problem to a certain extent)
theres people in this discord that would disagree with me but I feel like its important to get a good grasp of the language first
so that means i should try make some projects off of any game engine?
just asking cause that could apply to both options
Going into any multi-disciplinary skill with the existing knowledge and experience is obviously a benefit, that's just common sense.
It's not mandatory either.
There's no should or should nots. Whether you work on an individual skill first or simultaneously doesn't really matter and is unique to each person.
hi everyone- is there any one knows about web request visual scripting- this is my first part of script and I should see my backend messages in the console . but I can not see
I don't think you'd find many people here who think learning programming in any capacity wouldn't be helpful before starting Unity. Hell, even learning something like COBOL before starting Unity would help. The hardest part of programming isn't the language it's having an intuitive sense of control flow, understanding procedural logic, and how to split a task into smaller chunks, which you could learn in basically any language.
Had an argument with someone here before that said learning c# on its own before moving to unity is a waste of time since they'll be practicing their c# while working with unity anyways
big yikes
It's not necessary, but it is by no means a bad idea
wsg guys, just started using unity today, can someone teach me how it works or smth
Hello! I'm new to unity, and I got into coding cause I want to be a game developer, I've tried different coding language, most recently, I use ActionScript 3.0, now I am switching to unity, my goal is to create a "gacha life like" game, a character creator/customization game, I tried a tutorial online, but failed, the asset does not switch, nor does the asset switch color like in the tutorial, do any of you know how? Or like know tutorials I can source else where besides youtube?
who reacted with google 😭😭😭
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
We would find the same things on Google that you would find searching for character customization tutorial. If it worked for the tutorial, then odds are you did something wrong and should look at it more carefully. Or add debugs and try to figure out where the logic is going wrong and narrow down what line isnt working as expected
The problem was with the graphic, like the button asset that was provided in unity, it does not show up when I play the game 😦
Without seeing the setup its hard to say anything. If it isnt code related, then you'd want to show your setup maybe in #💻┃unity-talk and ask why this button does not show up
Hey, guys! I was wondering how I am supposed to rotate a game object to a specific point/angle? Is there method or something?
I am currently working on a horror game and I want to rotate a crucifix game object to a specific angle and then to stop rotating. I think you have seen that in horror games.
there are several static quaternion methods, you probably want Euler for this?
and then you can slerp towards the resulting quaternion
or perhaps smoothdampangle before the euler
a lot of ways to go about this
So, I can use quaternion.lerp() or quaternion.rotatetowards()?
Probably?
I mean in order to create this smooth rotation and then to stop.
well depends on how exactly you want it to go, smooth is pretty broad
but that's the idea, yes
(perhaps get it working before making it look good)
does anyone know why my enemy isn't moving to the player? public class BaseEnemy : MonoBehaviour
{
public float MaxHP;
public float HP;
public float MoveSpeed;
private Rigidbody2D rb;
private GameObject player;
private Camera cam;
public float dist;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
cam = Camera.main;
player = GameObject.FindWithTag("Player");
HP = MaxHP;
}
// Update is called once per frame
void Update()
{
if (HP <= 0)
{
Destroy(gameObject);
}
if (HP > MaxHP)
{
HP = MaxHP;
}
}
void FixedUpdate()
{
GetDist(player, gameObject);
Vector2.MoveTowards(transform.position, player.transform.position, MoveSpeed * Time.deltaTime);
if (dist <= 5)
{
}
if (dist >= 10)
{
transform.position += (MoveSpeed * Time.deltaTime * transform.forward);
}
}
public void TakeDamage(float damage)
{
HP -= damage;
}
private void GetDist(GameObject Object1, GameObject Object2)
{
dist = Mathf.Sqrt(Mathf.Pow(Object1.transform.position.z - Object2.transform.position.z, 2) + Mathf.Sqrt(Mathf.Pow((Object1.transform.position.x - Object2.transform.position.x), 2) + Mathf.Pow((Object1.transform.position.y - Object2.transform.position.y), 2)));
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok gimme a sec
hey btw Vector3.Distance exists
the math.. seems to be wrong though
that MoveTowards also isn't doing anything
Yeah, IDK why
because you aren't doing anything with it
also, you have an rb but you're trying to modify the transform
Vector2.MoveTowards(rb.position, player.transform.position, MoveSpeed * Time.deltaTime);
Is that better?
or should I move it somewhere else
You still aren't doing anything with the result
MoveTowards doesn't do any physical moving
you're just computing the value moved towards the other value
rb.position = Vector2.MoveTowards(rb.position, player.transform.position, MoveSpeed * Time.deltaTime);
oh..........
whoops
why not just use the rb
I fixed that up there
setting position does teleportation, not great for doing physics
no, like actually utilize what the rb can do for you
you can just set a velocity pointing to the player
Ok, thanks for the help!
i want verification on my code, simply "is this good?"
this is a join request UI that update itself using server data and epoch, with this workflow:
received join request -> 10 second wait(keep updating UI) -> timeout -> deny requests
-> calling
Init(serverEvent evt){
...
StartCoroutine(UpdateUI(evt.Time.AddSeconds(CommunicationConstants.JoinRequestDuration)));
}
-> function itself
private IEnumerator UpdateUI(DateTime endTime)
{
while (DateTime.Now < endTime)//localtime
{
//updating UI
yield return new WaitForEndOfFrame();
}
UniTask.Action(async () =>
{
await SendMsgToPlayer();//network action
}).Invoke();
Destroy();
}
evt.time is server epoch , so its basically epoch + 10 seconds
don't use WaitForEndOfFrame for that
if you want to wait a frame, you can just do yield return null;, but for simple checks like that you could also condense it into WaitWhile or WaitUntil (for potentially cleaner code, depending on what you feel is clean)
UniTask.Action(async () =>
{
await SendMsgToPlayer();//network action
}).Invoke();
This is pointless
looks like waitwhile is new stuff
you can just not await SendMsgToPlayer()
i know if i wrote it like that its actually fire and forget, but if something bad happened unitask can catch it right?
it was added in 5.3
i removed the action layer, lets hope it doesnt become too expensive lol
there is no perf difference
the Forget ensures exceptions get logged by un awaited UniTasks
the old method probably did the exact same so dw about it
ty 👍
actually i have 30+ places doing that before lol
gonna rewrite them all
yea probably best 👍
try to use async methods when working with async code too, its hard to use coroutines and async together.
Unitask does offer things to let you execute and await a coroutine. Other way around is hard
the problem is at least 70% of my unitask code is to register something that need to await into UI button events
which must return void
i do have legit tasks that send stuff over network
under unitask
trival to overcome:
button.onClick.AddListener(UniTask.UnityAction(AsyncFunc));
or
button.onClick.AddListener(() => AsyncFunc().Forget());
same problem exists with coroutines so either way its easy to solve
i just gonna do forget
accept.onClick.AddListener(() =>
{
CommunicationManager.Instance.SendMsgToPlayer().Forget();
Destroy();
});```
yea thats one of the many solutions
does anyone knows about lighting in unity here?
alread did , no reply 😅
you're not more likely to get a reply here
i see
UniTask delay/wait functions can be given a cancellation token as an arg
I dont understand the issue if there even is one
ok then this should be fine
private IEnumerator UpdateUI(DateTime endTime)
{
yield return new WaitWhile(() =>
{
//update UI
return DateTime.Now < endTime;
});
CommunicationManager.Instance.SendMsgToPlayer().Forget();
Destroy();
}```
for me it does look better , ty 👍
EVERYTHING WORKED 😭
hmmm this could be useful for some other things too
you can also do () => DateTime.Now < endTime
yeah i just knew that lol
why not just a regular while(DateTime.Now < endTime)?
this way there will be no capture causing by the lambda, meaning zero closures
i will optimize it with the way that chris taught me lol , should be better then
they aren't that different
im now fixing other errors
something something wait for time to end in a better way
no no, the lambda will capture the variable there.... if you're fine with closures then go for it
https://paste.mod.gg/uxrbwcxftcnv/0
I do have a little problem, and that is with the MuonManager like i do have it on Don'tDestroyOnLoad
But however when i start the world scene, it starts at "0/12" despite already rescued a muon object, when i got back to the stage and see that one muon object already been rescues, and when finishing the game, the muoncounter went back up to "1"
how do i that the number start at the already rescued muon objects?
A tool for sharing your source code with the world!
I don't know what is the IDataPersistance used for, but for storing objects between zones you can use the Scriptable Object - then when you change the scene the object will keep the information.
not 100% sure but i think it is happenig because you got the DontDestroyOnLoad inside the if statement for the singleton, you might want to try it out outside
I missed that - that's also a valid point - don't destroy on load shouldn't be inside if
well i do have it on DontDetroyOnLoad
A tool for sharing your source code with the world!
if i remove DontDestroyOnLoad, it will still start of with "0". and the number won't go up from rescuing a muon object in the stage
No, no - slightly different. Keep the DontDestroyOnLoad but put it before your if:
// put it here
if (Instance != null)
{
// not here
}
like this?
https://paste.mod.gg/xhjwtsgfqgdh/0
also this is for the coutner on the world scene
A tool for sharing your source code with the world!
they're different in many ways. the delegate passed for waitWhile there got fixed overhead for creating and invoking (call vs callvirt). also closures in general is evil as they will make copies in memory
yep :)
but the amount of muons rescued still starts at "0"
if you want to share that value between scenes simply create a static c# class which you can access easly
Can you say what do you mean by 'starts'? Starts when you 'play' the game and each time it goes to zero, or it goes to zero when you change levels?
when i play the game and each time when i start the game it goes to "0"
Yep, that's expected "DontDestroyOnLoad" won't help with that. It still resets the state when you 'play' the game.
You will need to use scriptable object for that
so should i create a new script or?
You need a new script that will extend ScriptableObject instead of MonoBehaviour, it needs to have a special attribute [CreateAssetMenu], then you can create an instance of it in your assets window. Then in your actual script where you count the values you need the reference to that scriptable object and you drag and drop it in the inspector. You can have a look here for a small introduction to scriptable objects: https://www.youtube.com/watch?v=IxxsROBNA04
Hello Fantastic People! Ready to elevate your Unity game development skills? Today, we're diving into the magic of Scriptable Objects. This tutorial is your guide to decluttering your scripts and injecting flexibility into your game design. Learn how to craft configuration files that minimize script variables, perfect for managing properties acr...
the use case is slightly different, but the main idea is shown there. The only thing is - if you want to release the game you also need to store the information and load it (in a file or player prefs)
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
then after this. I am thinking on how to make the rescued images to appear on the empt yslots when selecting a stage and player. But i'll take that later and focus on designing
I have a stupid question. I know the Vector3 position my hand needs to move to.
I need to know where each finger will be before the hand reaches that position.
Can I do:
"Vector3 fingerOffsetFromHand = fingertip.position - handTarget.position;"
and then:
"Vector3 predictedFingerTipPos = newHandPos + fingerOffsetFromHand;"?
is this it?
Assuming it's not going to rotate, then something like this:
Vector3 diff = finalHandPos - currentHandPos;
Vector3 predictedFingerPos = currentFingerPos + diff;```
if there is any rotation at all, we'll need to account for that separately
The Vector3 final hand position will have different rotations but the finger will always have the same local offset
Is the finger a direct child of the hand?
yes
then you would do something like this:
Vector3 fingerLocalPos = fingertip.localPosition;
// newHandPosition needs to be a world-space Vector3 position
// newHandRotation needs to be a world-space Quaternion representing the final rotation of the hand
Matrix4x4 finalHandMatrix = Matrix4x4.TRS(newHandPos, newHandRotation, handTarget.lossyScale);
Vector3 finalFingerPosition = finalHandMatrix.MultiplyPoint(fingerLocalPos);```
Why does my camera rotate a bit even when its rotation is 0?
using UnityEngine;
public class TeleportTrigger : MonoBehaviour
{
public Transform targetLocation;
public string playerTag = "Player";
public GameObject ObjectToActivate;
public bool invertRotation;
private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag(playerTag)) return;
other.transform.position = targetLocation.position;
var look = other.GetComponentInChildren<FirstPersonLook>();
if (look != null)
{
float currentYaw = look.transform.eulerAngles.y;
float newYaw = invertRotation ? currentYaw + 180f : currentYaw;
look.SetYaw(newYaw);
}
else
{
Quaternion targetRot = other.transform.rotation;
if (invertRotation)
{
targetRot = targetRot * Quaternion.Euler(0, 180f, 0);
}
other.transform.rotation = targetRot;
}
if (ObjectToActivate != null)
ObjectToActivate.SetActive(!ObjectToActivate.activeSelf);
}
}
(invert rotation is disabled)
cool, so very minor differences
perf doesn't really matter at this level, readability takes precedence
Can you explain the nature of "rotate a bit"?
literally, i trigger the teleport and it rotates the player about 1-10 degrees
no matter if the rotation is 0 or any other number
Doubt it has anything to do with the code you just shared then
Although it's unclear what this "FirstPersonLook" is and how it works
so it could be a problem in there
I would also really avoid dealing with euler angles in this way, it's bound to lead to sadness and pain
Thanks, I'll try that. But is the matrix necessary? Can't I offset it locally from the desired position if I rotate it away from the player?
The position will be tilted on the z, nothing else
the matrix is the simplest way to account for rotation and position changes at once
hey, im attempting to "glue" my player mesh to a moving platform that is also slightly rotating around (ship deck), however attempts to simply parent when collision detected merely result in the player mesh rotating with the buoyancy (as in, doing frontflips) and also not keeping the same velocity as the ship while moving
one of my friends gave me this code, however its old and doesn't appear to be working
What exactly isn't working? Is it compiling properly or are there errors?
compiles properly, no errors, just doesn't work. player doesn't acquire ship's velocity, which leads to them flying off the back
It does look a bit shady with the cross product between position and angular velocity.
But the idea of controlling the player velocity and angular velocity relative to the ship is correct.
You just need to refine it
What script should I use to make an rb move in it's faced direction?
a script that makes a rb move in a faced direction probably
you might have to be more specific
A script to add force to an in rb. But in the direction it's facing
I'm not sure if that's just LinearVelocity though
what do you mean "what script should i use"
addforce is probably what you want yeah, if you do a little light googling you'll find some examples/references that might help you out
ok thanks
hey guys why can't I save my script into the asset directory it says I need to, but I can't I clicked create and add but it moves me to the file explorer
where are you trying to create it?
im instantiating enmies in my game via a spawner and i want to let the spawner know when the enemy has died. Im trying to do it via actions but struggling to bind the event considering its instantiated at runtime. any help would be appreciated
the simplest approach would be to make your spawner a singleton, assuming you have one spawner
events can be done via code, usually preferable so! what specifically has you stuck?
normally i bind and unbind in my on enable and on disable events however because the enemies spawn at runtime thats not really possible so im struggling to find the right time to bind it
well you would bind it during the spawning, no?
Spawner
SpawnEnemy()
MyEnemy newEnemy = Instansiate(etc.)
newEnemy.OnDeathEvent.AddListener(OnSpawnedEnemyDeath)
eg.
that would work however where would you unbind it in case something got disabled or smth
When the enemy dies?
Or if the spawner dies too i suppose but depending on stuff and things less of an issue
can do im just thinking of if the spawner got disabled and the enemy dies it would fire and cause an error
Why would it cause an error?
i assume null ref
just add a check beforehand
can do that makes sense
What are we putting a check on?
if spawner is active
That's not really how events should be used
what's wrong with this approach?
yeah at that point i might as well just call the function from the enemy
if you need to explicitly check up on one of the listeners at that point the enemy would just talk to it directly
when you say the spawner is disabled, that's not a null ref. do you actually mean disabled or do you mean destroy etc.
exactly
oh i assumed that was already happening
could be either i know its unlikely but its for an assignment so they care about that kinda stuff
im using system.action
system.action doesn't even know things can be disabled
it's not a c# concept, thats a unity thing
yeah but it can cause memory leaks and that if not unbinded correctly
Potentially yeah, but that's why I was curious on if you actually meant disable or not
because the time to unsubscribe would be whenever you destroy or disable it
yeah that makes sense i can unbind at destroy but i wont have access to the action in on disable
why don't you have access on disable?
cause the enemy gets instantiated at runtime
If your spawner is the thing that creates the enemy im sure it could do a fine job keeping track of where it's at 😄
yeah no it can but i wont be able to get the reference from the instantiation and put that in the on disable event
Why
well i mean if its possible i wouldnt know how to do it
{
Vector3 randomPos = UnityEngine.Random.insideUnitCircle.normalized * 12;
GameObject enemy = Instantiate(m_BaseEnemy, (m_Player.transform.position + randomPos), Quaternion.identity);
EnemyHandler EH = enemy.GetComponent<EnemyHandler>();
EH.Initialize(m_ES[difficulty]);
EH.EnemyDead += EnemyDead;
}```
at the bottom i bind my event so how would i take that so i can unbind that in my on disable
eg.
private List<EnemyHandler> managedEnemies
SpawnEnemy()
managedEnemies.Add(EH)
EH.EnemyDead += OnEnemyDeath;
OnEnemyDeath(EnemyHandler EH)
managedEnemies.Remove(EH)
EH.EnemyDead -= OnEnemyDeath;
OnDestroy() //OrDisable etc.
foreach (EnemyHandler enemy in managedEnemies)
enemy.EnemyDead -= OnEnemyDeath;
bits of this can differ depending on preference and how you wanna handle stuff
yeah that works ill keep a constant reference to active enemies and not just at spawn
what do you mean?
in what folder are you trying to create the script
what folder should it be in?
assets folder
ohhhhhhhhhhhhhhhh thanks👍
so i have a gamemanager which has an array of the components
when a button is pressed a component is instantiated and added to the list
the components properties are set
ive also added for debugging purposes that when the component is instantiated and set it prints its values
however its values are unset even after being set
gonna need to see some !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
// in the main script
void AddObject(int posX, int posY) {
Obj o = Instantiate(ObjPrefab);
Obj.SetPosition(posX, posY);
objList.Add(o)
}
void Start() {
AddObject(3, 5);
print(objList[-1].posX);
print(objList[-1].posY); // outputs 3 and 5 as expected
}
// in the component itself when
void Start() {
print(posX);
print(posY); // outputs 0 and 0 even though it was set
}
i thought since it was a reference object I could chagne the fields and have it update elsewhere
what if you add a print right after the Instantiate, before the SetPosition
its still unset
yeah, since it's before the setposition
what i'm trying to get at is, the component Start might be running before the SetPosition?
i don't remember the flow there but i wouldn't doubt it
I'm pretty sure you're right Chris
Obj o = Instantiate(ObjPrefab); // `Start()` will run
Obj.SetPosition(posX, posY); // this is after
No, that sort of stuff isn't allowed here.. and won't be in this channel if it was. Delete and post on 👇 !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
hey, is this code related?
i want to change how the theme of the unity layout looks for me, its currently like some light gray but i want it darker
no, obviously not code 😄
preferences > color
preferences -> general
actually no both places don't let you customize the ui color
general is where you swap between light/ dark theme
ok
they said they wanted a darker dark theme
no they didn't -> its currently like some **light **gray but i want it darker
damn i thought light mode would be whiter. it looks so washed out lmao
also im talking about the colors in the engine
same place it always is for your platform
We should probably move this to #💻┃unity-talk if it's gonna need to continue
but i thought
the ohject itself
is a copy
ok?
and that changes to it will affect like that actual object
sorry not a copy a reference
No idea if your code example is correct but you do not call a function on your new instance o after Instantiate()
Obj o = Instantiate(ObjPrefab); creates a new instance of that game object with it's own instances of the components
they do
this is correct
the thing that's going wrong is that you're checking the values before you set them
try opening the debug inspector or logging in Update
ive tried checking in update but what happens is
- i instantiate the object
- i set its values
- i add it to the array
from the objects script when i access its own properties it is unset
but when i am accessing its from the array it is set
then they are different instances
give each new instance a new name to help when debugging
if comfortable, use a debugger
in your current code? it's checking its own props before they are set
is that the case? if i add an object to an array is it not a reference?
It is a reference
you are fucking up somewhere clearly, either the data is set not when you expect or they are difference objects
or your function used to set the data is faulty
yeah i can see
wait for testing if two instances are the same, can i just use the equality operator?
ohh okok thanks
ill test it out and see
you could also change to Debug.Log and add a context to check if the logs are coming from the same object
okay ill try that
okay so two debug messages from the same object give me one thats set and one thats unset
the call with the set value comes from the gamemamnager
the unset one is from the object itself
as in when i invoke ShowData() from the gamemaanger it works but from the object it is reset
you need to share more !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
in the gamemanager:
in the plant superclass
in the peashooter subclass
peashooter derives from plant
could it be that due to being inherited, its fields are reset?
Can you just share the entire classes in one of the paste sites..
sure
https://pastebin.com/CW3uTxBm
thisd is plant.cs
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.
https://pastebin.com/cCsqfNh6
peashooter.cs
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.
https://pastebin.com/hAR3MSHM
level.cs
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.
you've been telling us names that you're not using.. so it's difficult to follow.
gamemanage = level.cs ?
ShowData() = TestPost() ?
yeah level .cs is the gamemanager
showdata is testposition
sorry i thought itd simplify it a bit
which logs are showing the value as unset?
the log that occurs in peashooter.cs
in update
always?
Hello
I'd imagine it starts off wrong, and then after singleton.plants[tile.posY, tile.posX].SetPos(tile.posX, tile.posY); changes to the right values
yeah
when the peashooter is instantiated, the first test log is correct (in level.cs, placeplant())
but every subsqeuent log is incorrect
no it different
Guys can you help me i am really newbie in unity
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
this is a code channel - only use this channel if your question is about code you are writing.
How fix this
Ok sorry
1- Delete that from here.
2- Find the correct channel -> id:browse
3- Do not post a photo (especially such a bad photo like that)
4- Explain wtf "this" is... no one knows your game
go to #💻┃unity-talk and explain what the issue is
Thanks
yeah its still tweaking after tweaking, im fully stuck
i want to find the angle between my enemy and my player.... i have a script in enemy for that... how can i achieve it? i also want it to work when the player is higher or lower than the enemy.
Vector3 vectorToPlayer = -(transform.position - player.position);
angle = Vector3.SignedAngle(vectorToPlayer, transform.forward, Vector3.up);
Debug.Log(angle);
will this work?
the angle relative to what
there's 3 points involved in an angle - a pivot and 2 endpoints
so ive tested and the plant in t he array is a copy of the plant
so they are seperate
your plant is a class, isn't it
that's a ref type, it's not gonna be a copy just from assignment
but like the plant in the array is basically a copy of the one that is actually instantiated