im doing a course on Udemy and there is something that don't make sense to me.
we created a weapon script https://gdl.space/azovihujol.cpp
and added dropped weapons from dead enemies (cool) but they are also moving and shooting even before I picked them up (it make sense since we didn't check anywhere in the code if the are equipped)
am I missing something?
#💻┃code-beginner
1 messages · Page 77 of 1
the next code snippit also doesn't work:
Sorry, I read again, yes I think it's a typo in the method code
cntrl dot to add the namespace
this stuff is so frustrating, I have no experience with this, there's no explanation, just a random code snippet that doesn't work, dunno where to put it, what to do with it, why it doesn't work, what it's purpose is ...
which one?
upper one
ah gues the first lol
well at least all the errors are gone, let's see if it works lol
Yo guys,im. Creating a card game and im using horizontal layout group,how can i make the cards in hand to have that curvy while still using hlg
You're going to be fighting against the layout group if you want to keep it only for the horizontal position.
But anyway, if you do, then you need to move the card as a child object of the parent that is controlled by the layout group.
You would offset the child position (vertically) and rotate it. The amount you would, would be a lerp between default position (no movement) to max movement based on how far from the center of the layout group the card is.
Will i win the fight?
quite magical, but maybe just a visual shader that curves them ?
also have some things i dont understand about FindGameObjectWithTag
can 🥲 🙏🏼
I Dont realy wanna use shaders for that,but thank You anyway.
can someone help me set up Steam login? I have no idea what's going on or how to use this, been re-reading the page for an hour now and I still don't understand how I use it to log in a player
https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-steam
Is it good practice to split FSM for character controller state and animation?
Usually all that logic runs in parallel
the blend tree is basically a FSM machine anyway, but it's still useful for when you need to blend stuff together
#854851968446365696 use ` 3x before and 3x after ur code block
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
can you like edit 1 of the message with a link and delete the rest?
a powerful website for storing and sharing text and code snippets. completely free and open source.
its kind of obnoxious
why am i tagged.. Anyway can you at leaaste delete the old messages so i dont have to scroll all the way up?
not 3x but this symbol: `
3 times before and after -_-
hey, I'm generating a new weapon with
Instantiate(weapon, transform.position, transform.rotation, transform);
but it seem that the components are not active
why is that?
because whatever weapon is has them off by default prob
i don’t have it in my keyboard
dont matter dont use code blocks for large code @novel shoal
when the player flips it fades away and i cannot see it anymore
fades away? nothing here fades anything
it flips and i cannot see anything anymore
also you do not use != on float numbers
but everytime i used Instantiate on prefubs so far it has them on,
so how do i activate the script and box collider?
i was watching a tutorial
well its wrong
okok
what is weapon exactly
find a better tutorial and try again
right how do i do that
i shown you
Hi... A question for all those Math lovers.. I have a sphere droid with different cannons around it (a cannon is a a child transform that looks outwards). What is the right formula to rotate it so a random cannon will face front?
oh and the var is a prefub
show what projectile is
this?
yes its an example. do you see why it "locks" enemy not to float
not really
@zenith acorn Don't DM me randomly, it's against the rules. Ask your questions here
and this is the code of the projectile
https://gdl.space/ahiqasivev.cpp
btw destroy has a timer so u dont need invoke
Destroy(gameObject, lifeTime)
so witht that when its moving it cant jump
which one is the one that spawned Close Weapon(Clone)
yes you have to tell it to do that properly
but we want to Instantiate the explosion only after that timeout
you can run method OnDestroy()
which runs automagically when object is destroyed
how do i do that
it wasnt spawned, i put it there manually
and once i picked it up i destroyed it from the
pickupscript https://gdl.space/nehofuziyu.cpp
and destroyed the held weapon and then instantiated the equipped
how do you make it jump now? its the same thing execept it doesnt follow player on y
nothing much changes
this is my jump code
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
isGrounded = false;
animator.SetTrigger("Jump");
Can someone please help me set up Steam login? None of the code on the docs page is working for me ... Been at it for 2 hours now ... 😭 #1177962063503573053
does your player jump properly?
but how you determine when to jump?
private IEnumerator BounceTowardPlayer()
{
while (true)
{
// Wait for a random duration before jumping again
yield return new WaitForSeconds(Random.Range(0.1f, 0.5f));
// Jump if the enemy is grounded
if (isGrounded)
{
Jump();
}
}
}
my enemy is a slime thing so i have it look like its bouncing
is one of these part of the scene already?
Random? Every cannon has its own position. You can choose a random one from them
then just rotate using a coroutine with lerp
Quaternion.FromToRotation can be useful here
each cannon will have their own target rotation
like (0, 0, 0), (90, 0, 0), (180, 0, 0) and (270, 0, 0)
Something like this could workcs List<Vector3> directions = /* list of directions corresponding to the cannons, in local space */ int index = Random.Range(0, directions.Count); // Random direction idex Vector3 dir = directions[index]; Quaternion lookRotation = Quaternion.LookRotation(enemyPosition - myPosition); lookRotation = Quaternion.FromToRotation(Vector3.forward, dir) * lookRotation;
Untested, might need to flip the last line
And yeah, using rotations instead of directions is an alternative like password123 said
I wonder if they want to find the nearest cannon to the enemy
this way the target rotation should be lookRotation - nearestCannonRotation
I suppose
Thanks. I don't mind it not being the nearest cannon. I just tried so many calculations and it doesn't work right
I will try to play with the @verbal dome code and see. Thank you!
You gotta modify it a bit, put the directions declaration in the class (not in the method), randomize index only when you want (not in Update)
And the left & right side of the last line might have to be flipped, I forget how Quaternion multiplication order goes
I'm trying to Instantiate a prefab of enemies but all enemies share a healthpool and i cant interact through C# with any particular instance, just the prefab itself.
don't interact with the prefab itself
well yes, but how would i do that ?
You actually get the reference to the object when you instantiate it
store it somewhere safe
im REALLY a beginner, no clue how to do that either
You've written anything, specifically for instantiating those prefabs?
yes
post it
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
public class Gameplay : MonoBehaviour
{
public GameObject enemy;
public GameObject enemyContainer;
void Start()
{
enemy.GetComponent<EnemyHealthTracking>().health = 100;
CreateEnemies(3);
}
void CreateEnemies(int enemy_amount)
{
for (int i = 0; i < enemy_amount; i++)
{
GameObject enemyClone = Instantiate(enemy, new Vector3(i, enemy.transform.position.y, i), enemy.transform.rotation);
enemyClone.transform.parent = enemyContainer.transform;
enemyClone.name = "Enemy" + (i+1);
}
}
}
GameObject enemyClone = Instantiate(enemy, new Vector3(i, enemy.transform.position.y, i), enemy.transform.rotation);
Alright, so you do get the reference to the gameobject here
You don't actually store the reference is the problem, unless you're accessing it from elsewhere
How are you doing damage to the enemy. Can you post that?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealthTracking : MonoBehaviour
{
public int health = 100;
public void TakeDamage(int damage_ammount)
{
health = health - damage_ammount;
Debug.Log(health);
if (health <= 0)
{
this.gameObject.SetActive(false);
}
}
}
it wouldnt let me delete it since i was trying to delete the prefab thats why its disabling it instead
So, your prefab has this component on it, yeah?
yes
Now, what method are you using to grab that specific gameobject instance that's now on the scene.
collider detection, casting, ect
raycasting yes
I have seen people use lerp speed for a health bar, is it necessary to use it?
Aight, let's see that one then since everything else looks fine
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using StarterAssets;
using UnityEngine;
using UnityEngine.InputSystem;
public class Take_Damage_Enemy : MonoBehaviour
{
public EnemyHealthTracking enemyHealthTracking;
public StarterAssetsInputs starterAssetsInputs;
void Start()
{
this.gameObject.SetActive(true);
}
public void DealDamage()
{
Debug.Log("yes");
RaycastHit hit;
Ray ray = Camera.main.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0));
if (Physics.Raycast(ray, out hit))
{
Debug.Log("no");
enemyHealthTracking.TakeDamage(20);
}
}
}
Heey, does anyone knows how can i export terrain textures on a jpg to apply them to a plane? 🧐
Ok, here your logic is a little off. You're caching a single enemy instance first off, and additionally your ray is not doing much as you're dealing damage to that specific instance no matter what when you enter your hit statement there.
what should i implement instead ?
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
if (hit.collider.CompareTag("Enemy"))
{
EnemyHealthTracking enemy = hit.collider.gameObject.GetComponent<EnemyHealthTracking>();
Debug.Log("Enemy hit is: " + enemy.name);
}
}```
something like that
I suggest layers instead of tags though
which you should watch tutorials of
But to clarify what I'm doing here is I grab info from the hit and check if these gameobjects of these colliders have this class type instance (their hp class)
thank you for the help, while you were typing that up i found a solution on the forum since i knew what to look for
i found this on a forum
yeah, there's a lot of info out there for this stuff
should remove this too:
public EnemyHealthTracking enemyHealthTracking;```
as you shouldnt need to store a 'single' instance of your enemy here
you'll get their instances/references on demand from the cast
Is it possible to have a script run on a de-activated game object at all? As strange as that sounds.
de-activated should just stop update and other unity methods
thanks, leftovers from before i edited the code for troubleshooting
Yeah thats the problem I suppose.
Was hoping there was like a [AlwaysExecute] type thing.
Specifically, the problem I'm trying to solve is that, sometimes, when modifying the UI, I'll disable objects that need to be re-enabled.
And I'll forget lol. So, was hoping to just toss a script on them.
if you need like coroutines to run, you can make like a singleton manager that re-enables the UI objects
I do something similar
No, ExecuteAlwaysAttribute executes the active script in edit and run modes, ExecuteInEditMode just in edit mode.
Oh, do coroutines still run? I thought they didn't.
coroutines don't break when GameObject becomes inactive
my coroutine manager too sweet to remove though ;)
I have a script where when i left click a gameobjects follows my mous movement. but wenn the size is negativ you cant see the gameobject
How could i fix it ?
I am sorry, I've made a mistake. Coroutines aren't stopped if the MonoBehaviour script is disabled, but they're stopped if the associated GameObject is disabled or destroyed
so you don't have to remove your sweet coroutine manager
I'm not too sure with using the UI tools honestly
yes, because you're setting it a negative size
could you, please, show your code?
basically you have to abs your GameObject's size
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Vector2 size = mousePos - initialMousePosition;
selectionBorder.GetComponent<RectTransform>().sizeDelta = new Vector2(size.x, size.y);
Vector2 checkScale = new Vector2(size.x, size.y);
selectionBorder.GetComponent<RectTransform>().anchoredPosition = (mousePos + initialMousePosition) / 2f;
"You can’t have a rectangle with negative dimensions.
What you need to do is create a rectangle that has positive dimensions starting from the point where your mouse is to the point where the drag operation started.
Basically, when your mouse X and / or Y are negative you will be redrawing the rectangle FROM CURRENT location of your mouse pointer to the START OF DRAG location.
In cases when they are positive then the logic stays as you have it since your are drawing the rectangle FROM START OF DRAG location TO CURRENT mouse position."
Unity Discussions
Now that I understand the question, here’s your answer: http://docs.oracle.com/javase/6/docs/api/java/awt/Rectangle.html A Rectangle whose width or height is negative has neither location nor dimension along those axes with negative dimensions. Such a Rectangle is treated as non-existant along those axes. Such a Rectangle is also empty with re...
If I were to do it I'd just draw my own quad honestly
You have to store the delta. Your sizeDelta has to be Mathf.Abs(delta) and anchoredPosition - delta / 2f
please, note that it'll work just if both of your pivot is exactly (.5, .5)
if you need to change your pivots for some reason, you'll have to implement additional logic
Thx
does it work now?
yes
you should also store your RectTransform as a variable
and checkScale is redundant
Basically all that has to be changed is a anchoredPosition
"Just make your sizeDelta to be always positive and multiply the anchoredPosition according to the pivot"
That's how you change your anchoredPosition regardless of the pivot
offset.x *= _stretch.x == 0 ? 0 : pivot.x + (_stretch.x > 0 ? 0 : -1);
offset.y *= _stretch.y == 0 ? 0 : pivot.y + (_stretch.y > 0 ? 0 : -1);
rect.anchoredPosition += offset;
where offset if the difference between previous and new sizeDelta and _stretch the direction
@steel pier in case you want to change the pivot
ok thanks
getaxis horizontal gets the arrows or the “a” and “d” keys
no, just right and left arrows
No, it gets A and D or the arrows unless you changed it in the input manager
Aren't arrows set as default?
They're both set as default
I see, nice
yes normally they can jump fine when i try and make it so they dont just fly to the player they have to move on the ground they cant jump
so what's the issue?
Hey, having an issue where this hit.transform.SendMessage("Hit", weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]); is supposed to return "Hit", int 20, but it returns 2[TKey,TValue].get_Item
when typing in "pistol" which is the key for the value 20, it works just fine
Using SendMessage is hurting you here instead of just calling the function normally
I was wondering if i could get some help with a small problem i am having, this script works great but the GameObject's in the Array are all being set to false when I press "E" on one of the objects which is not what i want to happen. Any help is greatly appriciated.
Thanks from Mplu3s. <33
i cant call it normally since its in a prefab and i need to interact with one instance specifically
Well you're literally looping over the whole array and deactivating them all so not sure why you are surprised
That's nonsense. You have a reference to it to call SendMessage on it. Use GetComponent and call it directly
hit.transform is already the specific object you want
Heey, does anyone knows if is there any way to export terrain textures?
im still pretty new to C# how would i fix this
Instead of looping just deactivate the single one you want to deactivate
will that even fix my issue ? i still want to use the dictionary to get the damage amount
We'll your issue didn't even make sense because it seems confused about whether the thing is a string or something else entirely. If you do things normally you'll get compiler assistance with the parameter typing and such errors will become impossible
the enemy no longer jumps
they just move on the x axis
i have no idea how
I just told you how
Use GetComponent
Then call the function on the component
it wont let me, or im doing it wrong
Definitely the latter
how should i do it ?
Call GetComponent on the object to get a reference to the component.
Then call your function on that reference
What does "it won't let me" mean
my function is in another script
Obviously
If you're having trouble with syntax you should share the code you tried and whatever errors you might be getting
the function in the other script wont show up
Is the function public?
ok thanks i thought it was when it wasnt
HeyHo;
that still doesnt fix my issue of the dictionary not working how it should though
Show what you mean
What you typed above made little sense
Just looked like the ToString output from the dictionary or something
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem.Interactions;
public class Weapon_Tracker : MonoBehaviour
{
public Dictionary<string, int> weaponDamage = new Dictionary<string, int>()
{
{"pistol", 20},
{"rifle", 35}
};
public string currentWeapon;
void Start()
{
EquipPistol();
}
public void EquipPistol()
{
currentWeapon = "pistol";
}
public void EquipRifle()
{
currentWeapon = "rifle";
}
}
Is there a way to reference/set a fixed Sprite in an Scriptable Object?
so that I don´t need to referenc it by draging the sprite in the field, when ever I create a new "instanc" of that SO?
Ok and where is the dictionary returning that weird thing you talked about exactly?
Set it in the script defaults
ok how do i do that ^^,
thats basicly where i fail ^^
im telling it to go to the dictionary and input "pistol"
Looks fine so far
Where are you seeing a weird result
Click on the script itself and look at the inspector
That error is very clear
The key "" isn't in the dictionary
Looks like you tried to pass an empty string in
You should be calling EquipPistol in Awake not in Start
Start happens very late
Thx totally forgot that worked
thougth i had to write it as code -.-
i moved it out and i declare it before anything happens
still the same thing happens
Because it's serialized
Do what I said
Put it in Awake
It will work
BTW this whole question was very confusing. You should have just shared this code and your error message from the start
Likewise you can set it in the inspector and it will work too
What
Why did you move the variable declaration
All you had to do was rename Start to Awake
From this code. Start -> Awake
ok
alright
thank you
sorry for the trouble
well nevermind, i had manually put in "pistol" to test it, putting the dictionary back, it throws the same error
you cannot access a local varible (a variable that's created in the method) outside of this method
yeah i fixed thta
also you cannot use an unassigned local string
I'll recommend you Exercism
well, this isnt a passion project i can put down for 2 months
Well getting other people to write it for you isn't teaching you either #justsaying
It's gonna take you much longer without knowing the basics
Ok, can you just show the whole thing?
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.InputSystem.Interactions;
public class Weapon_Tracker : MonoBehaviour
{
public Dictionary<string, int> weaponDamage = new Dictionary<string, int>()
{
{"pistol", 20},
{"rifle", 35}
};
public string currentWeapon;
void Awake()
{
EquipPistol();
}
public void EquipPistol()
{
currentWeapon = "pistol";
}
public void EquipRifle()
{
currentWeapon = "rifle";
}
}
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using StarterAssets;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
public class Take_Damage_Enemy : MonoBehaviour
{
public Weapon_Tracker weapon_Tracker;
void Start()
{
this.gameObject.SetActive(true);
Debug.Log(weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]);
}
public void DealDamage()
{
RaycastHit hit;
Ray ray = Camera.main.ViewportPointToRay(new Vector3 (0.5f, 0.5f, 0));
if (Physics.Raycast(ray, out hit))
{
hit.transform.GetComponent<EnemyHealthTracking>().Hit(weapon_Tracker.weaponDamage[weapon_Tracker.currentWeapon]);
}
}
}
Although that error would happen at runtime, and is caused by whatever is requesting it
I'm not sure if you've written it by yourself, actually
it does also happen at runtime
how do i reference a script from a scriptable object?
as in usual scripts, no?
well the raycast code isnt mine, but most of what i show there is written by me
cus i dont know how to do a raycast
wdym
or.. i didnt
Not sure if this a code question but does anyone know why my tilemap might be bugging out and causing these lines?
the referecing in ScriptableObjects should happen the same way as in normal scripts, I suppose
Did you drag in the right WeaponTracker into the inspector and was the weapon tracker and this script enabled at the start?
Your weapon is still empty when it is sending the dictionary request, so either one of the assignments is off, or the scripts aren't being enabled at the right time
Can someone tel me how to fix this i cant find a video or any online documents that show it
please, !code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yea its all on
But you are literally going through 'foreach' and setting them to false.
usually i would write enemyAi = GameObject.FindGameObjectWithTag("EnemyAI"); but then it gives me an error saying "Cannot implicitly convert type 'UnityEngine.GameObject' to 'EnemyAi"
ik but i don't know what to change it to
What do you expect it to do?
yes, of course it cannot
enemyAi's type isn't GameObject, it's EnemyAi
the problem isn't in ScriptableObjects
i want it to only set the object im pressing E on to be false not the whole array
ohhh right
How do you know which doorbell is selected? Do you click on it?
Right now it's just a script just whenever you press E it disables them all
true, do you know any other way i could try and reference my enemyai script?
yeh so when the cameras box collider is in the object it puts them all to false
does anyone know where i could get help with fixing my camera
I'd start by writing down exactly what you expect to happen.
I.e. click on X
X is highlighted
Press E to disable etc
And then break it down from there.
Right now I have no real idea how your project is structured or how you want it to work, so I can't really advise. If this is one script, or many scripts, attached to the doorknob, or all doorknobs. Why is there an array? Etc
Yes, you can use other Find method. You cannot reference a GameObject from your scene though.
#🎥┃cinemachine if it's about cinemachine, #💻┃code-beginner if it's about code, otherwise #💻┃unity-talk
the players camera have a box collider on it which is set to is trigger when that collider goes onto the object it shows an [E] on the UI when the player presses E the whole array is put to false i only want the object im looking at to be set to false and leave the others true
im not sure what the issue is cause its just using the normal camera but it seams to be a visual issue
and they issue persists across diffrent cameras engines
Is this script on every doorknob or is it one script shared by them all? I'm not sure why the array is being used here
what iz the z value of your camera?
thank you! this worked :)
5 i think
If it's a shared script, you need to tell it what was clicked on. If it's a singular script on each doorknob, an array isn't needed and it could just directly disable whatever itself. But then pressing E is running on all copies of the script anyway, so you keep a bool to tell which one is active
What kind of guess is that? They haven't even told their issue yet.
the script is on the player, i thought an array would be an easier way of managing things then having each doorbell having its own script
and you say that those lines aren't the part of your background or whatever?
please, show us your scene
Guyssssss, does anyone know what the code is like for the typical fps movement? Is it that I deleted it by mistake and I don't remember what it was like?
Okay, so what you can do, is on Trigger Enter - keep a reference to whatever the other.gameObject is that you touched.
Now I'm not sure how that gameObject correlates to the doorbell array, but then you need to figure out how to get the right array element based on which collider you overlapped
Ideally you'll probably want something more generic and reusable, so it checks not just doorbells but all intractable objects within reach
I don't think it's camera issues, probably tilemap's
how could tilemap cause issues tho and its only upon chaning the camera postion
like when camera is static they dont apear
or anyone could give me code? 😭
I am sorry, I cannot help you here, because I haven't used tilemap before
oh ok thanks for trying anyway do you know anyone who might be able to help me?
https://gdl.space/opuyiwarib.cpp
Anyone has a suggestion on how i should return the rocket into the rpg
Yes, someone who knows about tilemaps more than me
Also don't they have a clearer code on how to grab Half Life 2 style objects? 😫
No, nobody's gonna do this. Please, ask a specific question and don't expect others to do everything for you
Turn the rocket into the rpg? What does it mean?
Do you want to switch the weapons?
you should Instantiate your rocket gameobject to make a new one when you fire it
could anyone help?
Return not turn, like reload or smth
I was actually joking, I don't want them to do everything for me because if not where's the fun?
the fps movement
I don't think you weren't. You clearly said: "Write some code for me"
make all your weapons the children of a GameObject, deactive the previous and activate the new weapon when switching them
What are you talking about, i just need to reload an rpg
I see, I haven't understood it correctly, I thought rocket and rps are different weapons. Do like SteveSmith told you earlier
Well, your code says don't update the viewmodel if childCount is greater than 0.
I tried that, but when i after i insantiate it, it doesnt become a child correctly, the rigid body doesnt want to get disabled, and it always spawns in the wrong position
yea im seeking better ways of doing this
because you don't set it as a child
This code doesnt even include the instatiation
you should either use Transform.SetParent(Transform parent) or the the last Instantiate() parameter
cuz that went horribly wrong
it should though
a better way would probably to not destroy the viewer each time, and instead change the sprite or model or whatever and disable it when no item is selected. If you don't want to do that you pull the stuff inside your if statement outside and Destroy the viewer inside the if statement
Yeah ill try it again now ig
see Instantiate method's Transform parent parameter
Ok i figured out how to instantiate it as a child, but i cant figure out how to disable its rigidbody
Let's imagine you do really need this.
yourGameObject.GetComponent<Rigidbody>().enabled = false;
Does anyone know the max float size of a Keyframe tangent?
Rigidbody does not have an enabled property
Made it work ty <3
SpawnedRocket.GetComponent<Rigidbody>().isKinematic = true; btw
!code @unreal imp
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh i forget it,sorry
Guys I have a problem and it is that when I want to apply my jump code the player not only can't jump but he can't walk, any solution? Here the link: https://gdl.space/otiwaxehey.cs
yes, I forgot that it's not a behaviour
Can you forgive me?
you too?
no
This may be a dumb question, but can i add a script to the prefab, which will be spawned later (Rocket)
yes, of course
yes
Ok ty
Kinda the whole point of prefabs
looks to me that you should be debugging verticalVelocity and seeing what you set it to
tbh, when I see scripts posted and there is not a single Debug.Log in them it makes me think 'this person has done nothing to solve the problem themselves'
I always forget that I can do Debug.log
you forget too much and too often
I think you gave me an idea 😉
Heavy weapons guy tf2?!?!
does anyone know why this code allows players to clip though walls slightly ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed;
public Vector2 forceToApply;
public Vector2 PlayerInput;
public float forceDamping;
void Update()
{
PlayerInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
}
void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
Vector2 moveForce = PlayerInput * moveSpeed;
moveForce += forceToApply;
forceToApply /= forceDamping;
if (Mathf.Abs(forceToApply.x) <= 0.01f && Mathf.Abs(forceToApply.y) <= 0.01f)
{
forceToApply = Vector2.zero;
}
rb.velocity = moveForce;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Wall"))
{
// Reverse the player's velocity to prevent passing through the wall
rb.velocity = -rb.velocity;
}
// if (collision.collider.CompareTag("Bullet"))
// {
// forceToApply += new Vector2(-20, 0);
// Destroy(collision.gameObject);
// }
}
}
yeah its meeee
another one !code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Another dumb question like before, is it possible to reference a already existing game object in a prefab
no
Nope
only another prefab
Shit
Maybe set up a game manager that has the refrance to that object
Then get it in the Start method on your prefab
So basically when the prefab is created it asks for the game manager for the refrence
Ill try it ty
So I am importing 2dgamekit into my project and I need to know what each of these settings do so I know whether or not to let them override my project settings.
When i don't give them override permission, the textures of moving background objects and perticle effects get reduced to pink polygons. when i give them full access, i lose access to the layer dropdown in my inspector. do you guys have a brief overview of what each asset does so I can figure out if i want to import it? even like a link to the documentation or something?
hey so im still struggaling with this how do i have my enemy ai move only on the x axis because i have them able to jump and i want them to be able to move when they jump but right now if the player is above them they start flying to the player i dont want that but they still should be able to jump so i cant just lock the y axis
here is my enemyai script https://pastebin.com/QvYibAfP
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Why do you reverse the players rb, shouldn't the colliders on them prevent them from clipping?
Ok i googled some stuff about this, is game manager just a empty game object with a script on it?
Yes
But if the rocket cant reference the rpg, why would it be able to reference game manager
take the player position and set it's y value to the same as the enemy before you use it anywhere. Therefore the code thinks the player is on the same y axis.
Its a thing called singletons, look it up online.
Also why would your rocket projectile need a refrance to the rpg anyway
Cuz it spawns semi clipped into rpg and it instantly explodes
So i want to disable the colision betwen them
Well i dont see why that would need a refrance
You can just use physics layers for that
Use physics collision layers
Put your rpg on one layer, like "player", put the rocket on another layer like "projectile". Then disable the collision between them in project settings>physics
no the problem is when the player jumps the enemy will start to fly to you
well right now they dont but they cant jump
Is there code for 2D to determine if a sprite is in game view
What do you wish to do with the information? You could use OnBecameVisible for example, depending on the situation
When you spawn the rocket you would pass the rpg as a parameter in a function:
public class Rocket
{
private RPG rpg;
public void Setup(RPG rpg)
{ this.rpg = rpg; }
}
------
void SpawnRocket()
{
Rocket rocket = Instantiate(rocketPrefab);
rocket.Setup(this);
}```
https://i.imgur.com/2fbZbdq.gif https://pastebin.com/zWPUir9c thats a example of them just flying with the code
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I will be Destroy(); the gameobject after it leaves the view
sorry to you and everyone about my behavior is that I forgot how things were here 😦
ill try onbecomeinvisible ty 🙂
i want them to move towards them on the ground but be able to jump and when they jump they should be able to move in the air not just jump straight up and down
it calculates the direction by using the players position. So when you ignore the players y position by setting it equal to the enemy's y position it will calculate the target position as if the enemy is on the ground.
so how exactly do i do that im really new to this
Kiss me in my hot mouth,I'm feeling romantical (ok now I stop joking)
oh you are actually doing that already.
oh wait, you commented that line out
which line is that?
in the code you posted, you need to remove line 38 and uncomment the next 4 lines, then it should work
yeah with that the enemy cant jump
it will play the jump animation but if they are moving they dont jump
ye, but thats the problem of your Move() and Jump() functions
it is?
should i just apply the movement as a vectory to the rigidid body?
what is happening ```cs
[SerializeField] private GameObject[] items;
private void Start()
{
foreach (GameObject item in items)
{
GameObject newItem = Instantiate(item, itemHolder);
newItem.SetActive(false);
}
}
I think so. I think the problem is that your enemy isn't grounded and thats why he doesn't jump? Try adding a Debug.Log("Jump"); inside your jump method
also samething happens with this code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed;
public Vector2 PlayerInput;
void Update()
{
PlayerInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
}
void FixedUpdate()
{
Vector2 moveForce = PlayerInput * moveSpeed;
rb.velocity = moveForce;
}
}
``` and its like super simple so idk how the wall pushes back
could it have anything todo with the type of collider i am using?
All the basic physics stuff should be handled by the colliders itself. Maybe a video of your problem would help
that code looks fine
its not very noticeable but i can send video if u want
it just triggers me cause i cant un see it now
i get the log but still doesnt move up
that is strange, comment out the lin in your Move() method, rb.MovePosition(..) and see if it can jump then
yep they jump now
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class startGameEasy : MonoBehaviour
{
public string LevelName;
public void LoadLevel()
{
SceneManager.LoadScene(LevelName);
}
}```
anybody know why the only option im getting is monoscript here?
then rb.MovePosition() is overwriting the jump. You could try this:
rb.MovePosition(rb.position + movement + rb.velocity);
ye that shouldn't be happening, I would also recommend changing your collider to multiple box colliders
now they just instantly fell through the map
did you drag/drop the script or the gameobject containing the script?
does anyone have a good starter game idea for well beginners?
yeah
still happens with box collider
there was a question there
pc game btw
i dragged the script onto a button
Then you need to move the player by another way:
Vector2 movement = direction * moveSpeed;
movement.y = rb.velocity.y;
rb.velocity = movement;
need to drag a gameobject containing the script
oh ok ty
should i just re do my movement or smt
yeah that worked thx
select the player in the inspector, when you walk against a wall does he come to a standstill or 'bounce' off in the other direction?
why doesn't unity have a copy paste system? like I can't copy paste scenes or assets without going back into the file explorer
duh? Select + Edit->Duplicate
works now thanks
you mean from one project to another?
oh so they use ctrl d instead of c and v
bounce
mildly annoying but much better than what i was doing tysm
thank you
top down shooter maybe?
ooo ty
mhh that is strange, do you need physics for your player other then colliding with walls?
i use triggers for collisions but other then that no
you could remove the rb from the player and just move him with
transform.position += (Vector3)PlayerInput * moveSpeed;
I don't seem to understand what's the issue
nah it's fine.
ok ill try it
maybe log the name of each item that is getting Instantiated
Perhaps the objects are destroying themselves with some script
yeah it was ondisable method
foreach (Transform item in itemHolder)
{
ResourceItem resourceItem = item.GetComponent<ResourceItem>();
IEquippable tool = item.GetComponent<IEquippable>();
if (selectedItem != null && selectedItem.id == resourceItem.item.id)
{
item.gameObject.SetActive(true);
tool.Equip(itemHolder);
}
else
{
item.gameObject.SetActive(false);
tool.Unequip();
}
}
```does this seem good enough
do you know how to paste between projects?
Assets -> Export Project, or manually by using File explorer
ffs !code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
check what is in the inspector
do you ever call getDamageValue()?
screenshot inspector
yes
i see my console outputting damageValue and enemy health, but not "pistol"
even though it should
you sure it has no trailing spaces?
well, you learn a lot of valueable things here, one of which is that string comparisons are error prone.
well i tried with a dictionary, that went even worse
yes, try changing it to an enum, much better
I would use ScriptableObjects for weapons.
rn all i want is for this to work
public enum WeaponType {
pistol, rifle
}
how do i make the easy mode method not be overrid by the defonition at the start
write: Debug.Log(currentWeapon + " - " + "pistol" + " - " + (currentWeapon == "pistol");
and paste the result here
definitions will be applied before any methods can be called. That shouldn't happen.
when i run it im getting it as 1 so ill check the method
looks like currentWeapon is null. Do you maybe have two of the scripts in your scene?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class startGameEasy : MonoBehaviour
{
public EnemySpawner EnemySpawnerReference;
public string LevelName;
public void LoadLevel()
{
SceneManager.LoadScene(LevelName);
EnemySpawnerReference.EasyMode();
}
}``` this should be calling the method when loading the scene right
sure, if you call this function when you load the scene
no.. i dont think so
it will be called
i have multiple damage scripts at the same time though
then i dont know why the value isnt changing to 1.5
because you are not calling the function
since im instantiating my enemies
well, the EnemySpawner script isn't the same as in the scene you load
again, show me where do you call this function
he posted it above
that's not function call
thats function definition
but where do you call it
it has 0 references
what do you mean by that
you made a function, but you are not using it anywhere
A function is like a list of commands. You've written the function, but you are not asking it to do the commands it has
here?
that is not that function
I don't know what a "loader" is? If you want to change a value from one scene to another you can use static variables:
public static spawnRate;
Then you can change it from any script without needing a reference:
EnemySpawner.spawnRate = 1.5f;
that is not a good approach
oh thanks thats helpful
oh
What about a game manager?
use a singleton, or store the spawnRate data in scriptable objects for example
that's a fine approach for something like that
sure but what if you want to add more levels in the future
i dont
ok xd
its not that type of game
make a DifficultyManager (singleton), set the difficulty whenever you want (store it as enum for example EASY, HARD) then in the spawner in Start() set the spawnRate based on the difficulty from the manager
Just use a singleton. Plus, you will probably need a game manager singleton script later down the road for other things
whats a singleton?
i just see that it means it only creates one instance of itself
Yes exactly, there is one instance only meaning it is easily accessible through static fields
Singletons stink, just make the spawnRate static
why do you say that? 😄
i've worked on many AA projects
in every we've used a singleton
Singletons are just static variables with extra steps
Bruv didnt even know what a singleton was a second ago and is now saying singletons stink
ok, ive figured something out, the currentWeapon becomes null every click
i dont know why
i never set the currentWeapon value because of a click
there are a lot of advantages of singletons rather that static class
they have 2 different use cases you cant really compare them
am i dense? why does this fire 3 times instead of one? assuming the error is with my input, im using default button input mapped to left click
are you using the new input system?
yes
ah i see so should I put it on started or performed?
is the new input system worth using, or should i use the manual one ?
well, for now you just need to learn basics of C# before you start learning the API
i dont really have the time for that
im at the point where i can't type C# because I don't know the specifics of the syntax but can read and understand it bc i know python and C lmaooo
🤷
making for a miserable experience
youre wasting your time then im sorry
not knowing C# or basic programming will make making anything of any consequence impossible
still, don't throw yourself in the deep waters
learn C# basics
then learn Unity API in depth
are you coming from roblox
no
hmm whyd you learn lua?
DotA, maybe
Gmod
Garrysmod? Teardown? GtaSa?
just wanted to, i liked it more than python
best answer
lol scripts
well u wasted ur time then xD
Uses of lua(out side of modding games):
.
complete list fr
world of warcraft addons
well it still teaches you principles
python on top
i learned python before lua
lua syntax is wack af too
enough off topic guys
Enforcing one instance and then accessing variables on that instance vs having static variables are very different.
When you accidentally have 2 instances of the class and arent notified, you now have random bugs to debug
What's an example of a time you would not set a box collider to a trigger but still use a collider?
A wall
How about a wall in pong? Same deal?
anything solid
Yes? If you want it to be solid
if you set to trigger, the ball will just dont collide with the collider
He just wanted to set the difficulty from the main menu. Having two spawners wouldn't cause any bugs, they would just read the same value.
@rare basin Huh? I thought it would still collide
if you set to isTrigger it wont
triggers aren't solid
you only get OnTriggerEnter/Exit etc. callbacks
trigger means, report but dont stop
Ahh
That makes sense
So report something back to me if you get hit
So if we use the Pong example then the wall without a trigger would just collide but not report back
https://unity.huh.how/physics-messages/trigger-matrix-3d
https://unity.huh.how/physics-messages/trigger-matrix-2d
here is graph to what can hit what
no, a collider which is not a trigger will report and stop
So in the case of pong I would want the player and ball to be triggers but not the walls, right?
- a rigidbody
no
alright i found out where my currentWeapon gets deleted, idk what to do with that info tbh
the only thing that would be a trigger in pong would be the Goal scoring area
Ahh gotcha
also cus that part of the code doesnt interact with it
That wuld cause issues if the ball hits the top of the player.
Maybe the player should be a trigger and change the velocity of the ball?
Via script
You can do that anyway, dont see how it would create issue
i usually use Vector3.Reflect for pong clones
How many times have you remade pong? 😲
Player moves up, the top of the player hits the bottom of the circle collider, ball moves up
at least 7 😅
sometimes I do it for jams
with different mechanics to add variation
Yes and even worse, there is literally only a handful of people whos advice is actually useful instead of complete nonsense
i found the issue it was because my camera was following the player in the z axis aswell :/
Any way a changing the y value of child within a horizontal layout group by script?
How do i make a button run a method?
there should be a on clicked methord
link to the OnClick
Inspector or code, either one
what do i put under here tho
oh
Did u replyed to me?
huh?
When u sayd inspector or code i thought You were talkin to me,my baad
oh wait how do i choose what scene is opened first
What's the advantage of using Visual Studio of VS Code for scripting in Unity?
It's sooo slow to load up
Build Settings
ty
Its just more polished, better Intellicode, very few bugs
Oh gotcha
proper and easier debugging of your code when you screw up
Debugger alone is worth 100%
although vscode is slowly catching up. maybe in 2 years its caught up
I've heard some controversial statements about debuggers, like they don't work in larger projects sometimes
The vscode extension isnt also in a stable release iirc.
Lots of people have asked in here why their vscode suddenly stopped working, while for VS I've rarely seen it asked
As for the load time, if your computer is really old then I can see this being an issue... but it's a one time issue. You arent opening and closing it multiple times per coding session
I've got a new machine, it's just compared VS code is what I meant
I mean yea a text editor is always gonna startup faster than an IDE 😆
InputAction.CallbackContext
is this what i would want as my "context" parameter in the function? I'm a bit confused on this part lmao
Do any of you use a "library" of scripts? Like you keep old scripts for reference in later projects.
Lots of them
What's your best tip/tool for organizing them? Gist?
I also make custom Class Library in VS so I can use the same thing through different UIs (including unity)
Gotcha
Me too
InputAction.CallbackContext is a type, you should check out the New Input System Startup Guide. Basically it will look like this when you link the unity event from the PlayerInput to your script:
public void SomeMethod(InputAction.CallbackContext context)
{
if(!context.performed)
{
return;
}
//Rest of your code
}```
figured it out, thank you!
For some reason my paddle is moving both left and right players... any thought?
public class Paddle : MonoBehaviour
{
public bool isPlayer1;
public float speed;
public Rigidbody2D rb;
private float movement;
// Update is called once per frame
void Update()
{
if (isPlayer1)
{
movement = Input.GetAxisRaw("Vertical");
}
else
{
movement = Input.GetAxisRaw("Vertical2");
}
rb.velocity = new Vector2(rb.velocity.x, movement * speed);
}
}
Player2 moves individually when I just press up and down but when I just move Player1 with the W and S keys it moves both players
I found it
sounds like your Vertical2 axis also uses W and S
Yeah
Funny how typing out the problem exactly you can sometimes findd the answer yourself hahahaha
started* not performed
Git and UPM
How come my headers aren't displaying in my GameManager?
Oh whoops I have errors
So my ball is just dropping here upon play... any thoughts on where I went wrong?
Physics material seems set correctly
Gravity scale is set to 0
The rigidbody's X position is frozen
Right... any idea what's causing the freeze?
The tick you've applied to it
!vscode
because its bounciness is 0
I believe the paddle's Rigidbody must be set to kinematic?
For the paddles you do need to freeze the rotation and X position
Yes that too 😄
That did the trick thank you @keen dew
You may want kinematic instead of freeze position. Freezing the position can kinda mess with the collision, at least I've had issues with it. Objects think they can go further than they should into a frozen object
I'm quite sure a kinematic body is more appropriate in this case: https://docs.unity3d.com/2022.2/Documentation/Manual/Rigidbody2D-Kinematic.html
Because you are not wanting the paddle to be effected by external forces
@eternal needle with kinematic the paddles then go through the upper and lower walls
Do those walls have static rigid bodies?
Yes, add static rigid bodies and the paddles should not go through. Fingers crossed
When you get a chance, take a moment to review that doc I linked to. I believe you will want to check "Use Full Kinematic Contact" https://docs.unity3d.com/2022.2/Documentation/Manual/Rigidbody2D-Kinematic.html
The docs say "Enabling Full Kinematic Contacts enables a Kinematic Rigidbody 2D to collide with all Rigidbody 2D Body Types. This is similar to the behavior of a Dynamic Rigidbody 2D, except the Kinematic Rigidbody 2D is not moved by the physics system when contacting another Rigidbody 2D. Instead, it behaves like an immovable object with infinite mass."
Let's see... how you are moving the paddles in your script? Are you adding/removing velocity? Or directly translating the position? Were the paddles being prevented from going outside the walls when its body was dynamic?
rb.velocity = new Vector2(rb.velocity.x, movement * speed);
Yes, velocity
I'm gonna stick with Dynamic for now
Okay... at the very least freeze the Z rotation
I have an odd error when i collect coins guys. not sure how to fix it. when i collect coin number 1, it sounds correctly. I have a different empty object with an audio source for coin 2, but when you grab coin 2 it sounds both the sound of coin 1 and coin 2.
How would you be able to deal with the list being modified while this loop is running?
{
while (Receivers.Count > 0 )
{
yield return new WaitForSeconds(_attackInterval);
var receiver = transform.GetClosestReceiver(Receivers.ToArray());
_actionHandler.Shoot(_shotOrigin.position, receiver.GetTransform().position - _shotOrigin.position);
}
}```
Its erroring out when receivers turn to 0
i tried adding a null check on Receiver[0] as well still same issue
nvm i fixed it. i was sharing the same animation for both so the position would break
nvm i cant fix shit
When i click to change the animation, it does. but when i play the game it goes back to the animation i dont want em to do. Not sure what im doing wrong
If both "Nota"s have the same animation controller, they will surely play the same animation.
Now i fixed it. I ended up giving the animation to the empty parent instead of "Nota"
So they all play the same up and down, rotation animation.
is there any way to change my materials texture from urp to built-in
https://pastebin.com/gGBqUr5t could anyone help? whenever a tool breaks, entire system just falls apart and it becomes very buggy
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
https://gdl.space/femebotexe.cpp
the game objects are not rotating and appear to be lightly vibrating as well - how can I fix this?
Likely because you are using a rigidbody
And rotating it with transform
What should I do instead?
Show the inspector of your rigidbody?
Constraints too
none
What's causing this Object reference not set to an instance of an object error?
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Ball"))
{
if (!isPlayer1Goal)
{
Debug.Log("Player 2 Scored...");
GameObject.Find("GameManager").GetComponent<GameManager>().Player2Scored();
}
else
{
Debug.Log("Player 1 Scored...");
GameObject.Find("GameManager").GetComponent<GameManager>().Player1Scored();
}
}
}
Did I incorrectly tag something?
if tag look for player 1 or player 2 goal, if goal set game manager component to 1 or 2 score
What's the better method?
Typically the game manager is a singleton so that you can refer to it directly
or in simple cases, make a serialized field and drag the object there like with everything else
Out of curiosity what's wrong with .Find?
Well for one, you can very easily typo the name as you found out
lol
it's slow, unreliable and you've now committed to never changing the object's name
Alright let me see what I can do
I'm trying to add actions to my condition script but they aren't given as options
drag and drop won't work either
You need an actual reference/instance of an action, not the script . . .
Is Action an SO or MonoBehaviour?
idk what an so is, the action script is built in the playground urp package
You are searching scene objects only
Or am I looking at it the wrong way
both of them give nothing
The bottom warning in your console seems very much related to this issue
Okay, I have no experience with the Playground URP package, so I'm unsure of its project structure . . .
i'm testing moving unitytech to directly sub assets folder
Looks like it tries to find UnityTechnologies in the assets folder, so yeah make sure it's there
always the stupidly obvious solutions that i can't seem to figure out that just happen to work
thanks
Checking the console helps 😉
Yeah, it's inside of the "Imported" folder . . .
yes, making text appear on the screen is incredibly hard which is why nobody has ever done it before
You can just use a scroll view with text. It's up to you which method to use . . .
it's hard to understand half of the console errors an they usually bring me to the scripts that i know nada about
Looks like someone woke up a little bit angwy
i have 2 problems. 1 is making the gun not point to the the mouse while moving, prolly camera. the other one is that when i go in bewtween gun and the player it will go the opposite way. these two combined make this game practically unplayable.
wait
got more images
click on the image and press left or right
idk what went wrong
I understand, just wondering why the thumbnails don't show
dunno. doesnt matter currently.
Alright! Got it going thank you all for the debugging help :)
I'm unfamiliar with cinemachine, but try changing that Update to LateUpdate in case it's an execution order issue @red prairie
Or make sure that your code runs after cinemachine in the execution order settings
its even worse. idk
direction is (endPosition - startPosition). so when your mouse is to the left of the object this script is attached to, then the direction will be to the left.
which problem?
when i go in bewtween gun and the player it will go the opposite way
still dont know ur logic on that
Yep, better use the character's position in the direction calculation instead of the gun's position
r u reffering to this line of code?
that works.
just spawns from the player which is kinda wierd.
what about the other problem. i tried setting one to eairly update. and cinamchine to late
Huh? Then you changed something else too
Anyone know what is causing the following error?
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
what?
yes i used the players transform
Unity editor bug, you can clear the console and ignore it. If editor errors keep popping up, you can try resetting the layout and/or restarting editor
Oh alright, thank you
Don't use the player's transform as the bullet's spawn point. Just for the direction
yes but how do i use the players transform for the bullet?
they r the exact same for both transforms
Use a reference like in your latest screenshot
Or do the logic on the player object and reference the gun
Maybe it's best if you show what you just changed
that still doesnt solve the issue of it not pointing to the mouse
all i changed was the position of the transform
Show your current PointTo script
I just told you to use the player's transform instead of the PointTo object's transform here
Isn't the PointTo object on the child object?
yes.
And change this back to whatever it was
@red prairie Vector2 direction = mousePosition - playerTransform.position
so instead of transform.position. i use gameobject.position?
Just make a reference to the player transform in your PointTo script and do this ^
kk
Not sure how it wasn't clear from this question tbh.
mb.
so, i have a player object, it has a sliding() coroutine, in which it deactivates the main hitbox and activates the lower body object, which has its own, adjusted hitbox. I tried using a normal sliding() function, but making a timer for it doesn't work, as it will run entirely in the frame it was called. Is it a good idea to make a separate script for the lower body?
There is a lot to unpack. Probably best to just show your !code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public IEnumerator escorregar()
{
//setting everything for the slide
escorregando = true;
hitbox.enabled = false;
corpobaixo.SetActive(true);
animador.SetBool("Escorregar", true);
//duration of the slide
yield return new WaitForSeconds(2);
//deactivating the animation, starting a transition in the animator window
animador.SetBool("Escorregar", false);
//duration the transition should be
yield return new WaitForSeconds(0.5f);
corpobaixo.SetActive(false);
escorregando = false;
nada();
}
the variables may be a little weird bc they aren't in english
nada() is a function that sets everything back to normal
Hmm, and this all runs immediately?
Are you perhaps accidentally calling escorregar more than once at a time?
no, what runs immediatly is if i make it a function, the problem with this one is that there is a period of time after everything ends that the player doesn't do anything, like it doesn't accept any input
Also make sure to start the coroutine with StartCoroutine(escorregar())
Instead of escorregar()
i'm calling it correctly
Ok, yeah you can't do waitforseconds outsixe a coroutine
The timer would have to work completely differently and it would need to be multiple functions
i absolutely hate writing code in native language
why not just english, especially when you are sharing this code in public discord
i didn't plan to share it here, i'm together with another guy writing this, making the variables in native language helps me, and the other guy understand it better
You write it in whatever language makes sense for you. It's wild for anyone to suggest anything else
I've helped people who write in many languages. It doesn't really make it much more difficult to help with
Chinese and other languages like that have been tough though, haha
i know it's hard for other people to understand the code without the whole context, so don't stress over it, i'll try a bunch of possible solutions here and report back if any of them worked
I dont think its an issue of not understanding the code (ideally use a code site and paste more context so we can see what type each thing is), but that what you're describing doesnt make a whole lot of sense. if you called the coroutine properly, it shouldnt be running all in the same frame. I think maybe you have more code which is causing issues instead, you should add Debug.Log in your coroutine to see all of this doesnt happen right away
how is that weird?
I said wild.
english is the most common to write in code, if he ever wants to find a job he will need to adapt, i doubt there is a single company (serious company) in the world writing code in native language
Not in my experience at all 🤷♂️
But yeah, many want english. But they are making a game with their friend, so that is completely irrelevant
Guys, does anyone know why my bullets don't have the same rotation as the gun or the muzzle? var bullet1 = Instantiate(bullet, muzzle.transform.position, Quaternion.identity); bullet1.GetComponent<Rigidbody>().velocity = (targetPoint - muzzle.transform.position).normalized * shootForce;
pass the rotation of the object you want it to have the same rotation as instead of Quaternion.identity which is no rotation
How would i go by checking whether the player is using controller or keyboard. Would i have to add every controller and keyboard binding to their own scheme in the input system?
I believe there's a static class/method/bool that's just like Keyboard and if not true then it's a controller. I swear I've seen it in Unity's controller package.
Okay, i'll try searching for that.
I recall it was in one of their example scenes like when you create a new project and they come with a controller. There was a ternary line in there that checked if it was a keyboard or not. Might have been Keyboard.current
Maybe something like: if(keyboard.current == null)?
yup
Okay i'll try that
Looks like it's Keyboard.current and Gamepad.current
Could probably create some Action with that for when switching between controller/keyboard too.
I think, if the keyboard and gamepad is connected at all, then both bools will be true, i want to check what input device is sending input currently. @quasi rose
But I think current would work if you got creative with the bools and events, idk. You could track which one last had input and then update your UI or whatever you need based on an event.
how do i assign player to this in code
would i do smth like this ```csharp
target = GameObject.FindGameObjectWithTag("Player").transform;
always good to try it and see 🙂
i am
hey guys
it works
Im new with unity and I need some help
i wouldnt do it like this, it is relying on the tag of the object. Dragging it in inspector is fine but i assume you cant for a reason (like player is spawning through code). in that case, instantiate returns the object and you can pass that to anything who needs it.
Im tryna make a game for our class project and I cant seem to activate my key
im stuck here
this is a coding channel#💻┃unity-talk
okay sorry, Im new here bro
well there will only be 1 object with the tag player so i dont think it would really effect it
then use singleton instead, enforce the "only one" logic with a pattern. This method you're using is slow and can be incredibly weird to debug. Like if you accidentally tag an empty object as "Player" in a scene with 100s of objects, you'll suddenly have a very confusing issue
so could you explain how to have it set to it
not sure how to do either of the things you are talking about
Why does this work when i'm navigating through my scene, but if i pause my game, it flickers back and forth between the two bools? https://hastebin.com/share/samiqujixi.rust
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
nothing here shows you're pausing the game
I know, this is the only code in my game that sets the bools.
Everything else, checks those bools.
Yes but I don't know where these methods statements are located in. Methods? Update? Events?
It all depends on how the player exists in the first place. If it's just in the scene already then dragging it in is fine. If something is spawning it, you get the object returned from instantiate and plug that into any object that wants the player. Or you use the singleton pattern (google it for unity) and access it via a static field
so the enemy is spawned in
I think i found the culprit, In the Gamecontrols.GamePlay.Mouse.WasPressedThisFrame() it checks for input from a mouse, but i have a virtual mouse in my game, which i think is triggering it. WHich is why its flickering. How can i fix this?
Still haven't answered the question
Are you checking through update or through events
Update
If you're pausing the game, your timescale should prevent these types of updates, no?
I mean, there's a few ways about pausing. One is using timescale, and the other is separating game logical updates from input.
Actually, I don't think the event system does pause. You may be correct if you're using timescale
In that case you may want to add a boolean in your update (if paused then skip this input)
I ended up fixing it by using Input.getAxis instead of the new inputsystem, that detects even virtual mice. Also Time.deltaTime isnt affecting my code.
anyone know how i can check if there are no objects with a tag (trying to check if there are no enemys left before new wave)
I'm just not a fan of using timescale, but if you're using rigidbodies I'd assume you are required to use it.
otherwise just manually disabling updates on the game logic is my solution
Thank you
the proper way to do it is using a list instead of scanning through all objects each time.
only on removal of enemy from list is check how many left in list
cant a list not be emtpy though
bro im so mad rn i just lost so much progress cause unity crashed
a list can certainly be empty
what kind of crash? file a bug report
it just starts not responding i dont get a error message
so is it after you hit play?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab; // Reference to your enemy prefab
public Transform[] spawnPoints; // Array of spawn points
public float numberofenemies;
public int numberOfEnemiesInWave = 5;
public float timeBetweenEnemies = 1.0f;
public float timeBetweenWaves = 5.0f;
private void Start()
{
// Start spawning waves
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()
{
while (true) // Infinite loop for continuous spawning
{
if (numberofenemies == 0f)
{
yield return new WaitForSeconds(timeBetweenWaves); // Wait between waves
for (int i = 0; i < numberOfEnemiesInWave; i++)
{
SpawnEnemy();
yield return new WaitForSeconds(timeBetweenEnemies); // Wait between enemies in the wave
}
}
}
}
void SpawnEnemy()
{
// Randomly choose a spawn point
Transform spawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
// Instantiate the enemy at the chosen spawn point
Instantiate(enemyPrefab, spawnPoint.position, spawnPoint.rotation);
numberofenemies++;
}
}
thats the code i changed i believe
i dont think i changed anything else
the while loop is missing a yield return null;
also this is a bad way to do this anyway
again you should just keep track wit a list
Instantiate returns the enemy spawned
where do i put that?
in the while loop?
anywhere or at the end or smth
inside the while loop
works now thanks
It means x is 0 or negative
Thanks
also any idea why this barely launches the enemy but when they are above me it launches them super high
void LaunchTargets()
{
// Find all objects with the specified tags within the specified radius
foreach (string tag in targetTags)
{
Collider2D[] targets = Physics2D.OverlapCircleAll(transform.position, affectRadius, LayerMask.GetMask(tag));
// Launch each target that is not the current object
foreach (Collider2D target in targets)
{
if (target.gameObject != gameObject)
{
Rigidbody2D targetRb = target.GetComponent<Rigidbody2D>();
if (targetRb != null)
{
// Calculate the direction from the launcher to the target
Vector2 launchDirection = target.transform.position - transform.position;
// Apply force to launch the target
targetRb.AddForce(launchDirection.normalized * launchForce, ForceMode2D.Impulse);
}
}
}
}
}
i have tried setting launch fordce higher doesnt fix much
Hi friends!
I'm using this line in attempt to basically find the net angle of input if that makes any sense:
Mathf.Atan2((Input.GetAxis("Vertical"),Input.GetAxis("Horizontal"))) * Mathf.Rad2Deg
But unity disallows me stating:
" CS7036 There is no argument given that corresponds to the required formal parameter 'x' of 'Mathf.Atan2(float, float)" "
Does anyone know how to make it accept my values?
You have an extra set of ()
So it thinks you are giving it just one variable, more specifically a tuple (float, float)
All that time wasted to such a silly mistake!
I never would of caught it myself, thx a lot for the help 🫶
How do I measure something in Unity? For example if I wanted to replace the paddles how would I know what size?
Like if I wanted to replace them with custom sprites I made in Aseprite, how would I know what size?
Go to the scene view and turn on the grid. Each unit grid cell is one unit, and you can decide how many pixels that should be.
If those are just squares that you scaled, you can also just check the scale
Oh I see so just judge based on the scale
