#π»βcode-beginner
1 messages Β· Page 153 of 1
what do you need to do ? a Coroutine you can yield till nextframe
gonna be honest I'm clueless about coroutines
what should i set Times Clicked to if i cant set it as 0 if its not an Int
who said anything about ints
Then you should probably learn
Hello
well i tried to set it to 0, but because its Text im unable, so what should i set it to
TimesClicked is clearly an object (assuming a Text object)
but its not assigned, therefore Null at runtime when you try to use something from it .text
private Vector3 offset = new Vector3(16, 3, -9); how can i put dots there Vector3(16, 3, -9) without error (exmpl 16.5, 3.23, 9,30 this is error)
If it's a Text object why are you trying to set it to 0? You want to set it to a reference of a Text object
use f
Use floats, not doubles. Floats have an f at the end
for float
how should i set TimesClicked to a reference of a Text Object
assign it through the inspector
here is an example
https://unity.huh.how/references/serializing-component-references
dont copy the code, just look at the example
thanks so much @polar acorn @rich adder
This is what its been set as
if its set there BEFORE you pressed play, more likely you have a copy of this script somewhere where its not assigned
search hirerchy for t:MouseInputProvider
more common if you saving changes to a script during playmode
if not that, one of your assets/prefab would be missing a script / broken meta
yeah thats it its just that didnt use to shoot off errors and now it does
maybe you just noticed?
its a warning btw not an error
how do i start a timeline through script
i did and that didnt come up you dont need to be sarcastic about it
orly ?
you asked a better google question on this discord and not the search itself ,wild π
acivate timeline through bool is very strange
the two aren't much related
just saying keywords matter, if you search what you wrote on DC
So when you declare a rect, it uses the 4 parameters as described in the upper image
But how do i declare one using xmin etc?
Theres an easier way then doing
Rect test
test.xMin = ...
test.yMin = ...
...
right?
I think its more like
test.min = Vector2 (xmin,ymin);
test.max = Vector2 (xmax,ymax);
But is there a way to just do it in one line like there is with the upper image
Rect test = new Rect(xmin, xmax, ymin, ymax)
because the website is stating it as if there is
public Rect(float x, float y, float width, float height);
public Rect(Vector2 position, Vector2 size);
the mins are the start
the size is the ends
min and max
the size is the distance from x to the end point
Why cant i refrence the code in SBulbUp if its a public class?
i just want to define the x and y point themselves
I think I may be confused, how does:
public Rect(float x, float y, float width, float height);
not work for that?
because if x = 1 and width = 2
the rect x coords would be 1 and 1+2
but i want to declare it using x=1 and x=3
where i input 1 and 3
public static Rect MinMaxRect(float xmin, float ymin, float xmax, float ymax);
Show the class
Can you show us the class definition?
Also, what does the error say?
but this is not SBulbUp class
So the class type isn't sbulbup
ah
Ive got coordinates of an object that I want to be a vertex for my Rect
But the transform.position of my object uses a dif coordinate system to Rect
As in, the the width of my rect is 12.5
but ingame thats really small
because im guessing declaring a rect uses pixels instead of whatever coordinate system the objects use?
How do i convert them
ohh is that was ScreenToWorldPoint does
gee wiz
Hello, is anyone familiar with Pool It? Do I manually have to add it to the pool manager for each prefab, or is there a quick way I'm missing?
Just trying to speed up my building system, my building system uses instantiation and causes big lag spikes. Maybe I am missing something.
It seems based on the profiler, it is causing a lot of lag
Wow, I figured it out. I always do when I ask for help. Its my UpdateBag function.
public void UpdateBag()
{
...
// Repopulate slots based on the bag items
foreach (Item item in items)
{
GameObject gameObject = Instantiate(inventorySlot, Vector3.zero, Quaternion.identity, contentObject.transform);
gameObject.GetComponent<Slot>().SetItemSlot(item);
gameObject.GetComponent<Slot>().SetID((int)count);
gameObject.name = item.name + " " + count;
slots.Add(gameObject);
count += 1f;
}
...
}
instantiating 152 objects is causing the lag π€¦
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swing : MonoBehaviour
{
public int Debounce;
private Quaternion OriginalRotation;
//rotate function
void rotate()
{
OriginalRotation = transform.rotation;
for(int i = 1; i < 10; i++)
{
transform.rotation.Set(0, 0, OriginalRotation.z + (1/i), 0);
Debug.Log(OriginalRotation.z);
}
new WaitForSeconds(Debounce);
transform.rotation.Set(0, 0, OriginalRotation.z, 0);
}
//set the starting rotation
void Start()
{
transform.rotation = new Quaternion(0, 0, -18, 0);
}
//rotate when clicked
void Update()
{
if (Input.GetMouseButtonDown(1) == true) {
rotate();
}
}
}
rlly new to cs, why doesnt this work? i just want it to rotate whenever the mouse is clicked
You know GetMouseButtonDown(1) is Right Click?
Just checking
Incase you're left clicking expecting something to happen
tested it with 2 and it didnt do anything either
I have a really long function that I want to reuse, which looks like this
private void HandleFaceType(int corner1, int corner2, int corner3)
{
int count = 0;
if (vertexData[corner1].isPath) count++;
if (vertexData[corner2].isPath) count++;
if (vertexData[corner3].isPath) count++;
//more logic
but the problem is, I want to somehow swap out the condition in the if statements. For example, I'd like to check vertextData[corner].isWater for example
how would that work?
then you need reflection
How comes the program doesnt think my mouse pos is inside the rect?
The mousepos vector is clearly within range of the TL and BR vertex
How do you determine if isPath ==true?
that just returns a boolean
i would do that
[System.Flags]
public enum Terrain{....}
//in your struct or class
public Terrain terrain;//set the flag
//the method
public void Function(...... ,Terrain terrainYouWantToCheck){}
private void rotate()
{
OriginalRotation = transform.rotation;
for(int i = 1; i < 10; i++)
{
transform.rotation.Set(0, 0, OriginalRotation.z + (1/i), 0);
new WaitForSeconds(0.1f);
}
transform.rotation.Set(0, 0, OriginalRotation.z, 0);
}
why does this not rotate the object
Pretty sure those are not valid Quaternions
how so? its not giving any errors
I am not familiar with rotating objects, but can you not just modify the transform.rotation itself?
Do you know what a quaternion is
is this an example of c# reflection?
the data that rotation uses
no
yeah but do you know what it is
i assumed it's like the rotation you can directly change in unity
You really really should not be modifying a Quaternion's individual values unless you have incredibly strong math skills
is that wrong
It is
but it's a quaternion
a four dimensional normalized complex number
how can i not use a quaternion
You can
but do you actually have any idea what you're doing
i am rotating the object along the z axis
That's not what that does
The X, Y, and Z values of a quaternion have nothing to do with the X, Y, and Z axes of normal euclidian space
They're just the first three values of the 4D number that expresses an orientation
so how do i not use quaternion
Try using transform.localrotation π
still a quaternion
Use Euler Angles if you want it to be in degrees in 3D space
Euler angles is also a good choice yeah ^
thx
lemme see if that works
private void rotate()
{
OriginalRotation = transform.rotation;
for(int i = 1; i < 10; i++)
{
transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z + (1/i));
Debug.Log(transform.rotation.eulerAngles);
new WaitForSeconds(0.1f);
}
transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z);
}
k so for some reason it's not waiting
and it's also not changing the rotation
You're still trying to read the Z value of a Quaternion
transform.rotation is wizard math do not use any components of it
Also your entire loop is pointless because you just instantly overwrite it
it's an animation
what about the for loop?
Your new WaitForSeconds does nothing, this isn't a coroutine
the loop happens instantly and then is overwritten before the function even ends
what'll make it wait?
Actually using a coroutine
You have to use a coroutine.
The void has to be an "Ienumerator" and then you start that function with "Startcoroutine(Ienumerator));"
Googling "Unity documentation - Waitforseconds" gives a great example
It would be a good idea to read through this
https://docs.unity3d.com/Manual/Coroutines.html

