#💻┃code-beginner
1 messages · Page 611 of 1
{
animator.Play("Base Layer.MortemRifleShooting");
GameObject nuevoProyectil = Instantiate(proyectil, proyectilposition.position, Quaternion.identity);
Vector3 direccion = (objetivo.position - proyectilposition.position).normalized;
Rigidbody2D rb = nuevoProyectil.GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.linearVelocity = direccion * bulletspeed;
}
balas--;
}```
bullet needs its own script
it does in the Rigidbody
this is all
public class MortemRifleProyectile : MonoBehaviour
{
public int damage = 5;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.TryGetComponent(out ValeriaController player))
{
player.TakeDamage(damage);
Destroy(gameObject);
}
}
}```
so this means i have to take the rigidbody's values, and then reflects them
pretty much
store it in a vector3
Vector3 rigidbodyVelocity
FixedUpdate(){
rigidbodyVelocity = rb.linearVelocity
if its a trigger though it gets a bit more complicated
because with triggers You dont really get the normal
with triggers you mean the
private void OnTriggerEnter2D(Collider2D collision)?
meaning the collider is a trigger yes
dont worry, i will use the same mechanic of harming an enemy, just that instead of damaging the proyectile (wich would be cursed) it will make the speed thing
btw, make sure to put ```cs and not just ``` when posting codeblocks
private void OnTriggerEnter2D(Collider2D collider)
{
if (collision.transform.TryGetComponent(out ValeriaController player))
{
if (player.IsParry)
{
var collisionPoint = collider.ClosestPoint(rb.position);
var dir = rb.position - collisionPoint;
rb.linearVelocity = Vector3.Reflect(rigidbodyVelocity, dir.normalized);
}
else
{
player.TakeDamage(damage);
Destroy(gameObject);
}
}
}```
You're checking meltdownTimer, but the value displayed is currentNumber, which is calculated after the check. Compare that variable instead . . .
once u used loadimage
https://docs.unity3d.com/530/Documentation/ScriptReference/Texture2D.LoadImage.html
can u redefine the size of the texture?
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
#1253440741322133545 message finally got it worked out
until i dont 🙂 lol
i barely caught that bug
Hahaha . . .
texture.LoadImage(File.ReadAllBytes(filePath), true);
if (texture.width > 480 || texture.height > 480)
{
texture.Reinitialize(480, 480);
}
texture.name = fileName;
return texture;```
i gonna force texture like this first
btw this is necessary to be inside the onTriggerEnter2D?
cuz my idea was to make this inside a Void
thats how my meele works, it calls a state from the enemies
wat?
this is how my weapon works, look
inside a Void
{
// Cast a ray to detect if an enemy is in range
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, demons);
// If an enemy is detected, deal damage
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
}
}
}```
a normal method
OnTriggerEnter2D is also a "void" return method
but without needing to trigger the collision
cuz the machete and the player has the same collision
...so it would be a paradox
or no, i dontk now how overlaps works
confused to where the bullet part comes in?
the idea is
the same way i make enemies go into their hurt method
i will make the proyectile go into it reflect method
public class MortemRifleProyectile : MonoBehaviour
{
public int damage = 5;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.TryGetComponent(out ValeriaController player))
{
player.TakeDamage(damage);
Destroy(gameObject);
}
}
public void Parried()
{
things
}
}```
it makes sense in my brain
You would still want to track the velocity of projectile rigidbody in its own class
i suposse
the thing is, i tried to paste it inside the method, and it showered some errors
paste wat?
dont mindless copy code without understanding what its doing
You can call Parried if you use a physics query sure
the rest is similiar
can you make sure to put ```cs and not just ``` when posting codeblocks
so if you stache a reference to a game object you have to use _spawnedObj.getcomponent().Level unless you use Unit instead of gameobject type but what if you have other classes on a game object like if you have a mage class or something would you create another of that same game object but of type that class?
Unit unitPrefab;
Unit instancedUnit = Instantiate(unitPrefab);
Mage mage = instancedUnit.GetComponent<Mage>();```
maybe I misunderstood your question ?
btw what values are collision and rigidbodyVelocity?
rigidbodyVelocity is a Vector3
collisionPoint is a Vector3 also
i just mean if you have a game object you store references so you dont do find i think but what if that game object has a bunch of components
can you give me an example, not sure I get what ur asking
but i mean, how do i put them, cuz it says those values aren't set, specificly how i have to set them
using UnityEngine;
public class MortemRifleProyectile : MonoBehaviour
{
public int damage = 5;
public Rigidbody2D rb;
private void OnTriggerEnter2D(Collider2D collider)
{
if (collision.transform.TryGetComponent(out ValeriaController player))
{
if (player.IsParry)
{
var collisionPoint = collider.ClosestPoint(rb.position);
var dir = rb.position - collisionPoint;
rb.linearVelocity = Vector3.Reflect(rigidbodyVelocity, dir.normalized);
}
else
{
player.TakeDamage(damage);
Destroy(gameObject);
}
}
}
}```
like you store the references as unit a type other than gameobject so you dont have to use getcomponent but what if you have a bunch of components
wdym how do you put them ?the same way you declare other variables you did
the only difference is rigidbodyVelocity goes in fixedupdate to be update by rigidbody
```cs
code
```
not
```
code
```
what i mean is, to what i set them
also i dont understand the cs thing
!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/, https://scriptbin.xyz/
📃 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.
got it
oh wow
the only one needs to be set is rigidbodyVelocity in fixedupdate, the rest are already set on the trigger happening
but yeah, im pretty confused right now
but the thing is how
sorry im just getting confused
idk wat you mean how ?
also didnt you want to do from the weapon itself now you're back to trigger?
i realized my plan was dumb
or not idk, i just want this to work, i didnt knew making this would be so tiring
its valid
you have to pick one or the other
either put the logic in the projectile or the parrying / deflecting object
Vector3.Reflect but in 3d . I put it on the projectile itself
what about them ?
then you can only do that for one class
You can only grab 1 type return from Instantiate
but again once you have that either use a public field/property to access the other components from that script, or do a GetComponent on the instanced object like i shown above
Holup.
What if i delete the proyectile, and make the player shoot a brand new proyectile with the same sprite as the enemy one?.
I did the same thing for a doom mod long ago
public class Projectile : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
// use collision to Try to Get CharacterController2D
if(collision.TryGetComponent<CharacterController_2D>(out CharacterController_2D characterController))
{
// if we're here then our Trigger found a CharacterController_2D
Debug.Log($"We activated Trigger. Reference to CharacterController: {characterController.name}");
// we could do something w/ our CharacterController_2D if we wanted.
// now we destroy this gameobject
Destroy(this.gameObject);
}
}
}```
i think u shold do it however u feel like doing it..
but i would sit there and just test for a bit..
get ur collisions working correctly.. debug the values in the console window..
see what ur hitting.. what references ur grabbing.. and all that jazz
Makes sense
just little OnTrigger2D test i did real quick.. but thats before i read the entire thing..
this just shows the collision via that code i sent above ^
Hello, I'm creating new project but I got this error already. Does anyone know how to resolve it?
restart unity
if problem persists go to package manager and remove Version Control package
hii im new to unity, can someone help me, why is my character is falling through the map
Hi, it would help if you shared more about your character and how you set up collission specifically. I assume from this message alone you forgot a step with the collision and therefore it fails. Consider following the steps to debug this: https://unity.huh.how/physics/physics-issues
Specifically, check if everything has a collider and check that these can communicate with eachother. Additionally, make sure you use the correct colliders. For example, don't use 2d colliders when you work in 3d.
either the floor or the player doesn't have a collider
is there a nice way to disable the physics of a game object? for example, when the player dies i want all the objects on the map to stop moving, i was thinking of using a static bool but having to check everywhere if the player is dead seems unnecesary, i was wondering if a function like gameObject.DisablePhysics(); exists..
i know Time.timeScale exists, but that will also disable the player
gameobjects don't have physics
i meant like the Update() function or something
i think timeScale would be appropriate here
that would be enabled on the component
thanks
if the player is dead, what would timeScale mess with?
it falls to the ground
i think timescale would be most appropriate here, and there's a few ways to work around that
I'm using this parallax script:
using UnityEngine;
public class Parallax : MonoBehaviour
{
private float length, startpos;
public GameObject cam;
public float parallaxEffect;
void Start()
{
startpos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate()
{
float temp = (cam.transform.position.x * (1 - parallaxEffect));
float dist = (cam.transform.position.x * parallaxEffect);
transform.position = new Vector3(startpos + dist, transform.position.y, transform.position.z);
if (temp > startpos + length)
startpos += length;
else if (temp < startpos - length)
startpos -= length;
}
}
And when I start the game it makes all 3 backgrounds snap into the same position, what are the possible fixes? the images are the before and after I start the game
i guess Time.unscaledDeltaTime exists but..
- change the timescale a bit after the player dies, giving the ragdoll time to fall
- change the timescale gradually, giving an effect of time slowing down until frozen
- use unscaled time for the death animation (if it's a separate animation) (though this would make everything but the player stop moving while the ragdoll falls, that might look weird)
!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/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
dont crosspost
funnily, the player has no death animation, the "animation" is just the gravity acting upont he player, the only thing that happens is that the input is disabled 😭
you're not even a mod or anything just doing it for the love of the game
Maybe get some shit going on in your life
<@&502884371011731486> (random insults when being told the rules)
not-mods have power to tell people how to get help appropriately, yes
rip that last option then
although you could simulate gravity under unscaled time yourself, it'd probably be a pain though
im thinking of just disabling manually
since all my :"Objects" live under Managers object
if i disable Managers i presume everything will stop too
it will not
dangit
enabled is a property of each component, it doesn't propagate to anything
you're thinking of SetActive
but that'll make everything disappear too
This is a community run server. People do not have to be mods to remind you of the rules. You've already been told not to crosspost in the past, so if you choose to continue to, you will not be allowed to post.
anyways @green badge what even is the issue with backgrounds snapping on play? do they move correctly according to parallax? do they tile correctly when you move far enough?
✌️
It's like
they do snap in front of the camera when u move out of range
But I got 3 different ones and they all go into the same position as the game starts idk if you understand what I mean
ah i see
if that doesn't work, please format your code properly or use a paste site so we can actually read it
yea mb, thanks for the help
watch this, 
it somehow worked
well sure but that's not going to be very flexible or maintainable
you'll have to make sure everything is reenabled properly, and no state broke in the meantime
maybe it works, but imo seems like a pretty fragile system
well the thing is, the only thing that can happen from this state is that you reset the game
reset as in, reload the entire thing?
yeah
there's no respawn mechanic?
reload the game scene
nope
oh i thought you meant reload the entire game, like close and reboot lmao
oh nooo
its just a 1:1 recreation of flappy bird im doing
you could just use events and subscribe to some global OnPlayerDeath event. then have the scripts disable themselves when the player dies
ah, ok. well, more power to you, but just keep in mind that this does not scale particularly well
yeah i can tell
not perf wise, it just could have a lot of hidden consequences if you have more complex systems
i might do this
in a flappy bird scenario, shouldnt you just have 1 script control the location of all pipes anyways?
then that one script can just stop moving them
i move pipes and the ground
they both have their own "Managers"
that sit under a Managers game object, i just take that Managers object and disable both of them
if i have something like this, should i put the component on the model, camera or the parent
animations are gonna be the death of me
apparently "Exit" doesnt stop the animation 😭
it just goes back to "entry"
It would not matter because the collission would still trigger as far as I know
But I would assume you just put it on the parent here since that's the main component
You could even make a third child purely for the collission if you want to organize it a bit and separate collission
Your issue is probably that you use either the wrong type of collission, or the collission is set incorrectly for it to work
ive done this to all model
still falling 😦
Would this calculate correctly? Or would it get stuck/throw errors when values get too large for ints?
All the variables used in the formula are ints:
return (long)(baseXp + (baseXp * MathF.Floor(level / levelIncrease)));
well it's kinematic so that's not gonna fall on its own. how are you moving your rbs?
level and levelIncrease are also ints?
yes
you don't need that Mathf.Floor then
what if level is 3 and levelincrease is 2?
you'd get 1
oh k
int/int -> int
but its uses RoundToInt instead of floor
anyways if the result gets too large for an int, it'd overflow before you cast it to a long
it truncates
oh nvm
trunc is equivalent to floor for nonnegative values
cool 🙂
does that mean cast all the ints to long?
so if you suspect it'll get too large for an int, just cast it to long somewhere before the calculation
or have some value already be a long
ah just one is fine?
no, any arithmatic involving an int and a long will result in a long; the int will get promoted
the int will be happy to hear that 🙂
you could also consider uint
so:
return (long)baseXp + (baseXp * level / levelIncrease);
to answer your question more directly; if levelIncrease overflows to 0, you'll get a div by zero error.
anything other than that case won't error, you'll just get incorrect results.
probably should get the 2nd baseXp, since that's the one going to get too big for int
a theoretical overflow would most likely happen in the multiplication part, so you'd want that to be handled with longs
return baseXp + ((long)baseXp * level / levelIncrease);
It is eventually going to be too large for int, so might as well set it up right from the start not?
if any of these can get too large for ints, you should just move away from ints entirely there
its not like itll be converted correctly if the value already overflowed
all individual values are fine as int, but the calculation result will not be
Kinematic rbs don't give a damn about collisions. If you want the object to be processed by physics correctly, it needs to be non kinematic.
Or you should handle the collision manually in code.
To be more accurate - Kinematic rigidbodies exert forces, but do not respond to them
how do i read the value of the individual things like depth and horizontal
}
private void OnDisable()
{
playerInput.Disable();
playerInput.Player.Movement.canceled -= Handle_Movement;
}
private void Handle_Movement(InputAction.CallbackContext context)
{
Vector2 direction = new Vector2(context.ReadValue<>)
}```
this is what i got so far and now i dont know how to get the individual values for depth and horizontal
You need to redo this
Remove all the bindings in the action.
Set the action type to Value and control type to Vector2.
Then add an up/left/right/down composite or whatever it's called
And add all 4 keys there
Oo okay
ill try
Btw how do i make an animation
Do i need blender?
You don't need blender but blender is probably a good idea
Its tools for animating are better than Unity's
Look at mixamo too
I have an incredibly confusing problem here.
Within this if statement, neither Log is being triggered, it is as if the entire If statement is being skipped.
However, this only happens if I click on the very first button of the list of attacks, for every single other attack, it fires through normally, and the information is updated.
What could possibly cause this?
well, what's above it?
This is the full Update
I think I might be stupid but... I'm trying to have an object follow the path of a lineRender. The problem, is that it seems to be traveling VERY slowly through it.. and I'm not really sure why that would be happening? I would figure it would be near instant.
private IEnumerator FollowPath() {
transform.position = lineRenderer.GetPosition(0);
Debug.Log("Duration: " + duration);
for (int i = 0; i < lineRenderer.positionCount - 1; i++) {
Vector3 pos = lineRenderer.GetPosition(i);
transform.position = pos;
yield return null;
}
}
!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/, https://scriptbin.xyz/
📃 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.
but anyways, try debugging before other conditionals
{
if (state == BattleState.PlayerAttack)
{
if (EventSystem.current.currentSelectedGameObject != battleMenuControlSystem.currentlySelectedGameObjectByEventSystem)
{
TMP_Text _textHolder = null;
foreach (var text in battleMenuControlSystem.attackText)
{
if (EventSystem.current.currentSelectedGameObject != null && EventSystem.current.currentSelectedGameObject.TryGetComponent<Button>(out Button _button))
{
if (_button.GetComponentInChildren<TextMeshProUGUI>() == text && _textHolder == null)
{
_textHolder = EventSystem.current.currentSelectedGameObject.GetComponentInChildren<TMP_Text>();
}
}
}
if (_textHolder != null)
{
Debug.Log(_textHolder.text);
foreach (var knownAttack in playerUnit.entity.knownAttacks)
{
if (_textHolder.text == knownAttack.Base.Attackname)
{
battleMenuControlSystem.UpdateAttackDetails(knownAttack);
}
}
} else
{
Debug.Log("Textholder is null");
}
}
}
}```
I have been for about an hour and I've been able to narrow it down to that spesific If Statement.
If none of the logs print then probably one of the first two if statements evaluates to false and skips them
ok, if you put a log before that if, does that trigger?
if not, then the entire if isn't being reached
no... no it is not reached....
I'm actually mad at myself for not realizing that, thank you.
Today has been one of those days
Since there's a log in the if and else, if neither are printing, then it is definitely not reaching this if statement. Log the value before the if statements it is inside of to find out which isn't running
I figured out what is causing it. Or at least I hope this is it
I fixed it
LOL it was such an easy fix after I figured out that if wasn't being reached. Thank you
So, in another script, I hap hazardly already set those values to be equal in a redundancy check, but that caused the first update to never fire, so the first button of the group would never get updated.
Cutting out that part of the redundancy check fixed it
this is my flight controller and camera script
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[Header("Follow Settings")]
public Transform target;
public float mouseSensitivity = 100f;
public float distance = 10f;
public float height = 5f;
public float smoothSpeed = 5f;
public float minVerticalAngle = -80f;
public float maxVerticalAngle = 80f;
private float xRotation = 0f;
private float yRotation = 0f;
private Vector3 velocity = Vector3.zero;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void LateUpdate()
{
if (target == null) return;
// Get mouse input
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// Apply rotation with clamping
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, minVerticalAngle, maxVerticalAngle);
yRotation += mouseX;
// Calculate offset and rotation
Quaternion rotation = Quaternion.Euler(xRotation, yRotation, 0);
Vector3 offset = rotation * new Vector3(0, height, -distance);
// Smoothly follow target
Vector3 targetPosition = target.position + offset;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothSpeed * Time.deltaTime);
// Maintain focus on target
transform.LookAt(target.position);
}
public Vector3 GetCameraCenterPoint()
{
return target.position + transform.forward * distance;
}
}```
I am SOOOOO confused on how to make the plane face the center of the free cam
i just implemented the free cam and its kinda alright
but when I tried to make the aircraft turn to the center of it
it rotated without banking and using turning speed
your SmoothDamp usage is wrong, maybe review the API https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.SmoothDamp.html
bet
{
public Transform playerBody;
public float mouseSensitivity;
public Vector2 lookInput;
private float xRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = lookInput.x * mouseSensitivity * Time.deltaTime;
float mouseY = lookInput.y * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}```
i dont understand why camera movement is so jittery
Do not multiply mouse input by deltaTime
mouse input is already an absolute amount of movement
unlike a thumbstick input, which is a rate of movement (and thus needs to be converted into an amount of movement by multiplying by deltaTime)
The longer the frame takes, the more mouse movement can happen in one frame
When you multiply by deltaTime, you wind up making those long movements even longer
can one of yall try help me in editor my games works perfectly fine but in builds i get a MethodNotFoundExeception and ive debugged alot the method is public ive made sure it doesnt get stripped i just dont know why
share more details
so my button uses a clickedOK method to delete the ui text and spawn another one for more text however when clicking on the Ok button it just says methodNotFoundExeception
and as a result my game cant be played because it wont progress until the ok button has been pressed
what kind of build is this? PC/mac/linux, or Web?
how are you seeing this exception? did you make a development build?
is it IL2CPP or Mono?
mono
er, actually, it could still be happening; i was thinkign about the wrong thing here
You may need to look in the log file to see more information. I forget how much appears in the in-game console..
1 second
oh yeah i made a seperate debug log aswell to see
in the log it doesnt explain much either bascially the same thing im seeing in
the ingame console
well that's vague
How is the button's target assigned?
did you set it up in the inspector, or did you add a listener via script?
listener
public void clickedOK()
{
Debug.Log("clickedOK was called");
if (!isActiveUI())
{
Debug.LogWarning("clickedOK() called but UI is not active.");
return;
}
if (textIndex < texts.Count)
{
displayCurrentMessage();
playOpenSound();
return;
}
close();
if (onOK != null)
{
VNLUtil.getInstance().doStartCoRoutine(onOK);
}
}
Hey everyone! I'm experiencing an FPS drop when playing footstep and sprinting sounds. My code just picks a random AudioSource from an array and plays it, but as soon as I add footsteps, my FPS drops significantly. I've checked the profiler, and audio seems to be causing the issue. Does anyone have tips on optimizing audio playback in Unity? I'd really appreciate any help
Can you show the profiler results you saw and your code?
!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/, https://scriptbin.xyz/
📃 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 void clickedOK()
{
Debug.Log("clickedOK was called");
if (!isActiveUI())
{
Debug.LogWarning("clickedOK() called but UI is not active.");
return;
}
if (textIndex < texts.Count)
{
displayCurrentMessage();
playOpenSound();
return;
}
close();
if (onOK != null)
{
VNLUtil.getInstance().doStartCoRoutine(onOK);
}
}
can you show the inspector for your button
like - how you hooked this method up to the button
uhhh what is this haha
none of this is standard unity stuff
How does this UI Button Message script work
And what does the inspector of the MessageUI object look like that you have there
oh man that's an old inspector
Is this like a Unity 4 or 5 thing
2017
- Why does this UI obejct have a box collider?
- What are these UI Button Message things, why not normal Button component? (that existed in 2017... right?)
idk its a older project im just trynna fix em so i can release em i honestly do not know i think this was my first project
my presumption is whatever object that you have assigned there does not have a script with that function
(the MessageUI object)
I mean if it's really bad I'm willing to change it tbf
if this was the case it wouldnt work in editor however it does
just in builds it doesnt
maybe that object is being destroyed in a build or something
Can you show the inspector of that object
aalso what is the target platform you're using here? Windows?
of the messageUI object?
Yes
yes windows
btw if you wondering this is what the hirenarchy looks like for it
It probably is a code stripping problem
how did you "make sure it doesn't get stripped"?
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
is this not correct?
probably
you sure it's the same method and not a different one this time?
yes
using UnityEngine;
public class Footsteps : MonoBehaviour
{
public AudioSource[] footsteps;
public AudioSource[] Running;
public void PlayFootStepAudio()
{
if (footsteps.Length == 0) return; // Prevent errors if no sounds are assigned
int n = Random.Range(0, footsteps.Length);
footsteps[n].Play(); // Play the selected footstep sound
}
public void PlaySprintAudio()
{
if (Running.Length == 0) return; // Prevent errors if no sprinting sounds are assigned
int n = Random.Range(0, Running.Length); // Select a random sprinting sound
Running[n].Play(); // Play the selected sprinting sound
}
}
looks like most of that is rendering, not audio
662ms in RenderLoop
so how do i fix it?
!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/, https://scriptbin.xyz/
📃 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.
i have this adjusted code for a weapon in my game https://paste.ofcode.org/aHrxTgB4H8E3eUKjx9Aj4g basically i want to instanitate it from my player like a bullet but im not sure how to go about it because of the target component in this script because i cant set it in the assets as i get a type mismatch
You can't reference a scene object from a prefab
Whoever instantiates the prefab should give it the necessary scene references
intresting thank you but if i instantiate it from the player how would it work because i reference the transform component in this script
intresting thank you
I have an object with a script running an OnTriggerEnter2D Function, and i want the trigger to count the hitbox of a child object. Is there a way to register the OnTriggerEnter of a collider not attached directly to the same object as the script?
if you have a rigidbody the child should still receive triggers hits
Theres the issue, i forgot the rigidbody 🤦♂️
btw that null check is not needed , TryGetComponent returns true if the component is found
if(collision.gameObject.TryGetComponent(etc..){
Yeah i noticed that (editing old code and i had no clue with trygetcomponent back then lmao
If you want more precision or the child being origin of hitzone for specific things, you could use physics queries like Overlaps and Casts
to my previous question i have it set up something like this how would i change it up its not making sense to me right now
why is the player dealing with UI
UI should be something already inside the scene
the object in the scene should then reference the player when its spawned to track its stats to display
im having a hard time using this code to launch the special powerup: https://paste.ofcode.org/aHrxTgB4H8E3eUKjx9Aj4g
from the player
so i have a transform component but i cant really set that up in the prefab but i use that prefab in the player game object as seen above
which transform is it ?
wdym you cant set that up
because its in the hiearchy
if the player prefab was placed already in the scene you can only add scene references to that player in the scene
how do you spwan it
from the playerscript using instantiation
you havent sent that
so you want to pass target to the couscousInst?
so basically i launch it from the player and it uses the seek to go to the middle point basically
okay but that doesnt answer the question nor does it say how is the "middle point" target created
just from what I seen so far
CousCous couscousInst = Instantiate(CousCousPrefab, SpawnPoint.position, Quaternion.identity);
couscousInst.target = myTarget
other than that you need to explain more, in your mind it makes sense. To someone outside looking in you have to explain exactly what you want to do
so basically the player launches this power up from the spawnpoint position (in front of the player), it uses seek to go to the middle of the screen(target gameobject) to destroy all enemies(that part is not implemented yet). what i am having a a hard time with is using the targets transform properly
using the targets transform properly
in what way ?
is target already in the scene? or is it created at runtime
its already in the scene its the empty gameobject in the middle and its at the bottom of the hiearchy
Okay so you need to find it at runtime, or if player is in the heriarchy already like now just assign it?
btw this is pretty inefficient to do every frame..
GameObject[] enemiesArray = GameObject.FindGameObjectsWithTag("enemy");
if the player is already in the scene like you have it now, assign it from the instance in the scene then pass it that way.
Otherwise you need a tag / component you can search for at runtime
im not really worried about finding the enemies right now im just trying to find a way to launch this missle from the player to reach the target
alright well the answer remains the same
pass the reference on instantiation or do a search at runtime (less efficient)
thank you i will look into these options
Trying to get player to rotate based on my mouse position but it wont follow my mouse, only rotates towards the position of the mouse where it was when i start the game when i move the player
what have you tried
This is the code
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float playerSpeed;
public Rigidbody2D rb;
private Vector2 moveDirection;
private Vector2 mousePosition;
[SerializeField] private Camera sceneCamera;
// Start is called once before the first execution of Update after the MonoBehaviour is created
// Update is called once per frame
void Update()
{
ProcessInput();
}
void FixedUpdate()
{
Move();
}
void ProcessInput()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized;
mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
}
void Move()
{
rb.linearVelocity = new Vector2(moveDirection.x * playerSpeed, moveDirection.y * playerSpeed);
Vector2 aimDirection = mousePosition - rb.position;
float aimAngle = Mathf.Atan2(aimDirection.y, aimDirection.x) * Mathf.Rad2Deg - 90f;
rb.rotation = aimAngle;
}
}
try
mousePosition = sceneCamera.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0
"'Vector2' does not contain a definition for 'z' and no accessible extension method 'z' accepting a first argument of type 'Vector2' could be found (are you missing a using directive or an assembly reference?)"
There's no Z value of a Vector2
It's got two dimensions, hence the 2
oh wait it was already vector2
ScreenToWorldPoint returns a Vector3, you should store it in a Vector3
mybad
yeah idk player just rotates to the spot where mouse was at the start but wont follow mouser
wont follow mouse*
i feel like theres nothing wrong with the code but idk
the aiming or the movement wont follow
so i can move the player normally with wasd, but it wont rotate and aim towards mouse
just rotates automatically to where mouse was at the beginning
where it clicked "play"
Is your camera perspective or orthographic?
just curious, can. you try this rq
rb.transform.right = aimDirection
or use .up if your forward is the green arrow
orthographic
and no that didnt fix it
are you sure this script is running after?
Okay so it wasn't what I thought, you shouldn't need to add an offset to the mouse position
and it moves fine throughout ?
yeah movement is fine, its just the rotation thats wacky
can you show whats happening in a video? might be better to understand problem if we can see whats goin on
sure give me a sec
nvm i found the problem
i had the script in twice somehow and one of them didnt have the camera on it
you have an error
right
keep the console window docked
never hide the console
its easy to miss errors at the bottom
haha almost a case of rubber ducking
what is this ?
objects
the square paracetamol object is falling and spinning
how do i make it not spin
please explain the full problem and what it is you tried doing to fix issue and whats not working
lock the rigidbody rotation
ok gimme a sec
wait do u mean like the freezing rotation thingy in the script
also wtf is up with that mass..
ok so rigidbody2d 1 (the square paracetamol) can jump and all that and when i put it at the edge it falls to one side thus spinning
i was tryna fix it
yeah you gotta lock the z rotation
the square paracetamol?!
to stop it spinning
ohh
it works now thanks
but when i hold right
it makes me stick
to the thingy
welcome to physics
thats probably cause of the mass being so high
i made it less
nah its because ur constantly applying velocity into a collider
ah
in real life that doesnt happen
do i HAVE to do physics in unity
you either not apply force if you have obstacles inront of you
or use the physics material trick
yeah im finishing this project and never touching programming again 😭
more of a physics thing than programming
oh yeah you could make the material slippy
can i do that with the ray thing
yup
if you make the material slippy it wont be getting stuck and itll just slide along
can i change how slippery it is
depends on usecase. physics material with no friction is the easiest
ray is the cleanest
if this is a quick project stick to no friction physics material I suppose
should i do all this or should i just make the material slippy
physics material with no friction is slippy material
thats up to you , like i said
if you find coding hard then physics material is the easiest
otherwise you use the rb.SweepTest or Casts
so i just set the friction to 0
id just google how to make materials slippy in unity
alr
i find both hard
theyll explain it a lot better than i can
well not HARD
but like
coding is alittle complicated and i don't wanna do anything related to the 3 main sciences
thats a lot of game development unfortunately
yeah i figured
this is my LAST time touching coding
actually maybe not
cuz im taking cs as one of my classes next year so i am able to skip chem bio and physics
could always do visual scripting if writing code isnt to your liking
I find it kinda funny how most cs graduates know barely any code or how to actually create a game / application
here I am with a culinary degree making games and apps lol
though you gotta give to CS there is a lot of good theory, but a lot of students have just that.. All theory and no practical real world usecase
(this isn't a slam at you btw, just general observation it reminded me of)
criminal justice degree here!
that was my intention.. but here i am 🙂
were you talking about me
i never took cs
i meant next year i will have to as a resort to ditch the basic 3 sciences cuz they said minimum 1 science
for just this year?
nah I specifically said not you, but you mentioned CS and reminded me of that
wdym
this semester i mean..
im taking cs next year
i remember needing to take atleast 1 science class per semester
i was just curious how it was for u
for grades 11 and 12 we have an IB system and i can pick SOME subjects
AND I CAN FINALLY DITCH CHEMISTRY
AND NEVER DO IT AGAIN
lol.. chemistry involved soo much writting i remmeber 😭
damm what school. lets you do CS
they said min 1 science and i can pick from chem bio phys and cs
my school sucked and never offered anything even close to STEM
phys is a great option imo
we have 2 stem classes per week
like currently at my grade
lucky then
if u plan on going into game-dev i would say do both physics and cs >8)
its so ass bruh the teacher barely teaches us anything 😭
welcome to the real world
thats usually the case for an underpaid teacher
oh hell no i ain't doing game dev
i wouldn't say my teachers at my school are underpaid
most teachers are
yeah but not at my school
only college professors usually care about teaching cause they usually get paid big bucks
(not community college ofc)
i found it to be different..
once i hit college it seemed like the teachers could care less..
its your money.. go to class or not.. they'd not be affected a bit
what country should i go to for a college for finance or economics
depends how much tuition was too
if teachers get paid big and you're not learning there are complaints usually . Take schools like havard or NYU
USA
UK, Switzerland
yeah but like each year the country gets worse bro i WANTED but im starting to rethink
😭
Swiss manage rich people money
is switzerland fire
it is but prob almost impossible to go there as outsider
yea, USA and UK have Wall Street/ London Access
global economics i'd go UK or Switzerland
i wish i knew what that is
If you're not here for Unity development questions, please don't take it off topic.
my fault gng
ops yeah we got. bit carried away here
guys how do i add the physics material onto my object 😭
none of the yt tutorials are telling me
Drag it onto your collider* component
com on is that hard to do
"2d physics material"
I forget now
I DID I PROMSIE
put it on the collider
there isn't like a clear tutorial they just explain what it does
make sure its physics2d mat not physics material
oh com on thats rubbish
you're telling me the entire internet and you cant find, how do you think we learned..
maybe.. just MAYBE i only went through 2 youtibe videos but like i have no patience unfortunately
ohhh
well thats a problem with todays generation
you all want things handed to you without doing some critical thinking work to put effort into
2 youtube videos isn't the entire internet. You have a search engine that gives results into other pages and articles, the info is there. you just don't search thats laziness
these are important skills even outside of coding..
now with all this GPT / "AI" crap everyone wants fed answers and not think for themselves.
just learn by doing.. for example lets take the rigidbody material..
theres only 2 variables on it.. so u can assign it to the rigidbody.. using context clues
then can tweek those variables around to see what happens..
there.. you've already figured out what the physics material is.. where it goes.. and how it works..
never had to leave the engine 🙂
Yup got that at work today. Dude wanted to convert a CSV file into another format, and historically to do it they just "ask the AI", except said AI is blocked by IT now, my man was completely lost 🤣
ahahah!! Tiny Victories 🙂
yeah its becoming pretty fdup we are letting algorithms dictate our knowledge as some absolute truth. Its a scary path
pretty much
so basically if LLMs went down the newer generation have no more knowledge cause who remembers fed answers when you just wanted the solution
real
I mainly use it today to find obscure api functions that I keep missing (looking at you Roslyn generators), or to make a like 300 field enum from a provided list from a website because it would take me way longer to do it by hand lol (then I validate the values afterward) 
fair enough but you have the extensive/ experitse knowledge to recognize hallucinations
i treat GPT like a very uhhh obedient secretary lol
"I need a list of 300 names in Json format pronto! "
The list in question was this fun page https://docs.unity3d.com/Manual/ClassIDReference.html
oh god this makes me realize how much stuff really is inside of unity manual that I havent even touched yet
i get that same feeling when i expand the Gizmo's panel
Still mad it took me years to actually realize the gizmo icon pngs in the dropdown were the real toggle
They still do not look clickable
yeah some UX choices in unity are rough
I'm getting this error even though I set what it is earlier in the script
this is the line causing the error
well does that gameobject have an animator?
so Animator isn't found on this gameobject
yes it has the animator
show
and the animator also has a controller assigned
either that or you placed another of this script somewhere else
Debug.Log(anim);
add context so you can see whos logging it
Debug.Log(anim, this)
ahh yes context 🙂 we all love context
where should I put that? at the error code?
put it before the anim.Play line
somehow it doesn't even log
Put it before the line that throws the error
I have
If you've put it in Start, before the line that throws the error, and nothing prints then nothing in the scene has that script on it
that's not possible though, the object is there and it has the script
have you saved and recompiled
Show code, show console
doesnt Start disable the script if there is a nullref somewhere in the start method
place ur bets 🎰
console is just this each update, the debug.log doesn't show even if I put it in start (which I have done here)
To be fair, we don't actually know where the error is
entire script
no, but it'll stop executing after the null
call it before u try using anim
anim.speed
I couldve sworn one time I seen when accessing something null it would disable the script (in Start)
before that ^
If there's no long from Start, then nothing has this script
Chances are, it is logging. Did you actually scroll to the top
this does rely on another script called dialogue but no changes have been made to it
yes
it's the same all the way around
and as I have said before, an object called Dialogue has this script and it is not destroyed on starting the scene
comment out anim.Play then
that log should go in Update
What is the first error in the console
okay progress
still no log but the error disappears, now I have a completely seperate one
Because anim.speed will throw an error if anim is null
and we said to put the log before the error, including the one that's scrolled off the screen
I think this is just because gamestate is from a previous scene and is dontdestroyonload
so its not found that component
I'll try doing it from the other scene
you cannot GetComponent on a null object
progress bb
okay so no error and the debug log appears if I load it from the title screen (which goes into cutscene1)
only problem is now the dialogue box just disappears
AND NOW IT DOESN'T??
WHAT
fantastic, now it doesn't animate to show the different character faces and names
takes money to make money
oh its because I commented it out I'm dumb
So I have problem with one of my enemey's just going through soild walls and not sure why this is happening
but it needs to be commented out if I don't want exception
how are you moving the character?
transform.position =?
if its navmesh u need to exclude the walls from the surface so it bakes around it
this turned out to be the usual unity culling things and needing to put them on different layers for no reason and somehow it all works, thanks for help
nobody knows anything without you showing the setup.. Think about that for a moment
we dont have crystal ball
Fair enough, the only idea I have to show you is this but that's all I got
As the code shouldn't affect the collision
how are you moving it
this is totally incorrect
if ur using translation.. as i mentioned transform.position =
it does not respect collision.. and will shove ur colliders into each other
it might
Which would make sense but the other objects that have the same code don't do that
show the code
this alone tells us its just a rigidbody
Check out the Course: https://bit.ly/2S5vG8u
Discover 5 different ways to move your Unity3D gameobjects, see some of the differences between them, and learn which one I usually use.
More Info: https://unity3d.college
check this out
well no shit
do u need to borrow my crystal ball?
its phasing through walls because ur teleporting and not using the rigidbody
apparently it works better than mine yeah
You can still use MoveTowards but yu cant use transform.position =
one of these
But the question is why is it only the one and not the others?
maybe the speed..
luck
if its moving slowly theres a chance that the collider would realize ur intersecting it. and shove it back out
if its moving too fast.. u pass the point of no return and it'd shove u out the other side
you're basically teleporting without the rigidbody
the rigidbody will catchup on the next physics frame
by that time you might have already went thru the wall
I see, well thank you
is there a way to limit the scope of a FindObjectOfType to a specific scene?
I thought it was scene bound
maybe the other Find methods are ig
you can do a FindObjectOfType with 2 scenes open (as long as they're both open) and it will find a cross scene reference
It's how you get around inspector cross scene references
oh interesting... the other Finds dont do that iirc, i wonder why
FindObjectByTag for example iirc doesnt do cross scene
maybe do a Scene name check?
thats dirty as hell tho
FindObjectOfType has been deprecated
if(myscenename)
FindObjectOfType
WAIT
Unity says thats slow...
wTf
Note: This function is very resource intensive. It's best practice to not use this function every frame and instead, in most cases, use the singleton pattern. Alternatively if you only need any instance of a matching object rather than the first one you can use the faster Object.FindAnyObjectByType
I figured I could parent everything in a scene to one GO, but I don't really want to modify everything in the scene
yea, i think its fine for initialization methods tho
THEN WHY DID YOU EVEN PUT THIS UNITY OR SUGGEST IT IN THE DEPERCATED API
because you can limit a search by gameobject children
^ yea lots of things u can do with it
why wouldnt they just put FindAnyObjectByType as primary and then offer the other as more "deep" results
silly
suggesting the more resource intensive version first is backwards imo
maybe FindObjectOfType used to get the first one so it's offering the equivalent first?
idk just guessing
the warning is basically this
Note: The object that this function returns isn't guaranteed to be the same between calls, but it is always of the specified type. This function is faster than Object.FindFirstObjectByType if you don't need a specific object instance.
i remmeber changing all mine over to the FIndFirst
i honestly havent noticed any longer load times
this is basically the same traditional FindObjectOfType
FindFirstObjectByType i guess has to check the instance ids or whatever to check who was first component added?
unity just says "Resource intensive" pretty vague lol
probably no big deal doing it once in Awake/method regardless
my loading screen masks any of that anyway
sometimes
I was thinking about this the other day.
I have a random generated 2D map, I want to add a loading scene but I want cheeky words on each step
i got u
Learn how to design and implement a loading screen in Unity!
Making Progress Bars: https://www.youtube.com/watch?v=J1ng1zA3-Pk
Custom Playables In Unity: https://www.youtube.com/watch?v=12bfRIvqLW4
Strategy Game Camera Controller: https://www.youtube.com/watch?v=rnqF6S7PfFA
----------------------------------------------------------------------...
here ya go.. this is hte one i used.. he goes into great detail
and shows how to do random stuff while u wait
this dude has good vids
very very good
I found a starting point that works for my specific case. I'll be mocking up a demo with some metrics https://discussions.unity.com/t/find-gameobjects-in-specific-scene-only/163901
easy as this @rich adder
should I put the time be actual loading stuff? cause I dont have that much it will probably load too fast
I was thinking to like just fake the loading to a specific time
i have mine setup... but i use coroutines to fake it
as i dont really have enuff stuff to load to cause actual progress
same
my level generated 10 rooms in the beginning the rest are spawned in after
mine just loads gameobject by gameobject
this is my level boiler plate..
as long as i keep this structure (w/ the gameobjects) the loading screen works on ever scene
😉
hes a phony! a big fat phony! 👉
IEnumerator UpdateAdditiveSceneProgress()
{
totalSceneLoadProgress = 0f;
for(int i = 0; i < scenesLoading.Count; i++)
{
while(!scenesLoading[i].isDone)
{
foreach(AsyncOperation operation in scenesLoading)
{
totalSceneLoadProgress += operation.progress;
}
totalSceneLoadProgress = (totalSceneLoadProgress / scenesLoading.Count) * 100f;
LoadingBar.fillAmount = totalSceneLoadProgress * 0.01f;
LoadingStatus.text = "LOADING FILES"; //loading scenes
yield return null;
}
}
}
IEnumerator UpdateSceneInitializationProgress()
{
while(currentSceneInitialization == null || !currentSceneInitialization.isDone)
{
if(currentSceneInitialization != null)
{
totalSceneInitializationProgress = currentSceneInitialization.totalProgress;
}
int sectorIndex = (int)currentSceneInitialization.currentSector;
// Scene initialization *is done*
float totalProgress = Mathf.Round(totalSceneInitializationProgress);
LoadingBar.fillAmount = totalProgress * 0.01f;
LoadingStatus.text = sectorLoadingStrings[sectorIndex];
yield return null;
}
StartCoroutine(FinishSceneLoading());
}
``` heres the meat and potatos of it
tbh its been so long since i made it.. i forget how it works
this is important.. my past self probably thought..
mine generates almost Instant. So I def need a fake loading lol
ya u do
for something like that u can probably find a decent magic number to randomize around
3 seconds or so +/- 2 more
if u wanna make that loading system it doesn't take too long
ya I think maybe 5-6 seconds should do. I just feel bad punishing someone who has a fast pc compared to one with slow pc
it does require u to use additive scene and async loading
so it may not be something for you
Esc button override 😉
i noticed earlier that SOT lets u escape out of its intro cinematic..
Could time the loading itself and then enforce the minimum time, if you must do this
true.. Thats why i was thinking combining actual resource loading + some varied time
found out about 200 hrs too late
yaa this is a good idea actually
Danny always got legit ideas when he pops in 😃
i got code for ya to time it if u want 😉
mine takes 4 seconds for empty scene
oh i also used Actions too ^ each of those "Category" gameobjects could or could not have actions
ohh yeah this is good idea
they do various things.. like turn on lights.. make sounds.. etc
makes it nice and re-useable
I need to prewarm my pooling
unity poooling doesnt have an options 🥹
i enable the world.. b/c i was trying to find things to slow down my loading bar
lmao
doesn't really do anything
the only thing ive found that actually slows it any
its already in memory
is For Loops
If you did a Streamable assets I think you can Async load that to put a loading
each container just enables a sub-container
i think i was trying to make myself feel like i had accomplished something that day
im about 84% ready to learn about these
yeah its very good if you're trying to load big files , i guess in 2d no big deal but in 3D if you want to load an entire environment later or those type of big files late its a good usecase to speed up initial load time
awesome ! feeling inspired again to continue this project now, got decent ideas from here
i always thought they were for DLC stuff
oh yea they can be also used to remotely download a file too
but thats also in the realm of Asset Bundles iirc
guys i gave my wall zero friction so now my object can't stick to it. i tried giving it a little bit of friction so it can slide slowly but it doesn't work
is it because the friction is combined or?
why did you give the wall 0 friction
it was supposed to be on the collider of the moving rigidbody..
^ put it on the rigidbody ^
because i don't want stuff to stick to it
ohhh my fault
ya, but then ur constantly having to add that material to everything u add
vs just the 1 player
i only wanna add it to walls but i want the player to slide slowly down walls and walls only
and adding it to the player doesn't fix my problem
show
i can't figure out how to make it just slide slowly
what you did
wdym slide slowly?
what specifically do you want me to show you
what you setup so far
likee
strafe
is that the word
like slide down the wall slowly
when holding right
on the wall
then you need some type of raycasting
u may need to manipulate the physics material w/ code
or that ^
when on ground -> this material
when against wall -> that material
which one is easier
you probably still need a cast to figure out when you're on wall slding down
u mean like i switch the material of the player when im on the wall?
and switch it back when im on the ground?
currently im trying to lower the friction of the player generally but it doesn't seem to change anything
when i put the friction > 0 is just sticks and when its 0 it just slides normally and not slowly like i need it to
how do i fix ts
where are u putting the physics material
rigidbody 2d like u said
isn't that just the same as average
yea
thats what im thinking.. its similar but not the same..
so whats the problem with this
average has different ways iirc. Mean is the typical one we know as adding all numbers and devide by that
1, 2, 3, 3, 4 average = 2.6
the mean i think is 3
thats median
i tried putting it in both boxcollider and rigidbody and noneof them worked
yeah okay so average has different averaging "modes" ?
lmao.. i have a new mission for today
hmm..show the physics material on the collider and its settings
dont add it to both the collider and the rigidbody
the rigidbody automatically covers all colliders
and the value of friction goes from 0 - 1 just so u know
.1 probably is barely noticeable
does anybody know how can I prevent this while flipping my character?Should I just flip its head?
you tried 0 ?
not sure what ur asking?
yes and it doesn't slide like i need it to
ok so it is working tho
you said it dosnt affect it at all
also because weapons check velocity to damage, when ı flip they do damage because they have velocity.
try to make it 1 and make sure its actually working
once u know its working move to code
i need it to slide slowly and when its anything above 0 all it does is stick
i meant that it doesn't change based on what i do with it
I mean 2 characters intertwining
wdym "what you do with it "
like there isn't a difference in the friction as long as its above 0
theres different Collision Detection modes..
if its still sticking 0.1 try a lower value or youd have to manually code the falling by overriding the velocity
0.1 is the same as 0.9 etc etc
maybe u can use a more accurate method to detect collisions to stop it
else u might want to use a bigger overall collider
0.1 isn;t the same as 0.05 or something is it
so they cant get close enuff to each other to have their limbs twist together
you may just want to change ur gravity and be done with it 😛
how does it work?
if (isWallHit && !isGrounded) // Stick to the wall
{
velocity.y = reallyLowGravity;
}
ok its KIND OF working now it turns out that i had to reput the physicsmaterial in the rigidbody plkace after each try idk why but now its fixed
i just need to look for the perfect value which will take some time
and im putting it on the wall only this time
else
{
velocity.y = normalGravity;
}```
Fine Tuning!
glad u got it figured out
experiment
I thought about adding a big box collider over the character and only making it active the second Im flipping but havent tried yet
the heart of dev
0.1 IS the same as 0.05 when put on the wall
these dont really go on the wall but the player itself
uhm how can i make a IEnumerator run smoothly based on time.timescale?
i just put it back on the player and it stopped working
so now its 0.01 but still doesn't work
i forgot sorry
huh ? what are you even trying to do here
i had a problem like this yesterday... Ienumerator wasn't fast enuff so i had to use Update loop timer..
wdym "smoothly based on timescale?"
i wrote the yield return just as a placeholder, idk how to make it stop based on time.timescale
but thats not the same issue as here..
why not use WaitForRealSeconds
or w/e that is
WaitForSeconds literally is based on timescale
scaled time
oh so i just make it 0.1f and if time.timescale = 0 it will stop?
yeah its not gonna go anywhere
i mean, not run
the manual explains it better than I canhttps://docs.unity3d.com/6000.0/Documentation/ScriptReference/WaitForSeconds.html
@rich adder @rocky canyon both average and mean have several meanings, but the most common meanings of both are the same, arithmatic mean µ = 𝛴𝑥/𝑁
yield return new WaitForSeconds(1f);
yield return new WaitForSecondsRealtime(1f);
ya, i did some researching
it seems in most cases its almost the same
ya seems so what i read too
its confusing how the material has both options tho
still trying to figure out what exactly is the differing factor
"mean" is the mathematical term and there's also geometric and harmonic mean
where did you find it?
hey, this should make proyectiles enter into their parry state, but they dont, what im doing wrong?
private void MeleeAttack()
{
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, demons);
Collider2D hitProyectile = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, proyectile);
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
}
}
if (hitProyectile != null)
{
if (hitProyectile.TryGetComponent(out MortemRifleProyectile enemy))
{
enemy.Parry();
}
}
}```
proyectile:
```cs
using UnityEngine;
public class MortemRifleProyectile : MonoBehaviour
{
public int damage = 5;
public Rigidbody2D rb;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.TryGetComponent(out ValeriaController enemy))
{
enemy.TakeDamage(damage);
Destroy(gameObject);
}
}
public void Parry()
{
Debug.Log("PARRY");
}
}```
Physics Material
physicsmaterialcombine only has average
https://docs.unity3d.com/ScriptReference/PhysicsMaterialCombine.html
wall of code
2D** mybad
what is the context here?
ahh soo thats what it is
ah, you just posted it
start logging
mmhmm
Aha
i think Chris has the solution tho..
Geometric mean strikes again
Geometric mean
whats logging
wdym whats loggin ?
Debug.Log what else
the first step to solving any problem
deforestation, obviously
oh no, i already did
no you only logged the Parry function
you havent logged anything useful before it gets there
Mean algorithm used is: SquareRoot(valueA * valueB)
Average algorithm used is: (valueA + valueB) * 0.5
@swift crag @naive pawn @rich adder
ah, you mean to also Log the parring of the weapon?
You have to log everything you added
step by step and see where its going wrong
yeah that's geometric mean and arithmetic mean respectively
Log the line!
dont just put random useless strings
log until u get something u dont expect
put the actual objects to log
then u found the crack
TIL 🧡 thanks for clearing that up
makes sense, well, thanks
also gizmos you can use for those overlap
void OnDrawGizmos(){
Gizmos.color = Color.yellow
Gizmos.DrawCube(machetepos.transform.position, range);
}```
but i already have Gizmos
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Gizmos.DrawWireCube(machetepos.transform.position, MacheteRange);
}
}```
ok so where its drawing at
if its correct pos/size in game, your layers are either wrong or something else
could also be hitProyectile.TryGetComponent(out MortemRifleProyectile enemy) is false
or the nullcheck
but i mean, now it works
🤷♂️
dont look at it for too long