is there a way I could use the new input system to avoid a fixedupdate. (its not a big deal but helps keep things organized.
You should be storing the value in a field, then you can always get the most recent state of it in another function
you mean a class variable?
Yes
what does that have to do with my question? (ill do it)
It's the reason why you're getting the error
But no, to answer your question, there isn't. The new input system stlil requires you to cache the input and use it in update.
Hence the "there isn't"
There isnt sadly , thats why i dont use it tbh
yeah i mean i can use both systems so ill just use the default system for this
And i read a few things when i skimmed the web just now , and most of those fixes involves more places, so wouldnt really help your problem π
private void Rotate()
{
StartCoroutine(ChangeRotation());
}
IEnumerator ChangeRotation()
{
OriginalRotation = transform.rotation;
for(int i = 1; i < 10; i++)
{
transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z + (1/i));
Debug.Log(transform.rotation.eulerAngles);
yield return new WaitForSeconds(0.1f);
}
transform.rotation.eulerAngles.Set(0, 0, OriginalRotation.z);
}
This would wait, however I do not know if the code functions
2D world-space FTW
Why not just make an animation that loops, do you need to set the rotation programmatically?
i could but i'd like to get better at cs n stuff
Ah I see, was just wondering
But thats how you would use a Coroutine to actually wait. You cant call new WaitForSeconds outside of an IEnumerator
Just keep in mind that multiple coroutines can overlap , so it might not rotate that much beyond the first 1 second
I have a coroutine for reloading for example , but i fix that by having a "Isreloading" bool that just flips on/off for the coroutine
this does wait, but it doesn't actually rotate
As I said, I dont know if your code actually worked. I myself am unfamiliar with setting rotations progammatically.
good to know
Quaternions are a bit tricky to use , i could send a snipet of a rotation that works if it would help you?
Maybe something like this:
Vector3 originalRotation = this.transform.eulerAngles;
float waitTime = 1f;
for(int i = 0; i < 10; i++)
{
Vector3 rotationIncrement = new Vector3(0,i,0); //Rotate on the Y axis by one
transform.eulerAngles = rotationIncrement;
yield return new WaitForSeconds(waitTime);
}
transform.eulerAngles = originalRotation;```
@clever edge
should rotate every second then reset.
Ill throw it into a new project and test it for ya
im trying to access a variable from another script. I thought it was NameOfScript.nameOfVariable am I missing something?
yeah okay i think im just gonna use an animation
it would work but im also rotating around the cursor
Make sure its public
(2d project)
it is
Is it in a different namespace?
basically I made a table you walk up to, a menu is accessable by pressing E as long as your in the trigger. I have the menu popping up when pressing E, but i cant get the variable I set to true from the desk to the script of the player when he presses E
ill show code one sec
Ok, if the desk is allowing you to open a menu when you're in the trigger, what value are you trying to set. A value on the player?
Lets get the code first
public class DeskArea : MonoBehaviour
{
public bool inRangeOpenMenu = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
inRangeOpenMenu = true;
Debug.Log("Entered Desk Area");
}
private void OnTriggerExit2D(Collider2D collision)
{
inRangeOpenMenu = false;
Debug.Log("Left Desk Area");
}
}
void OpenRepairMenu()
{
if(Input.GetKeyDown(KeyCode.E) && repairMenu.activeSelf == false && DeskArea.inRangeOpenMenu == true)
{
repairMenu.SetActive(true);
Debug.Log("Set to true");
}
else if (Input.GetKeyDown(KeyCode.E) && repairMenu.activeSelf == true)
{
repairMenu.SetActive(false);
Debug.Log("Set to false");
}
}
the top is the script on the desk, the bottom is a method in the playercontroller script
public BoxCollider2D desk;
public GameObject repairMenu;
public GameObject workSpace;
private Rigidbody2D rb;
Vector2 move;
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private bool isFacingRight = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
desk = GetComponent<BoxCollider2D>();
i have this in start but im not too experienced to know what i did exactly lol
void OpenRepairMenu()
{
if(Input.GetKeyDown(KeyCode.E) )
{
if(!repairMenu.activeSelf && DeskArea.inRangeOpenMenu)
{
repairMenu.SetActive(true);
Debug.Log("Set to true");
}
else if(repairMenu.activeSelf)
{
repairMenu.SetActive(false);
Debug.Log("Set to false");
}
}
}```
Try this
I had a similar issue today with my debug console system, checking comparators in an Input.GetKeyDown was always causing it to return false
yea its still showing red under DeskArea.inRangeOpenMenu
its like it cant see the variable im pointing to
The original code should work. Its just not as refined as the above one
Ohh, are you putting DeskArea class instead of an object?
yea i dont really have a game object to check, just an ontrigger event to change the value
You have to pass it a component, not access it from a class. You could do this:
public BoxCollider2D desk;
public DeskArea currentDeskArea;
public GameObject repairMenu;
public GameObject workSpace;
private Rigidbody2D rb;
Vector2 move;
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private bool isFacingRight = true;```
i dont wanna use the value right away, but when i hit a key, so thats why its not just on triggerenter
and then set the currentDeskArea when the player enters the trigger.
okay ill try it
and change DeskArea to currentDeskArea like this:
void OpenRepairMenu()
{
if(Input.GetKeyDown(KeyCode.E) )
{
if(!repairMenu.activeSelf && currentDeskArea.inRangeOpenMenu)
{
repairMenu.SetActive(true);
Debug.Log("Set to true");
}
else if(repairMenu.activeSelf)
{
repairMenu.SetActive(false);
Debug.Log("Set to false");
}
}
}```
and in the Desk script do this:
ohhh okay, yea thats what i had wrong i think, i had workSpace as a public DeskArea, i think i had code wrong so i chagned it to GameObject, ima check if it worked rq
private void OnTriggerEnter2D(Collider2D collision)
{
//Add a check to make sure its the player
inRangeOpenMenu = true;
collision.gameObject.GetComponent<PlayerController>().currentDeskArea = this;
Debug.Log("Entered Desk Area");
}
private void OnTriggerExit2D(Collider2D collision)
{
inRangeOpenMenu = false;
collision.gameObject.GetComponent<PlayerController>().currentDeskArea = null;
Debug.Log("Left Desk Area");
}```
I think setting it to this would work however I am also a newbie
also if your script is not called PlayerController you have to change that in the GetComponent to the name of the class (ex. if your player controller script is named PlayerMovement, then change it to that)
woahh it worksss!
π
and im not too sure what you mean by this code ^^ i do know i did it kind of a jank way tho, im much newer than you XD
No youre good your learning I was doing the same thing 6 months ago, and I've been trying to make games since I was 12
Yea im stuck in the last half of tutorial hell, ive been really grinding to try and branch out into something i like
Yet handling it like a pro π (Quoted the wrong one lol)
You could just set the script to reference that one desk, however, if you have multiple desks the playerController wont know which one is the current desk, and if you have functionality for each desk it would cause issues. In its current state its unneeded
Thanks π
rn im making a Computer repair shop, i work at one, so i can really create a niche game with good detail, but as you can prolly tell I have a scope too large for my brain
Me too I am trying to create perlin noise terrain generation
its insanely difficult Lmao
and yea for now I will be making static levels, I only need a few desks to put laptops or desktops on, soo.. im in way over my head XD
I have a simple generator but without tilemap rules its garbage
And yeah, that's good man. You'll get there.
What I got stuck on early on, was Inventory systems. Learn about arrays and lists, it will greatly help you in the future.
how long does it usually take to learn anything past movement XD it seems like I know what game mechanic i want to implement but not what to look or search for
I always end up making movement on a character, then thinking of something else to add, by the time i go to add it its too complicated and i give up
can someone help me to get a sound to be toggle-able
ill send the code for someone to correct
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BathromSink : MonoBehaviour
{
public GameObject openText;
public AudioSource sinkSound;
private bool inReach;
void Start()
{
inReach = false;
sinkSound.enabled = false;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Reach")
{
inReach = true;
openText.SetActive(true);
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Reach")
{
inReach = false;
openText.SetActive(false);
Debug.Log("IsInReach");
}
}
void Update()
{
if (inReach && Input.GetButtonDown("Interact"))
{
sinkSound.enabled = true;
sinkSound.Play();
}
}
public void StopSink(AudioSource sinkSound)
{
if (inReach && sinkSound.enabled == true && Input.GetButtonDown("Interact"))
{
sinkSound.Stop();
sinkSound.enabled = false;
}
}
}
Giving up, made me stop working on a game that me and my friend were making for years. Made me stop working on my current project 2 years ago, and it destroys any hope of a future making games. You cant give up. If you get stuck take a break. Clear your head and then try to approach from a different angle. If you're trying to add an inventory system. Make it super simple at first. Just make a list. Make it so it only contains words
List<string> items = new List<string>();```
Make it simpler for you to understand
you can add a toggle from the UI gameObject. Then set that toggle to the audio, set the audio to the component
I frequently ask ChatGPT to explain things too, especially certain parts of a problem. Also have a plan and dedicate a certain amount of time
it is a sink you interact with
im gonna need this later on lolll
i learned some windows forms using VB so i know a lil about arrays and lists
You got it man, YouTube unity tutorials can be bad if you don't try to understand what you're writing beforehand.
theyre the worst clickbait haha, it starts as "download unity" to "im just gonna skip ahead coding a flying car rq"
im on the learn.unity site
Yeah thats a good place to understand stuff. I learned how to use Tilemap rulesets on there
ive dabbled, are you talking about making tilesets easier to paint?
Yes, making it so tiles with certain conditions, like bounds or corners, is automatic
I saw a vid on that and was super excited to try that next time i want to get into top down games. That looked so much better than wat i did. I quit making top downs bc of that
Yeah manually drawing tiles can be ridiculous. Its easier for modifying game worlds realtime if youre making a survival game like me.
you have any builds made?
Yeah, me and my friend have been making the game for the past 2 months
I'll dm you a Steam Key
oh crap its demoed π does it cost anything to list on steam?
Hey, Ive made 5 grand off a really bad game I made Lol
Farstorm on Steam
thats before taxes and before steam taking their cut but still was decent
also over the course of a year and a half
Honestly people did enjoy it somehow so it worked out π
Mostly laughed at it
haha that game is cool man, I love the nintendo look. does it not have any controls but E? XD
E: Opens Menu R: Opens Bag T: Opens Crafting, press c or click current item to set an item, pressing b allows you to build, left click builds an object, right click stops building
The menu looks nice
Thanks
Also some funny debug test items in there so if you see anything like that ignore it Lol
oh crap theres much more than i thought haha
Yeah, since there is no indicators it looks empty Lol
Save and Load system, crafting, inventory, building, chopping trees, picking up items
Oh, press Space to interact with objects
Day and night system, weather system
Theres a lot getting put into it
R rotates buildable items too
jesus lol yea you may need a good UI or tutorial for that one, theres alot in there, the tree system is dope
it acts just like my desks
Yes, but instead of using a Trigger, it uses Raycasts
does that work on a more managable scale than trigger? if i add another desk i feel like im gonna have to duplicate alot of code
oh god i suck with prefabs
I wanted to make it so objects have to be looked at by the player in order to be interacted with, and, I find it easier for tilemap grid based movement
Heres a video of the farming system
https://streamable.com/s8ceam and me showing off some glitches to my buddy
jesus that only took 2 months?
And a lot of failed attempts over 6 years Lol
i dont think ive put out a finished game yet. Ive been working on Unity for about half a year now
Make something stupidly simple a cookie clicker game and force yourself to finish it. Making games is the best way to learn
im too off an on to say half a year,but this month or so ive been on everyday
Yeah, having a project youre invested in makes it a lot easier to work on it every day
The games not done, and is going through lots of changes as we make design decisions but I'm gonna add you if you need help just send me a DM if im online I'll help you out
Gonna head off for the night good luck on your journey bro
sounds good, thanks for the help
np
how to add a source to a position constraint using codes
Always check the docs for questions like this https://docs.unity3d.com/ScriptReference/Animations.PositionConstraint.AddSource.html
why is it not autocompleting?
i have no idea how to use it
{
public Transform playerPos;
public PositionConstraint positionConstraint;
void Start()
{
positionConstraint = this.gameObject.GetComponent<PositionConstraint>();
playerPos = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
this.gameObject.transform.position = playerPos.position;
positionConstraint.AddSource();
}
}
You create a new constraintsource and pass it to that method
what goes next?
i think here is where im hanging
Well I am on my phone but the code will look something like var source = new ConstraintSource { sourceTransform = theTransformYouWant, weight = theaweightYouWant};
hey guys, it's been a while since i posted here
so i'm making a game where you shoot at machines to make them pull you in or push you out, but the intensity of the pull/push is largely inconsistent and depends on a variety of factors like how close you are to the center of the machine.
i want the machines to always launch you with the same speed. how can i go about doing this? at the moment i am using AddForce to boost the player in/away from the direction they shoot at the machine in. is there another way to reliably push the player around?
its probably inconsistent due to the current velocity of the player, rather than anything with the repulsor. See your results with a player or object who isnt moving
you also likely want that force to be an Impulse. Id also ensure that its not applying more than once
Anyone know why I can see the skybox through my tiles using pixel perfect cmaera?
changing it to impulse definitely does help
you're right about the velocity thing, i wonder if there's a way i cna make that not affect the push/pull
If you trully want thee exact same force from the push pull objects then zero the player velocity before applying the force however that may be undesirable. I for one always try to perserve player velocity
i'll see how it works out
You'd have to write the return type first
I.e. void
Change the offset of the grid on both axes to -0.001 (or maybe a bit more)
It's a common problem. My bet is that due to floating point precision sometimes it takes wrong pixels on the edge of tiles and takes a pixel that is out of bounds. There are a few workarounds to fix it. Some are listed here:
https://blog.terresquall.com/2023/03/how-to-fix-gaps-in-your-tiles-in-unitys-2d-tilemaps/
I think Sprite Atlas should work the best. If you want alternative solutions, you can configure your tiles to slightly overlap with each other (should work fine as long you don't use transparency) or you can draw extra pixels on the edges of your tiles (e.g. if your tiles are 16x16 pixels, you can draw them 18x18 pixels in the texture).
how do it? nvm got it, thanks!
oh so you mean I get the Cross direction from the wall and tell my player to go in that direction?
Hello, so im working on a Vampire survivors type game and yesterday i accidently fucked up the code and cant find where it is and now the player aint even loosing HP and the stats aint showing up in the pause menu, plus im getting all of these errors, ive tried to find where the errors are through what its telling me but i cant figure out where the errors are coming from
everything else ive done so far works, except for the HP bar for some reason
the player also takes constant damage even tho i set it so the player takes damage every 0.5 seconds
the code doesnt seem to be missing anything
but it just refuses to work
Go into whatever object has the EnemyStats script and set the public variables on the script to whatever they should be. It looks like you accidentally unset all the public variables on the script and now the damage interval has defaulted to 0 and the GameObject variables are null.
where's your scene at or are you loading most of it in
Yes, but its just what you set the public variables as in the inspector
I think
π 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.
refer to links
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyStats : MonoBehaviour
{
public EnemyScriptableObject enemyData;
//Current stats
[HideInInspector]
public float currentMoveSpeed;
[HideInInspector]
public float currentHealth;
[HideInInspector]
public float currentDamage;
public float despawnDistance = 20f;
Transform player;
void Awake()
{
//Assign the vaiables
currentMoveSpeed = enemyData.MoveSpeed;
currentHealth = enemyData.MaxHealth;
currentDamage = enemyData.Damage;
}
void Start()
{
player = FindObjectOfType<PlayerStats>().transform;
}
void Update()
{
if (Vector2.Distance(transform.position, player.position) >= despawnDistance)
{
ReturnEnemy();
}
}
public void TakeDamage(float dmg)
{
currentHealth -= dmg;
if (currentHealth <= 0)
{
Kill();
}
}
public void Kill()
{
Destroy(gameObject);
}
void OnCollisionStay2D(Collision2D col)
{
//Reference the script from the collided collider and deal damage using TakeDamage()
if (col.gameObject.CompareTag("Player"))
{
PlayerStats player = col.gameObject.GetComponent<PlayerStats>();
player.TakeDamage(currentDamage); //Make sure to use currentDamage instead of weaponData.Damage in case any damage multipliers in the future
}
}
private void OnDestroy()
{
EnemySpawner es = FindObjectOfType<EnemySpawner>();
es.OnEnemyKilled();
}
void ReturnEnemy()
{
EnemySpawner es = FindObjectOfType<EnemySpawner>();
transform.position = player.position + es.relativeSpawnPoints[Random.Range(0, es.relativeSpawnPoints.Count)].position;
}
}
checked the inspector and nothing seems wrong, the values are as i set them, heres the enemystat script
everything seems to be right on all scripts so i got no idea why the fuck im getting these errors
well, hard to help since I can't tell you what's happening on line 70
because posting in discord doesn't apply that
oof
Which line is 70 of EnemyStats?
should be whats inside the Awake function
but if the inspector stuff is set, then you should debug where you're doing GetComponent and make sure it's being set
bad weather today huh
If you can post using the external links, we can see the line numbers #π»βcode-beginner message
hold up im putting the code in a hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ok so thats the EnemyStats script
I'm assuming it's this line player.TakeDamage(currentDamage);
nope
EnemySpawner es = FindObjectOfType<EnemySpawner>();
Log it and make sure it's not null
Ah nvm
es.OnEnemyKilled();
if it is then it's not finding it
https://hastebin.com/share/oxagiqugah.csharp
this is the player stats script
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
alright
Maybe reference the spawner instead of searching for it, if possible.
wdym the rest of my scene?
like the inspector stuff?
Finding doesn't guarantee that it's valid
Unless you've everything contained on the Scene Container object there
Maybe this should be a thread
maybe
Consider referencing from the inspector if possible
Please note that this function is very slow.
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
Anyway, yeah using find is terrible. If you don't want to set references, then consider looking into a singleton pattern and grabbing references for spawn like the Enemy Spawner
i think im using singletons somewhere
does attaching a new child object will pause the animation? because its happening to me right now
ima make this into a thread so i can just dump all the shit thats giving me issues without cluttering the chat
it shouldn't but I've not really ran into that problem. Perhaps some flags being set/unset when childing
8-Bit vampire survivors issues
got it
I'm having an issue with color.lerp, it won't change smoothly with a transition as I expected, it only changes color once then after a few seconds it instantly changes color.
IEnumerator DayToNight()
{
float time = 0;
float transitionTime = 2;
while(time < transitionTime)
{
mainCamera.backgroundColor = Color.Lerp(new Color(214, 214, 214, 0), new Color(0, 0, 0, 0), time / transitionTime);
time += Time.deltaTime;
yield return null;
}
mainCamera.backgroundColor = new Color(0, 0, 0, 0);
}
Here's my code
What do you mean by smoothly?
like this
I'm trying to change it from one color to another
color a to color b
within a duration
Should probably cache the colors but it looks okay
the code?
This was just the sample reference of what I wanted to do
maincamera background color
its a solid color
I just want to make a smooth color transition from color a to color b
And values should be from 0 to 1
https://docs.unity3d.com/ScriptReference/Color.html
If you want values up to 255, use Color32
so I shouldn't use color with rgb then?
IEnumerator DayToNight()
{
float time = 0f;
float transitionTime = 2f;
Color32 day = new Color32(214, 214, 214, 255);
Color32 night = new Color32(0, 0, 0, 255);
while(time < 1f)
{
time += Time.deltaTime / transitionTime;
mainCamera.backgroundColor = Color32.Lerp(day, night, time);
yield return null;
}
}```
255? but solid colors opacity is 0?
I don't know what you're doing but 0 alpha would make the color transparent - invisible.
Can anyone tell me how can I get the cross out of an layermask object?
still doesnt work, it only makes my original color brighter, then instantly switches to black afterwards
oh wait its color32
ok it works
so what's the difference between Color and Color32?
What are you trying to do? This makes no sense
I feel bad for literally giving me the right code to this though
Might as well get something to learn from this
Color uses normalized values
Help, im planning to do the second image but it does this
The code: (GrabbedObject is the Red Object)
grabbedObject.GetComponent<Rigidbody2D>().isKinematic = true;
grabbedObject.transform.position = ray.position;
grabbedObject.transform.SetParent(transform);
Getting the cross value out from my wall object
then making the player run in that direction
Cross value out is not a real term, and what does this have to do with the layermask you said before
meaning?
Normalized values are within ranges of [0f, 1f] whereas Color32 accepts values from [0, 255]
I'm trying to get the cross direction of my wall
to tell my player to follow that direction
That's why I need the cross of the wall
It's practically your values divided by 255:
214/255 = 0.839
Ahh okay okay I see, but how is that different from the values that normal Color uses? Maybe I should have mentioned that this was a 2D game if that makes any difference between using Color and Color32
This still is just gibberish, and I believe your original error was because you were trying to assign a vector into a layermask. (Still not sure what the layermask was for)
You likely want to use the ProjectOnPlane method instead. But honestly with what you were plugging into the cross product method, you might want to learn more basics first.
They're the same thing, just different ways of representing the same values.
Normalized 214 would be 0.839
If you want to use Color, you'd use the normalized values else use Color32
Ah okay, but how did that make the major difference in smooth color lerp transitioning in my code?
Well for starters, your alpha was zero so there wasn't any visible color present.
Second, if you feed Color a value of 214 it'll behave as though you've fed it 1 so Color(1, 1, 1) would just be white but with an alpha of zero, you'd get no colors - invisible.
Going from no color white to no color black would just have you see a no color.
what if you change the position of the pivot?
maybe it attaches to the pivot
Basically, you were using non normalized values for Color that was expecting normalized values and you had alpha transparency set to max which made your color invisible to the eye.
got it
so you're saying that Color takes normalized rgb values as arguments?? while Color32 takes up the usual 0 - 255 RGB values as its arguments?
ah alr, I was searching for an image to explain it.
Thank youu
np
Layermask is to detect if I'm colliding with the wall or not
This is a layermask https://docs.unity3d.com/ScriptReference/LayerMask.html
It's not a Vector3. If anything, you can get a numeric value of which layer it's referring to.
Assigning it the cross product of two Vectors make little sense.
I'm trying to get access to the layer's object properties
I wasn't assigning
I was trying to show what I'm trying to get
reload scene on player death issues
Which is.. the cross product of two Vectors. Layermasks are unrelated to math or coordinates.
It doesn't make sense.
bruh
I said If I hit an object that has the specific layer then it'll make me move in the that object's cross product
What does a Vector3 have to do with a layermask?
nothing
i just find out that dictionary cannot have multiple key for a value (GameObject), i thought only the key that has to be unique.
what collection should i use for that purpose ?
Where did you read about values having to be unique?
wait
Pretty certain only the keys have got to be unique like with any other language unless there's been a new feature I'm not awre of
Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer. A key cannot be null, but a value can be, if its type TValue is a reference type.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-8.0
i got the error message that states it
Perhaps show us this error message?
multiple value detected or something
sec im looking fo rit
i already changed my code
yeah, only the key is what needs to be unique
yea i missread.. so my problem lies elsewhere then ArgumentException: An item with the same key has already been added
Yeah, it would seem to be a duplicate property or something
Hello, I tried to make an infinite loop coroutine to make gameobject no visible until a certain condition is met
IEnumerator HideDayBackground(ObstacleScript[] gameObstacles)
{
while(true)
{
foreach (var gameObstacle in gameObstacles)
{
if (gameObstacle.prefabObjectType == PrefabObjectType.Day)
{
gameObstacle.gameObject.SetActive(false);
}
else if (gameObstacle.prefabObjectType == PrefabObjectType.Night)
{
gameObstacle.gameObject.SetActive(true);
}
}
}
}
It however crashed my unity editor lol
I've put a character controller on my enemies. I have some code to make them face the player and Move() towards them. I implemented collisions with some throwables and the player with OnControllerColliderHit and sure enough they wouldn't react to stuff thrown at them when they're in idle state. (because the oncontrollercolliderhit is only called whenever the controller is moving). So beginner question: how do I setup my enemies? the character controller ensured they would follow slopes and the ground correctly. I was hoping to make them use navmeshes eventually. But if I want them to be able to fall off a cliff or something I still need to just put a capsule collider on them and implement things I got from the character controller myself? What's the "standard" way of doing this?
@lunar grove put a yield return new WaitForSeconds(1) (or however often you want to check for your condition) at the end of your while {} block. https://docs.unity3d.com/ScriptReference/WaitForSeconds.html
if you want physics with navmesh you simply don't compute the path when they aren't grounded
nor allow them to continue moving on the path they were currently on
how do i find the coordinates of where the player is looking at
raycast a screen ray and get the hit.point
probably start from the middle of screen space
Is it better to use Array.Find or to loop through the arrays items and find the item im looking for?
use dictionary
Thats not an answer to my question
array is pretty simplified concept itself so there's no real pattern matching beyond iterating and comparing it yourself
btw i would avoid using callback, that is much slower then normal function call (though callback is much easier to use)
and i will use dictionary or sorted set if possible
O(n)=O(10n) when n->infinity
that is a code relating channel, not off-topic
How do we add depth to Unity 2D? (like jumps and stuffs)
I am making a top-down game
Oh, sorry
shadows are one way but yeah this is a code channel
this is a code related channel
would this not return true if the player is falling? (or whatever i run this on is moving downwards)
Do you guys think this is the right way to do this?
basically I'm moving forward When I press W
nope, it would only work when you are pressing down
that's not how it works, that just input -1 to 1
I am thinking of adding z_value into consideration, making the y_value that appears on the screen = y_grounded_value + some_coefficient*z_value
how do we implement this? can we change unity rendering code?
can you guys elaborate
it returns a value of your joystick/keyboard input
down = -1
no input = 0
up = 1
Since input is not smoothed, keyboard input will always be either -1, 0 or 1
so its NOT if the player is falling, but if i press the down arrow button?
moving down in the y axis
you need to make your own falling logic
it's just input
it doesnt detect if player is moving down in the y axis
it detects if you press "S" key or left stick on gamepad down, or dpad down or whatever

Also for the sake of improving the way you write code, you can just do return lastPosition.y < playerTransform.position.y
even if the player moves up or down
Then consider logging both variables and see what they are each frame. That way you can determine what happens
You can use Debug.Log for that and then look at the editor console for the output
Debug.Log($"{lastPosition.y} - {playerTransform.position.y}");
Something like this, in your Update method.
Yes so my guess is you update lastPosition, and then check against the current position
Hey Guys
Does somebody know if the Object reference changed or something in the newer version?'Object' is an ambiguous reference between 'UnityEngine.Object' and 'object'
You need to make sure you update it after. One way would be to use LateUpdate
But I do advice against it
'Object' is an ambiguous reference between 'UnityEngine.Object' and 'object'
Remove using System; at the top of your file
Or add this:
using object = UnityEngine.Object;
If you need the namespace.
update it after i run the method that compares them, makes sense
You can also always have it 1 call behind in some way
So you don't update it immediatley, but instead you use something like a Queue for example
Thank you!!
All in all I just don't advice LateUpdate since you either use the normal variant or a late variant, and if you still need to have something happen later then you have no proper solution
So uhh, probably better to have a Queue and to take the second entry. The first one would be the same again most likely
okay so there a few problems, mainly that it somehow can set jump to true even when the player is idle, imma take a look at queue and see how it works, cuz rn i udpate the pos last thing in update
If you use the Queue class it works similar to a List, but instead of adding items you enqueue items. If you set the max size to 2 it will pop whatever items are added first so you can just get the second entry every time
Probably not very efficient though, but I think a queue is pretty solid when it comes to tackling the issue before you do any sort of polishing.
Be sure to make a GetLastPosition method or property that gets the entry in the queue for you to avoid having to rewrite a lot of code later
When i run left my character has a greater hitbox than when i walk right
any way to help?
I've been following a guide until I ran into a code i wasn't familiar with, it was called BoxGroup, what is it used for and is it code used from the asset store?
Maybe it's GroupBox?
Not much that can be said here unless you share the guide, perhaps
is there a way to check if a specific GameObject exists?
Yes, by using a Find method, but you should not use this. It also depends on what you're trying to do because there is almost definitely a better way.
I'm just trying to use it in an if statement to check if a specific game object exists
Yes, but why? Why check for a gameobject? What is the purpose of the script?
I doubt you are checking a random gameobject unless you aim for a specific system
So I can assure that the next object it spawns isn't the same type
Again, what is this system? Please specify it
Is it a monster spawner? Please share the code
It's actually just the chrome dino game lmaoo in unity, I need the moon phases
once a previous moon phase has gone by the next one must progress
Why not reuse the same moon instance and change its sprite to the next phase?
I feel like that's easier than removing the last moon instance every time
Because rather than reusing game objects my code has already been establish as destroying game objects once it has left the camera
Either way, if you were to spawn a new gameobject then consider using an enum, and a variable that holds that enum as the "last phase"
Then when you spawn the next one, check this variable for the next enum to spawn
And you can contain the moon's gameobject in another variable so you know what to destroy
I see. Generally you should not destroy and create gameobjects constantly and instead pool them or reuse them properly. I do think it's overkill for this but keep it in mind for when you are consistently removing and creating gameobjects for something
Yeah, I did this since its just a dino game lol
@burnt vapor
can you help me with my problem from above?
What does it say?
No, consider asking in #π»βunity-talk since this is not a coding question and please don't ping specific people for help
@short hazel i still have the error evne by switching it to SpriteRenderer
u mean the health bar?
Whatever you're trying to modify the fill amount of
What is Image here? I think your mistake is not using UnityEngine.UI.Image
Because that one has fillAmount
Yeah so that's the Image type
Could be wrong tho
Newer Unity versions have some changes with UI so you might be using a different Image class
So if your code fails to find a fillAmount property on it, then it's not finding the right Image type - did you make your own class Image? It's picking that one first
i tryed but that doesent fix
From what I understand you have UnityEngine.UI.Image.fillFormat in older versions, and UnityEngine.UIElements.Image.fillFormat in newer versions
But you have a separate package for UnityEngine.UIElements.Image.fillFormat you need to install or something
yes
why
Well there you go. Avoid naming your own classes the same as Unity's
Since your classes are put in the global namespace, it's technically closer to the one in UnityEngine.UI
So the compiler takes yours first
Did you rename your own Image class to something else?
yes
Make sure you saved and returned to Unity so the code is recompiled
Clear the console and make sure the error is not present there
still nothing
Show the declaration of your variable
Okay Ctrl+Click that Image and see where it takes you
It takes me to Image.cs
Which one? Unity's
yes, unity's
you can just hover over the Image variable type and see in which namespace it is
oh
You have the wrong using directive in your own code
Unity's Image class is in UnityEngine.UI
im trying to make my exp collectible spawn after destroying, but debug log is not showing "Exp collectible spawned". where the problem could be?
numberOfExpToSpawn is probably 0 in the inspector. Inspector value is what matters, not the number inside your script.
I have an audio listener and audio source, now I need to increase the speed of sound so how do I do it?
my current part of code:
{
score++;
speed+=0.2f;
Debug.Log("Score: " + score);
//transform.localScale += new Vector3(0.2f, 0.2f, 0f);
//GameObject.FindWithTag("Food").audioSource.Play();
SpawnRandom("Food");
//SpawnRandom("MWall");
}```
it is 10 in inspector.
also the audio components are attached to that object whose script this is
then the prefab is probably not assigned
You probably want to increase the pitch with:
audioSource.pitch = 1.5f;
do you get the expspawner destroyed debug log?
thanks
pitch has nothing to do with speed
so += right?
can someone help me with the fix?
pitch wont modify the speed of the audio clip
then?
the function returns an array of colliders that are in the sphere
it is assigned
do what you want with that array
so it cant be in an if
a pitch of 2 makes the sound play twice as fast as with a pitch of 1
yes
what are you trying to check?
by increasing the pitch you are "faking" the playback speed
but in reality you are not increasing the actual audio clip speed
you could see if the length is greater than 0, or loop through the array
depends on what you are trying to do
what lenght?
there isn't a built-in solution
you can use pitch scaling
to imitate that
just try it out and see if it is what you want, pitch of 1 is usually the default value and 3 is max
oh
time stretching requires a more complex algorithm that can be quite slow
i was trying to check whenever something collides i can do something like pickit up
for example
ok, so i'd just loop through the array and do your pick up logic
you can modify the pitch, then do 1/pitch in the audio mixer
only way to imitate the "speed up"
just changing the pitch wont do the trick
how can i loop tho sorry im new to this stuff
your audio clip will sound very high pitched only, not speeded up (it will be played in the same duration, just higher pitched)
does "ExpSpawner destroyed" show up?
it does
i recommend learning some C# basics
like what an array is and looping
those are key concepts
then check if the method is getting called and if the loop is getting called
probably would be neccessary but its boring tho
you can't get help
and coding seems more fun even when im struggling
good luck getting far without it
if you dont understand it
okay thanks :3
yes, the method is being called and loop too
If you think learning the basics is boring you're going to have a difficult time attempting to create any system or game mechanic which are essential for your game . . .
then expCollectiblePrefab must be null.
what can i do?
Remove line 2. That's causing the ambiguity because both namespaces have a MinAttribute in them, so the compiler can't choose for you
Yes work now thanks a lot
ok yea, i was dumb. I assigned exp collectible prefab from the scene and not the prefab folder. Its working now. Thank you!
hey guys, can someone tell me why I cant move in the scene view in unity 3d?
I'd appreciate any kind of help
you arenβt really putiting input into the game while in scene view
you can only really move things via transforms etc, like you would do in editor
Can anyone help me to fix an issue regarding Attack animation?
I have a PlayerObject with a Combat script. In this script I create a method "public IEnumerate DamageWhileAnimationPlays()"
on my PlayerObject I have a SubObject which is the PlayerSprite with an Animator attached. When I now try to create an animation Event and call the "DamageWhileAnimationPlays()" it doesnt show me any methods within the "create animation event" -window I know it's probably because the Combat Script is attached to "Player" and the Animator is attached to "Player/PlayerSprite". But is there a way to get this working?
Can you post the full code?
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Timeline;
public class PlayerCombat : MonoBehaviour
{
public Animator _anim;
private RaycastHit2D[] hits;
private float _attackTimeCounter;
[SerializeField] private Transform _attackPoint;
[SerializeField] private LayerMask _attackableLayer;
[SerializeField] private float _attackRange = 0.8f;
[SerializeField] private float _attackDamage = 1f;
[SerializeField] private float _timeBetweenAttacks = 0.15f;
public bool _shouldBeDamaging { get; private set; } = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private void Update()
{
if (_attackTimeCounter >= _timeBetweenAttacks && (Input.GetButtonDown("Fire1")))
{
_anim.SetTrigger("Attack");
}
_attackTimeCounter += Time.deltaTime;
}
public IEnumerator DamageWhileSlashIsActive()
{
_shouldBeDamaging = true;
while(_shouldBeDamaging)
{
hits = Physics2D.CircleCastAll(_attackPoint.position, _attackRange, transform.right, 0f, _attackableLayer);
for(int i = 0; i < hits.Length; i++)
{
IDamageable iDamageable = hits[i].collider.gameObject.GetComponent<IDamageable>();
//if we found an iDamageable
if (iDamageable != null)
{
//apply damage
iDamageable.Damage(_attackDamage);
}
}
yield return null;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(_attackPoint.position, _attackRange);
}
#region AnimationTriggers
public void _shouldBeDamagingToTrue()
{
_shouldBeDamaging = true;
}
public void _shouldBeDamagingToFalse()
{
_shouldBeDamaging = false;
}
#endregion
}
I got this script attached to the Object "Player" and got the Animator on the Object "Player/PlayerSprite". And basically I want to create an Animation Event with DamageWhileSlashIsActive() and one with _shouldBeDamagingToFalse()
can someone tell me why the object isnt moving in the game?
I'd appreciate any kind of help
not too sure about animation events, but if the problem is that perhaps the prototype of the method (it being a IEnumerator) is the problem, then maybe consider making another void method that calls it
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah, DamageWhileSlashIsActive is a coroutine, not a method so itβs not gonna pop up
bro tf is this
Bro itβs the way youβre supposed to post code
read the bot message and share the code properly
screenshots are a pain in the ass to view, esp on mobile
I know that you can use IEnumerator for Animation Events. I've done it before. I think the issue is that the Animator and the Combat script are on 2 different Objects and I don't know how to work around it
Oh you just create a reference to the other object
So make a public GameObject player; and in the inspector, drag the player into variable. Then, just say player.GetComponent<PlayerCombat>().theMethodIWantToReference @ionic lava
ok and are you certain this script is running?
0 errors
Ohhh I see. I'll give it a try. Thanks! @thorn holly
no issues found
ok, show the object where you put this script
Yup. Lmk if it doesnβt work
But is the script attached to the GameObject you want it to move?
yes
In this code
public float speed = 1f;
public float startAngle, endAngle;
private float startRot, stopRot, lerpAlpha, currentRot;
private bool animate, isRotated;
void Update()
{
if (Input.GetKey(KeyCode.Z ) || Input.GetKey(KeyCode.X))
{
if (!animate)
{
animate = true;
startRot = isRotated ? startAngle : endAngle;
stopRot = isRotated ? endAngle : startAngle;
currentRot = startRot;
}
}
Rotate();
}
private void Rotate()
{
if (!animate) return;
currentRot = Mathf.Lerp(currentRot, stopRot, Time.deltaTime * speed);
transform.rotation = Quaternion.Euler(Vector3.back * currentRot);
if (Mathf.Abs(currentRot - stopRot) <= 0.1f)
{
animate = false;
isRotated = !isRotated;
}
}
When Z or X is pressed the object rotates towards a different place, but the code works overall and the object rotates. But what im trying to say is that its not supposed to rotate the either way (its hard to explain, i recorded it)
ITs not supposed to rotate to the left
guys how do i start 2d indie game development?
with a mouse and keyboard
like im look for 2d game assist ai for generating sprite characters for rpg games
Should be rotating on the x axis I believe
just use sprites from sites like itch.io
you aint gonna find anything much useful with AI
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class turret : MonoBehaviour
{
[SerializeField] private Transform GunRotation;
[SerializeField] private float Range = 3f;
private Transform target;
[SerializeField] private LayerMask enemyMask;
void Start()
{
}
void Update()
{
if (target == null)
{
FindTarget();
return;
}
RotateTowardsTarget();
}
private void OnDrawGizmosSelected()
{
Handles.color = Color.black;
Handles.DrawWireDisc(transform.position, transform.forward, Range);
}
private void FindTarget()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Range, Vector2.zero, 0f, enemyMask);
if (hits.Length > 0)
{
target = hits[0].transform;
}
}
private void RotateTowardsTarget()
{
float angle = Mathf.Atan2((float)(target.position.y - transform.position.y), (float)(target.position.x - transform.position.x)) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
transform.rotation = targetRotation;
}
}```
!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.
Large code, use links
mb
works like a charm. Ty!
Fs!
I've just rid of a lot of Euler methods and primarily been using AngleAxis so maybe give that a try
Is there a way to make certain methods in a delegate run before others? Or is it all at the same time when the delegate is called.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class turret : MonoBehaviour
{
[SerializeField] private Transform GunRotation;
[SerializeField] private float Range = 3f;
private Transform target;
[SerializeField] private LayerMask enemyMask;
void Start()
{
}
void Update()
{
if (target == null)
{
FindTarget();
return;
}
RotateTowardsTarget();
}
private void OnDrawGizmosSelected()
{
Handles.color = Color.black;
Handles.DrawWireDisc(transform.position, transform.forward, Range);
}
private void FindTarget()
{
RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Range, Vector2.zero, 0f, enemyMask);
if (hits.Length > 0)
{
target = hits[0].transform;
}
}
private void RotateTowardsTarget()
{
float angle = Mathf.Atan2((float)(target.position.y - transform.position.y), (float)(target.position.x - transform.position.x)) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(new Vector3(0f, 0f, angle));
transform.rotation = targetRotation;
}
}```
we cant see line numbers like this genius
I been said use Link for large code
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this
this i s the wrong script mate
just me or did he sent wrong script
oohh
why are all of your classes starting from lower case?
that's not good C# and Unity standard
guys am I supposed to add f next to the numbers in the vector
i didnt touch the movement tho
for instance instead of (0,5,0), should I write (0,5f,0)
if theyre floats yes
you put f after the number
If you want to use decimals
write them after every number
what's a bigger value than uint?
okay
For ints it's not necessary but won't hurt anything
okay
Like this? ```cs
transform.rotation = Quaternion.AngleAxis(currentRot, Vector3.back);
did you try google?
it says long, but can I use that in Unity?
Is there a way to make certain methods get called before others in a delegate?
Then goblins must have done it. Either way your code is broken and you have to fix it
Or is it all asynchronous
yeah those goblins suck
It's the order they subscribed in
Sweet
||The goblin is you. Programming is like being a detective in a mystery show where you are also the murderer||
Another day, another w for delegates
"My car is broken." "But this is a bicycle?" "Yeah but I haven't touched my car"
it doesn't
What doesn't work about them
it does
it says that ulong is an unexpected token in my shader
Is this shader code or C#? If it's a shader that would probably have been a good thing to mention up front
why do you need a ulong in a first place?
i feel like you dont need it at all lol
what shader are you doing
it's both, it seems to be working on the cpu side, but not in the gpu
i need but probably will end up just using two buffers of uint. I needed the ulong because Im storing some indices that surpass the uint max value
I wanted to save some space by doing some bitoperations on uint and save the last byte, but I was looking for something inbetween uint and ulong
but it seems that if the size is not multiple of 4 it cannot be used in shaders, so there's nothing inbetween i guess
I am trying to debug some scripts in visual studio but for some reason it cant see or find anything under Packages, only stuff under Assets
How do I fix this and let it debug stuff in packages?
when I try to F11 to advance into the script, it brings up a 'cant find this in default path' complaint, with the default path being completely bogus
and when I manually go to the file, it lists it as 'external' for some reason
Shaders are an entirely different beast, they have a lot fewer options for data types because they need to make sure they can pipe it to the GPU.
It seems strange that you'd need numbers so high, but maybe #archived-shaders knows some tricks for packing big data into a shader?
i will try there then, let's see
so did you fix it?
yes
hi everyone... could someone tell me what i could improve about this... game structure... thing... :DDDDD
yo can someone help add my idle animation to my character in unity
not the x bot the character that I imported
bc it seems to not work
like I have the animator and the idle animation put into the block put idk why it will not work
Without context as to what the lines mean or what these classes do this diagram means absolutely nothing to anyone on the planet but you.
But if it does make sense to you then that's all that's really needed
i mean its a card game i just wanted to know if the code structure was at least somewhat decent
deck.cs holds the card objects and manages them
card.cs is a scriptable object thats just there for the card display and everyhting
this isn't a code questions
#πβanimation
i mean afaik i could just stuff everything into like three classes and call it a day
i just wanna do it the unity way ive read a couple books and it did clear a few things up but i
ok
i dont know honestly
Can someone explain to me how the inside of the "if" line of code works? I don't understand why we are using a new Vector3 and not Vector3 by its self? and why did he write transform.position.y and transform.position.z instead of just writting 0, 0
reposted since I sent it in the wrong chat
isnt vector3 a class
struct
You cannot use Vector by itself unless you're calling a static member
well i was close enough
The above would be calling the constructor to create a new instance of the type
because you need to make a new struct to replace old one, unless you had a Vector3 already stored and modify that one to put into transform.position
New is how you create an object. It creates a new vector and sets position to that
so you use new Vector3 whenever you have another vector3 in the line?
no
in this case transform.position is a V3 but you cannot modify directly its properties (x,y,z) only read them
so you either put another new vector3 that you created earlier or now hence the new()
You use new Vector3 whenever you want to create a vector
hey guys, quick question, anyone knows how to properly set the cinemachine? The vcam is set to follow the character but clearly thereΒ΄s a delay in that process
how are these screenshot showing delay ?
There is a property in the body section for that
^^ you want to remove damping probably
so you guys are saying as long as the game runs i shouldnt worry about the way i coded it...
well kinda, at least attempt to make it somewhat "clean to read"
for your own sanity
all i needed to hear, thank you
im using the tape for measurement, the tape is like the central point and when the characters walk its not centred to the tape, idk if that makes sense xd
ill check it out
What I'm saying is that we can't interpret your graph but we also aren't the ones that are going to be using it so if it works for you then more power to you.
well make sure also the pivots are correct dead on the player
usually Center mode will throw you off
instead use Local/Pivot mode
The assignment operator (the equal sign) suggests that you're wanting to assign something on the right to the left. Position is a property that is of the type Vector3. Since it's a property, we cannot modify it's members (x, y, z) directly so instead we'll assign it a completely different Vector3 instance. To create a new Vector3, you'd use the new keyword with it's constructor.
alright, so its all up to my creativity.... honestly didn't expect that from c# one bit
got it
how so, the language is inconsequential in these matters.
langauage is just a tool to achieve a goal
you're telling the computer to do X Y Z
it doesn't care which language it is
its all machine code in the end
Another common pattern is to copy the Vector 3, modify the particular component and reassign it back to the position propertycs var position = transform.position;//Cache the position position.x = -10;//Modify the x component of the Vector 3 transform.position = position;//overwrite the position property with our updated cacheReminder that properties aren't fields.
ive used a couple languages before deciding to ultimately switch to c#... and usually you have to come up with your very own creative solutions to problems more often than not... c# on the other hand has everything already covered and its... weird...
This has the benefit of not creating multiple new vectors which occurs for every call to transform.position
var feels like cheating tbh
yeah c# def hit my noodles early, it was surpisingly easier than what i've encountered before ( working with C++ on source engine)
yeah c# right after c++ is definitely a breeze
I used to think Game Maker Scripting language was hard so I never learned and used all drag n drop componentsπ€·ββοΈ few years later I'm coding in c# strictly π
are gdscript and gamemaker script even worth learning at this point
i mean honestly cant blame you i did the same thing
I like that Godot has C# and its newer .NET
no point in being a one-trick pony if you can make a game and write a server for the said game in c#
definitely
{
// Assign your player prefab, camera prefab, and Cinemachine prefab in the Unity Editor
public GameObject playerPrefab;
public GameObject CinemachineFreeLook;
public GameObject GameMananger;
private void Awake()
{
// Check if player, camera, and Cinemachine already exist in the scene
if (GameObject.FindGameObjectWithTag("Player") == null)
{
Instantiate(playerPrefab);
playerPrefab.GetComponent<Animator>().Rebind();
Debug.Log("added a rebind");
DontDestroyOnLoad(playerPrefab);
}
if (GameObject.FindGameObjectWithTag("FreeLook") == null)
{
Instantiate(CinemachineFreeLook);
DontDestroyOnLoad(CinemachineFreeLook);
}
if (GameObject.FindGameObjectWithTag("GameManager") == null)
{
Instantiate(GameMananger);
DontDestroyOnLoad(CinemachineFreeLook);
}
}
}``` is this the best way to do ddol?
Oh no..
don't name a class "DontDestroyOnLoad"
actually its a MB function so it prob doesn't matter...
definitely weird
i can rename it, is there already a DDOL class?
And the code won't work
dont think so no, its just a built in function in Monos (actually Object class)
Calling DontDestroyOnLoad on a prefab does nothing at best, throws an exception at worst
i see
how would you do DDOL
You use the value Instantiate returns and put that in DDOL
also would just use it in a singleton pattern
https://unity.huh.how/references/singletons
(much cleaner to have 1 class you can just adapt many singleton)
So if i went the singleton way. Could i create an essential Loader class. then have all my DDOl on that class
they can just inherit from that 1 singletonclass and you dont have to do any additonal logic or keep track of anything
or make the player a singleton
like per example Foo : Singleton<Foo>
and add the null check on that
transform.position is obtained through a property (getter) but there is no setter for independent values of x, y, z; there is only a setter for Vector3 struct as a whole. This means the only way to change the position is to send your own Vector3 struct into transform. Also, since transform.position is a property, the Vector3 information you receive is passed by value because structs are value type, meaning that editing the recieved Vector3 data will not reflect the actual transform.position data unless you send it back.
you want to avoid writing repetitive code
you write DDOL like 3 times in 1 class instead of having class take care of itself by inheritance
there are many ways to do pretty much everything, ultimetly its up to you. You're the one looking at the code
ok thanks guys
can some one help me find out where is error from this code ? i learn this course from udemy btw
π
!vscode
You need to configure VS Code so errors are highlighted in the code directly
Hi I am working on a pause menu for my game and put it in level one no problem but for level two I can not get the buttons to click, I had no idea what is wrong any help is greatly appreciated
You need an Event System in your scene. It's automatically added when you create a Canvas, so you probably removed it by accident.
Add one, it's what sends events to your UI elements
hi!
mScrollRect.normalizedPosition = Vector2.Lerp(mScrollRect.normalizedPosition, newNormalizedPosition, 10f);
does anyone know why this isnt moving smoothly? it just snaps to the new position
this is wrong
because that is not how to use Lerp
learn how lerp values t
https://unity.huh.how/lerp/overview
10f is literally impossible for t
Is it normal if the moove speed is higher in void FixesUptade than in void Update ?
depends what ur doing , show code
normal usecase but you have to write it correctly, coroutine is easiest imo
ur mean this ? should i unlock this one ?
Nah that one gets removed
Visual Studio Code Editor
did you read the link at all ?
No that package is not used anymore. Go back up, click the link and follow all the instructions
Hello, beginner here. So I have only small code here and unity executes Debug.Log twice. Why is that?
!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.
Usually you want to base movement on Time.deltaTime in Update and Time.fixedDeltaTime in FixedUpdate. However keep in mind you can set maximum Time.deltaTime in your project settings - in a case of a huge frame drop it will clamp the values.
also pass in the gameObject second param in the Debug.Log
see where the logs come from
nvm
thats a constructor
kinda invalid for a MB
use Awake instead
I write : horizontalMovement = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
Awake as a second parameter?
no as in use the Awake Method
Monobehavior are slightly different than regular classes, they are instanced by unity
Then in FixedUpdate you should replace Time.deltaTime with Time.fixedDeltaTime. If you have stuff like acceleration, then I recommend keeping movement code in FixedUpdate to make it easier to manage.
When I keep my mouvement on FixedUpdate, my jump is broke
Ah it works ! thank you so much
I watch a freeCodeCamp tutorial. and mentor removes MonoBehavior at all. when I remove it i get an error
if you remove it then its a regular POCO
should be no errors
you just cannot attach it to a gameobject though.
Show the error maybe ?
just in case you didnt know. But if you use Time.deltaTime in FixedUpdate it actually uses Time.fixedDeltaTime
deltaTime becomes fixedDeltaTime time when used in FixedUpdate . . .
Show us the actual code . . .
... i did.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player
{
int health = 100;
public Player()
{
Debug.Log($"This is health {health}");
}
}
some of those is because the script is still attached to a gameobject
so it should not be
Did you remove the script from the GameObject when you had MonoBehaviour attached to the script file?
never , unless its monobehvaior derived
regular classes can be embedded in MB and then attached to gameobject through that
or just instantate it when needed with new()
But they cannot be attached to gameobject directly
Only classes derived from MonoBehaviour can be attached to a GameObject . . .
Do you mean inputs? I believe inputs by default are configured to match frames. FixedUpdate doesn't align with frames, which might make you lose some inputs. I don't remember if it can be configured differently. I usually separate inputs and movement logic from each other to avoid potential issues.
@scarlet tiger @cosmic dagger That's interesting. Thanks for letting me know. π
when should you use "Int" when coding in unity?
so what i did was: removed NON MonoBehaviour script from gameObject. created Player warrior = new Player(); in different script which IS attached to gameObject. and Debug.Log() was executed once. thank you @rich adder @cosmic dagger β€οΈ
Whenever you want to store an integer (no decimals) number, and do operations on it.
Use Int when you need a number without decimals to save space
so we use float when we work with positions/x,y,z and decimals?
int is used for numbers that are integers (aren't decimal numbers) and are in a range between -2,147,483,648 and 2,147,483,647. If you need bigger numbers, use long. If you need decimal values, use float.
gotchu
Both int and float are actually on 4 bytes!
Unity doesn't use decimals for transform, they are floats
Cool, I didnβt know that
hello!
how can i animate a vector2 variable to get another value with leantween?
something like this
var position = new Vector2(0f, 0f);
LeanTween.move(position, new Vector2(100f, 100f), time);
in which the value of position changes as if it was a moving object
is it not working or something?
Hey guys, is there a good tutorial on how to make a bow and arrow 3rd person system?
probably, search it up
just do a 3rd person gun tutorial
what does that even mean
And Animation Rigging does not seem to fit, for my case at least
you're asking about the whole system you aint gonna find much
gun that shoots arrows
no bc the first parameter should be a gameobject. iwas thinking there might be some way using ltrect but i didnt really uderstand what those are from the leantween documentation
Yep, tried but aiming feels clunky, even with today standards
idk I use Dotween
Leantween was wack for me
!code
and how would you do it in dotween?
π 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.
do you only want to lerp V2?
yes
but be able to choose the easing
and not have to make a coroutine
whats wrong with that + https://docs.unity3d.com/ScriptReference/Vector2.Lerp.html
hi im trying to make a thirdperson item pickupscript but im stuck on checking if the item is close to the player(in my example 3f) im trying to do it with the overlapsphere but i dont know how to take exact values out of the array to do stuff with them maybe im trying to do it wrong if you have better ideas let me know
heres the script https://gdl.space/ogijikifox.cs
Hey guys, I think this can be answered without showing my full script. I have script on a on an object and a reference to my player(rigidbody) on the script, but on start ,it deletes and I get an error " There is no 'Rigidbody' attached to... ". I even have a on start to call the rb
private void Start()
{
RB = GetComponent<Rigidbody>();
}
am I doing this wrong? Does the object need a rigidbody its self for me to access another(player)
This where those c# problems come along but iterating through foreach is something you should read into
https://www.w3schools.com/cs/cs_foreach_loop.php
I suggest just go through all the topics on this if you've not. Very basic concepts to go through
I'd probably make a Sphere Collider act like a pickup detector and add every detected pickup into a list upon OnTriggerEnter and remove them with OnTriggerExit, then basically what Mao said
nvm I fixed it, I need to acces the player game object first.. than get the rigidbody
hello, I get this error:
Unable to find shaders used for the terrain engine. Please include Nature/Terrain/BillboardTree shader in Graphics settings.
What I don't understand is, why do I don't get this error in playmode? Only when I build the game and play via the build. I understand what it wants me to do, but I don't even have that shader it seems, the only shaders I have in Nature/Terrain/ are Diffuse, Specular and Standard.
So what is going on?
Any help is MUCH MUCH appreciated! (PS: I am using Adressables if it makes a difference)
i've got this "not loaded" "is loading" problem everytime, here is my zone changer code :
!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.
oops sorry wait
everytime i try to paste the code it change it to message.txt
because you're doing it wrong
