#💻┃code-beginner
1 messages · Page 1 of 1 (latest)
ok
do a nullcheck on the script that's accessing the enemy object
this error appears after i aded a enemy spawners
so when the player kill the first enemy the error appear and the Spawnerrs didint work
Well then you should probably put a prefab in the spawner instead of the enemy itself?
How exactly?
yes
the enemy is prefab
Anyhow, sharing the code will always get you better help
im just guessing in the dark now
thats right
.
do u know how to bring back the enemy from the prefab
some help (;
Maybe show some code?
can u pleas just tell me how to bring back the enemy from the prefab
We don't know anything about your code or scene.
can u pleas just tell me how to bring back the enemy from prefab to a normal OBJ
(:
What have you tried?
Bring the enemy back from where?
This is the coding channel so I'm assuming we're discussing something about code.
#854851968446365696
Usually, you'd show what you've tried and people would give you suggestions.
see
.
?
no they are asking you to show your code, they can't help you if you don't show your code.
the error not in the CODE
if the error is not in the code then why are you asking in a coding channel?
x = (gameObject.transform.position.x < 0)? gameObject.transform.position.x -0.5 : gameObject.transform.position.x + 0.5;
how can I type cast this into a float?
like how do you use type casting with the ?: operator
you don't need to cast anything, just use a float value for the amount you want to add . . .
do you know how to make a float value? if not, i'd look it up, it's quite simple . . .
huh? you just asked about a float value, not it's supposed to be a Vector3? you're only assigning the value to x which i assume is a float . . .
yep . . .
ye ye im stupid
Hello, I'm fairly new to unity and I've just designed an enemy that detects if the player is in range and starts exploding once it's detected a player.
The enemy object currently has a polygon collider for it's hit box and a circle collider set to is trigger for detecting the player.
The problem I'm facing currently is that when circle collider is acting as a hit box as well. I read online that I should move the circle collider to an empty child object. My question is do I need to write a separate script for the child object or is there a way for the parent object to read the ontriggerenter of the child object.
Sorry if this is confusing and long 💀
All colliders will become "part" of their nearest parent rigidbody. If a rigidbody object has a box collider, and a child object of that has a circle collider, an OnCollisionEnter script on the parent will fire if something hits the circle collider.
When a collision happens, the rigidbody component is the thing that calls the OnCollision functions, and it calls it on itself and the attached rigidbody of the collider it's interacting with (if it has one)
Absolutely not, A script can have both OnCollision methods and OnTrigger methods
Thank you for your replies :).
Just wanna say, this is a very common code error. It is saying the CODE is trying to use the object after it has been destroyed (which can only happen through code or I guess if you manually delete the object from the scene view during runtime, which you should of course never do)....
The error is most definitely caused by your code but as you wont share it there is no helping you
Hi guys, i have bought a pack named Low Poly Restaurant, did you know why i see all like this_
Incompatible render pipeline. Your project is using a render pipeline your materials aren't compatible with.
Use materials compatible with your render pipeline, or use a render pipeline compatible with your materials.
One of em has to change
Fixxed thank you
private void OnCollisionEnter(Collision collision)
{
placement.CanPlace = false;
}``` this is not doing anything when a collision happens, did i code it wrong?
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt Not tick
isTriggeron either - Thou Shalt have a 3D Rigidbody on at least one of them
||Function name + 2d||
Hi! Im a beginner and have some trouble with my start screen and buttons. I did an animation for the start screen and make the button to play the game but its not clickable?
When i try to click on the button the game screen closes
I'm having issues with an instantiated object not running its Start() and therefore getting NullReferenceExceptions later on in the same script (many many frames after the initial instantiation). I've read in multiple forums that Start() will always run for instantiated objects, so I'm a little confused here. Any clue on what might be happening? I can provide more info if needed
show your !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Start will run before the first Update this object exists and is active for
is the prefab is disabled by default, the start wont run iirc
Instantiation code on the player object
//The class this is running on is not a child of Monobehaviour, it's just a standard C# class with a method named Start
public PenFeatherShotBehaviour() : base()
{
actionBuffer = new Timer(0.05f);
// PREFAB LOADING
featherShotPrefab = Resources.Load<GameObject>("Entities/Player/FeatherShot/FeatherShot");
emberCost = 0.5f;
}
public override void Start()
{
base.Start();
pen.animator.SetTrigger("shoot");
pen.SpendEmber(emberCost);
// INSTANTIATION
GameObject featherShot = GameObject.Instantiate(featherShotPrefab, pen.transform.position, Quaternion.identity, pen.transform.parent);
Movement2D featherMovement = featherShot.GetComponent<Movement2D>();
featherMovement.velocity = new Vector3(FeatherShotController.baseSpeed * pen.facing, 0, 0);
}
** Start() of the parent of the parent class of FeatherShot (the prefab who's Start() is seemingly not running)**
The child classes all have a base.Start() on their own Start().
public virtual void Start()
{
attachedHook = null;
//VVV^BREAKPOINT HERE DOES NOT RUN WHEN FEATHERSHOT IS INSTANTIATED!! VVV
Transform hurtboxTransform = transform.Find("Collision/Hurtbox");
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [More irrelevant code here that is never being run]
//This variable is not being initialized on FeatherShot
immunityTimers = new List<(Timer, Immunity)>();
stuckTo = false;
}
prefab is enabled by default
Breakpoint in the very first line of Start() is never being triggered for this object
I understand that's how it's meant to work but clearly I'm doing something wrong 🤣
Wait, actually, might have spotted it
are you calling Start anywhere?
who calls start? this is no monobehaviour
if the parent class is not a MonoBehaviour, you need to call it, Start, manually . . .
yes, another class is calling start, otherwise the object would not have been instantiated in the first place :P
regardless it seems I've spotted the issue, and the breakpoint was working after all
I'll pick it up from there, thanks!!
show us where. instantiation is separate from a method being called on the instantiated object . . .
i think you should share the code on featherShot(?) indeed, you say the NRE happens in that script not the instantiate script
The issue was completely different from what I though; Start is running after all, it's just seemingly stopping the method in a GetComponentsInChildren halfway through the full Start() method. I'll dig a lil deeper into it before bugging you guys again :)
maybe the getcomponentsinchildren throws exception cause the start method is not "fully" executed
The GetComponentsInChildren is within the Start that's not fully executing, so anything it needs to run is already initialized by then
Is there a way for me to see exceptions being thrown by a specific line while step-by-step debugging? My log is being flooded by the aforementioned NRE
public virtual void Start()
{
attachedHook = null;
Transform hurtboxTransform = transform.Find("Collision/Hurtbox");
if (hurtboxTransform != null)
{
hurtbox = hurtboxTransform.GetComponent<Rigidbody2D>();
}
else
{
hurtbox = null;
}
boundsExtents = Vector3.zero;
boundsOffset = Vector3.zero;
Collider2D[] colliders = hurtboxTransform.GetComponentsInChildren<Collider2D>();
// STOPPING HERE
if (colliders.Length > 0)
{
Bounds bounds = new Bounds();
bounds.center = (Vector3)colliders[0].offset + transform.position;
bounds.Encapsulate(colliders[0].bounds);
for (int i = 1; i < colliders.Length; i++)
{
bounds.Encapsulate(colliders[i].bounds);
}
boundsExtents = bounds.extents;
boundsOffset = bounds.center - transform.position;
}
immunities = new List<Immunity>();
immunityTimers = new List<(Timer, Immunity)>();
stuckTo = false;
}
i remember there is a error pause button on console, turn on it
the hurtboxtf maybe null and you call a getXXX method on it
is hurtBoxTransform assigned?
he uses find to find that tf
if it's null, hurtbox will not be asigned and execution continues and tries to access it on the line before it stops . . .
when ever you get an NRE, look at the all the reference variables on the line and check they have a value (are assigned) . . .
yeah but there's no edge case for when it's not found bc they still try to access it later . . .
also, if you're dragging it from the inspector, when you attempt to find it in code it will overwrite the value . . .
I'm using all the finds to avoid drag and drop
I just forgot that some objects will not have hurtboxes, such as this projectile, and needed to add additional checks for that
If you can drag and drop, you should drag and drop. Find is slow, and you can't get any faster than free
i'd do the opposite. Find methods are slow while drag n' drop is the most performant since it involves no coding . . .
try to not use find, drag and drop can guarantee the component is assigned
I see, I see. I'll get to refactoring that, since there's few objects to change, then
you can have a check to assign a value if it is null (meaning it wasn't assigned a value from the inspector . . .
btw it will throw an unassigned exception if you have not assign it
Hi everyone, I'm trying to give a smooth movement to a drawer, could you give me a tip?
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.
try saving the file as C# so there is syntax highlighting. helps to read the code . . .
not a problem, just helps to see what is going on easier . . .
yes , ty
Lerp is used incorrectly. when using Lerp is good to use a duration. to animate linearly. you can also use MoveTowards, i think they have a Vector3 option . . .
should I use a target in the " endPosition " position?
the end position is your destination . . .
the third value for Lerp, *t*, should be animated from 0-1, typically, determined by the elapsedTime/duration. elapsedTime is added to every frame . . .
also, the yield is outside of the while so the Lerp is moot
yep, and the !open doesn't Lerp at all, it just sets the position . . .
and it's an infinite loop
basically everything was wrong lol
yes
And there is a bit too much whitespace
Sorry, just teasing.
but it's a work in progres, so . . .
i wanted to speak on the whitespace but declined myself . . .
the white space is due to the fact that I deleted a lot of things and quickly copied and pasted them into pastebin, it's still a work in progress ahah
Hey, he can have as much whitespace as he wants, it will neither generate a compile nor runtime error
That is the least of his worries
I'm simply learning programming, peace and love haha
what do you have now, so far?
you and me both, thats why I use a big portrait monitor for coding
I was just teasin, no need to worry about that at all, like steve said
I'm almost done with my project, I'm missing the last few things, it's not a triple A obviously, but I'm satisfied with my work
see, i did that, but turned it back bc i end up watching a bunch of stuff on it. it's hard to dedicate the entire monitor just for that — then again, sadly, it's not my day job (which would make more sense, or maybe i'm not decicated enough 😔) . . .
hey, better than most of us sticklers . . .
I run 6 monitors, dedicating 1 to coding is not a problem
jeezus! i have no excuse though, since i have 3 myself. are you using 1 for each asset you work on, haha . . .
lol let's say that programming has kept me out of trouble, I live in a dangerous suburb, so programming has been my salvation, I didn't have a good childhood, I'm making up for it
omg , i love it
making the best of it, good thinking . . .
exactly and since I don't even have a house and I'm supported by someone, I use my free time to learn programming
From left to right
Windows Operating System
Unity game View
Visual Studio
Unity Editor
Web browser
MacOS VM
oh, that's like a dedicated unity layout, nice!
Works for me
i think 3 across: landscape, landscape, portrait, with a 4th above the middle would work perfect for me. i'd need a different monitor arm though . . .
tbh I tried multiple vertical monitors, didn't like it, neck strain, horizontal works better imo
plus the mouse movement is really weird using multiple verticals
especially, if you sit close to the desk . . .
When i create a variable that has a type of "System.Action", the compiler tells me to convert that into a local function like this:
public void Method()
{
System.Action variable = () => cute();
// After i listen to the compiler:
void variable()
{
cute();
}
}
Which one is more efficient way for Garbage and performance
What should I do to execute Multiple gameObjects Component's function which have same name?
Like BroadcastMessage() but can use outer Gameobject and its child.
yep I could just grab them to large List<> but I dont want em
I would just make explicitly make a list once and then use that list every time i need to call the methods
So, you want to call a specific function on a collection of things that all have that function?
i'd use an event/delegate . . .
I want to call a function which has the same "name" inside all GameObject's Components
like
// in GameObject A
{
I_call_every_func_which_has_same_name("Print", gameObject.name)
}
// in GameObject B
void Print(string gname)
{
debug.Log("Print Requested by " + gname)
}
Event
Hi
i have a problem with the Enemy in the game
When the Player kill the Enemy the console shows a error
THe error 👇
Your script should either check if it is null or you should not destroy the object.```
Something is still referencing the object that is destroyed
so What's the solution ?
ok and what should i do
Stop trying to reference an object that is destroyed
This is really all that can be answered with no context
Somewhere you're referencing something that no longer exists, stop doing that
i know but ..
its the Ennemy Spawner
Okay, so your enemy spawner should probably not hang on to references of destroyed enemies
how ?
¯_(ツ)_/¯
I have no idea what your system looks like
I don't know what reference is being destroyed
i will show u
if u see the code can u tell me the solution ? ^_^
It'd be easier to find a code problem if you posted the code yes
evening friends. i've got a transform in here on an enemy spawner but the transform doesnt update, despite the object that was dragged into the field having moved (its always to the right, relative to the player). is there some way i can force update the transform
That will reference the specific transforms of the objects you drag in. If those objects move, their new values will be reflected in their transform that you are currently referencing
using System.Collections.Generic;
using UnityEngine;
public class SpownSystem : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject Enemy;
int randomSpawnPoint;
void Start()
{
InvokeRepeating("SpawnEnemy", 0, 1.5f);
}
void SpawnEnemy()
{
randomSpawnPoint = Random.Range(0, spawnPoints.Length);
Instantiate(Enemy, spawnPoints[randomSpawnPoint].position, Quaternion.identity);
}
}
Is Enemy a prefab or an object in the scene
first i try to make the enemy a prefab but the error is keeps appearing
now its not prefab
but nothing changes
So when that specific enemy is destroyed what are you attempting to clone
the enemy itself
But it's destroyed
the spawner cant make more clone
show the code that is doing the Destroy
i know
So why are you spawning an object that can be destroyed, instead of a prefab
so i need to make the enemy a prefab??
Yes
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
Instantiate(Explosion, transform.position, Quaternion.identity);
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
}```
what keeps appearing
This error
Your script should either check if it is null or you should not destroy the object.```
I understand that bit, so the object thats dragged in is a "platform spawn checker", essentially its a dummy object with no function bar a script so it always stays on the right side of the player at a specific distance, however when the wavespawner script instantiates enemies, it doesnt instantiate them at the current position of the "platform spawn checker"
Show code
Did you actually use the prefab or did you just make Enemy into one
seee
the enemy is prefab
You have to drag in the prefab into the spawner's variable
yes?
Show the inspector for the enemy spawner
the spawnPoints is the enemySpawner
Okay, so, Enemy is a prefab. That means the error can't be coming from Enemy being destroyed
?
The error isn't coming from Enemy being destroyed. It's somewhere else.
from where
but the error apears when the enemy got destroyed
show the COMPLETE error
ok
Then it's possible a different thing is referencing the destroyed enemy
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <6c9b376c3fca40b787e8c1a2133bf243>:0)
SpownSystem.SpawnEnemy () (at Assets/SpownSystem.cs:19)
still the same error . . .
how?
https://hastebin.com/share/vijenevowo.csharp here you go 🙂
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Which line is line 19
doesnt this mean they referenced a destroyed object they added in the inspector and trying to spawn it
Yes, but I've been assured it's referencing a prefab and not a scene object
where is 19 theris only 6 lines
I wonder if it is a spawnPoimt which has been destoyed
Then you haven't saved
Because the line numbers don't lie
so should i delet the enemy from the inspector
??
ah ok so they showed it was a preab from project folder?
They've shown they have a prefab and have said that's what they dragged in, so ¯_(ツ)_/¯
19 from error or code ???@polar acorn
From the script
SpownSystem prob
Right after spawning the enemy, put this line, then show what the logs say:
Debug.Log($"Spawning an enemy at the position of {spawnLocation[spawnIndex]}, which is {spawnLocation[spawnIndex].position}. Enemy is at {enemy.location}",spawnLocation[spawnIndex]);
So, it's possible that an element of spawnPoints was destroyed. Are any of them ever destroyed?
But let's first make sure. Can you show a screenshot of the thing you dragged into the Enemy variable on this script
What was the thing you clicked on and dragged into the slot
Hello, in this following code:
void OnTriggerEnter2D(Collider2D collision)
{
if (isAttacking || isAttacked)
{
if (collision.CompareTag("Enemy"))
{
damage = 10f;
enemyHealth = collision.GetComponent<EnemyHealth>();
enemyHealth.DamageEnemy(damage);
if (enemyHealth.enemyHealth <= 0f)
{
Animator enemyAnimator = collision.gameObject.GetComponentInChildren<Animator>();
enemyAnimator.SetBool("Die", true);
//wait
Destroy(collision.gameObject);
killedEnemies += 1;
}
}
}
}
I want to add something to the //wait section that will make it wait for 1.5f seconds. How can I do this? The reason I want this is to wait for the death animation to end instead of destroying the gameobject instantly.
Destroy takes in a delay parameter
You need to make this a coroutine then you can do that
You can just have the destroy happen after some amount of time
use animation event
see
Or these ^
oh float t?
Yes
oh tyvm
Right after spawning the enemy put this
Why does it tell me to remove it when I get to this line? it was doing this a while ago, I don't understand why...
@polar acorn
in what
When I deleted it and did ctrl z it was fixed. bruh...
intellicode having a brain fart
Which thing did you drag into the Enemy slot on the spawner
bruh. So all I have to do is ctrl z?
i dont understand exaxtly
How did you set Enemy on the enemy spawner
Escape?
just ignore it what its telling you ..sometimes it doesnt know wat you want to do. You probably have Destroy() without second paramater so it got confused
i drag it simply
It didn't work. But anyway, it's fixed now.
What did you drag in
What thing did you click your mouse on and then move to the slot
the left click
he says this is a prefab or gameobject or transfrom or what?
Show me the thing that you dragged in
I'm not going to ask again
what thing
did you click on
to drag
into the slot
before you answer, there are 2 enemies on the screenshot you sent
can i send a vedeo
He asks what you put there. 1 or 2?
oof
it's a gameobject
I asked you multiple times if you dragged in the prefab or the enemy in the scene
and every time
you said the prefab
bruh
yeah as soon as you hit play Prefab turns into GameObject
i didnt know thers defrent
the one in the Project folder is the blueprint you need
One is an asset you can reuse easily, the other is an single instance of an object
If you put a gameobject in that slot, you will get an error when that gameobject is destroyed or disabled.
thanx for this ('
bruuuuuuuuuuuh
guys i redownloaded VS but my scripts arent working ?
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
thx
tthx for the solution@rich adder@chrome scarab@summer stump@polar acorn
u re velcome
@polar acorn
im SO VERY EXTREMELY SORRYfor my stupidity
I had the same problem with someone else, I think it was the same person XD
Which children does this get the tilemap component from?
tilemap = grid.GetComponentInChildren<Tilemap>();
I want it to get this tilemap from "Zemin".
assuming that grid and its other children don't have Tilemap component too
Of course, others also have tilemap, I wouldn't ask if they didn't have it xd
otherwise you have to Find or FindGameObjectWithTag
foreach (Tilemap tilemap1 in grid.GetComponentsInChildren<Tilemap>())
{
if (tilemap1.name == "Zemin")
{
tilemap = grid.GetComponentInChildren<Tilemap>();
}
}
This was the first solution that came to my mind. but I didn't test it.
of course? then it's gonna get tilemap from Duvar
So it takes from the first object. I understand.
why dont u just put fields in the inspector?
GetComponentInChildren find the First component
So does this work? Or is it a bad solution?
what is this point of doing this..
grid.GetComponentsInChildren<Tilemap>().First(w => w.name == "Zemin");
just un-necessary calls to GetComponent tbh
it won't work
you assing tilemap to new GetComponentInChildren
you have to assign it to tilemap1 to make it work
tilemap1 is the var for the loop
you cant change it during a foreach loop
like that?
that is local variable in the foreach loop . . .
why are you doing this instead of just using a field 🤔
what do you mean?
foreach (Tilemap tilemap1 in grid.GetComponentsInChildren<Tilemap>())
{
if (tilemap1.name == "Zemin")
{
tilemap = tilemap1;
}
}
how so?
they mean you can serialize it and assign it in the inspector
nah thought you meant changing tilemap1
it's impossible.
I know I said that
The reason I do this is because I need to select a tilemap in another script. and I need to select gameobject to select the tilemap. And when I select gameobject, I cannot apply to prefab.
but "assign it to tilemap1" means that you have to set smth to be equal to tilemap1, no?
you could just pass it when you spawn the prefab
idk I got confused by the wording
you have to assign it to tilemap1
no biggie 🤷
Will it not give an error when I move from one scene to another in the game and come back to this scene?
I think my English sentence structure still wishes the best
the reference gets losts between scenes unless you persist them, otherwise why would the same object be in the scene? they also get destroyed
I'm tryna recreate the circle illusion where the dots move in a straight line but it looks like a circle rolling. I've got it mostly down but I have an issue with how my dots are placed about; they make gaps instead of being evenly spread in a circle looking way:
using System.Collections.Generic;
using UnityEngine;
public class DotsManager : MonoBehaviour
{
public GameObject dotPrefab;
public List<GameObject> dots = new List<GameObject>();
public int dotAmount;
public float dotSpeed;
public bool showLines;
float angle;
float turningAngle;
void Start()
{
turningAngle = 0;
dotAmount = dots.Count;
}
void FixedUpdate()
{
angle = 0;
turningAngle += dotSpeed;
for(int i = 0; i < dotAmount; i++)
{
dots[i].transform.position = new Vector2((Mathf.Cos(angle) * 3f) * (Mathf.Cos(turningAngle + angle)), (Mathf.Sin(angle) * 3f) * (Mathf.Cos(turningAngle + angle)));
angle += (180 / dotAmount);
print(angle);
}
}
}
If it helps, I have a scratch project that does this that I'm using as referenece https://scratch.mit.edu/projects/809102399/editor/
Can anyone figure out what I have done wrong
question, so im making an editor and implementing an undo redo function, how do i get the prefab used to create the object before it is deleted, so it can be undone?
look into command pattern probably
RecordObject
thx ill have a look,
Is there an easy way to find places where changes have been made? I've been browsing the inspector panel for 5 minutes...
git status
if you press on override in the inspector it will show you where u got changes
Overrides* tab when u click prefab in the inspector
where is the difference i dont understand xd
enemy list is the same too
When you click the apply drop-down should show a list
Yeah some stuff does appear each time, i just memorize what is there, i usually get network object as the "change" i think its because it gets active or something im not completely sure why honestly
yeah he is doing that but if u click on each of those stuff on list u get the differences
oh i get change for a reason though so forget it, never really checked on that haha
Okay, I noticed it when I clicked on Human Transform. Somehow it has changed from prefab to gameobject...
probably u got private values changed or other things inside of ur script
if its in runtime its gameobject
but also if ur Human Transform is inside of the prefab, it doesnt make it the prefab
now ur Human is a prefab though so forget this but if ur human has a gun within his hierarchy, the gun is not necessarily a prefab, and if u run the game its all gameobjects
Hey i need some help iam setting the color of a line renderer to a new Color(5,5,5,255) but it comes out different so the color is then like 200,200,200, 57 or smth why is that
show us code
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
use Color32
there is a list with colors and the tower laser (linerenderer) should first be the color of the list[0]
theres a method to convert it directly
just use Color32
no need to figure out the math urself
alr thanks
i have reloaded a scene and all things got deleted how can i redo this
Do you have your old scene file
I'd like to double check that you know what they do and why the exist before proceeding.
i did not see it in temp folder
Then you've overwritten it. If you don't have backups or version control, it's probably gone
You want to make sure that you're not in play mode when making changes to anything in Unity.
The behaviour is super finicky depending on the type of asset you're changing, but general rule is that you don't modify while in play-mode
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;
public class TextMaterialChange : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[SerializeField] private Material hoverMaterial;
[SerializeField] private Material originalMaterial;
private TextMeshProUGUI textMeshPro;
// Start is called before the first frame update
void Start()
{
textMeshPro = GetComponent<TextMeshProUGUI>();
originalMaterial = textMeshPro.fontMaterial;
}
// Update is called once per frame
void Update()
{
}
public void OnPointerEnter(PointerEventData eventData)
{
textMeshPro.fontMaterial = hoverMaterial;
}
public void OnPointerExit(PointerEventData eventData)
{
textMeshPro.fontMaterial = originalMaterial;
}
}
``` this script is supposed to change to glow material when pointer enters. It was working yesterday but now my text just disappears when I hover over. I get no errors.
I assigned the materials in the inspector
When your pointer exits the target, does it return?
yes it does
Have you tried a different material for the problematic one?
Does anyone know why my input could be delayed in low frame rates? Is there a common fix for this like multiplying by Time.DeltaTime?
Are you reading input in FixedUpdate?
I created another glow material if thats what you are asking
Did you put it in fixed update?
If you manually set the material to the one you're using for the hover material, is it visible, even without the script running at all?
If i manually put it on the text it disappears
Your code looks fine at a glance. You're simply assigning different materials in pointer enter and exit.
Then the code isn't the problem, the material is
The material is invisible for whatever reason
This is the material.
Might want to ask it in a specialized channel
#💻┃unity-talk if you're not sure else one of the graphics channels.

hi there, dumb question, if I have a normalized vector3 and I want a world position from another object 2 units say in the opposite direction to that vector, what should I do?
pos here x >> obj >> vector ----->
I worded my original question wrong, it does register input correctly but registers very late when you let go of it. I'm checking whether someone is holding down the left mouse button
And it is in FixedUpdate
A normalized vector isn't a position but a direction. I might not have understood it all but you'd multiply a scalar with the direction and add it to the position to move in that direction.
So, you have an object, and a direction, and you want the point that is 2 units away in the opposite direction from that?
yea
position + (direction * -2)
hi, how to make drop down folder like this by script ?
That's how lists and other collections are displayed in the editor
If you want a foldout without a list you'll need a custom inspector
custom inspector ? but i can't just do as unity does ?
You can. With a custom inspector.
ok tell me how
I'm not sure this is the right channel but, when creating a game for pc, unity recommends using a 10.8 size camera importing sprites at 100 ppu for example. Does this mean my tileset should be 100x100 then? Or do games usually mix ppu's. Thanks in advance
I forgot, so what is the code to generate a gameObject into a tagged object?
huh? what does that even mean?
how do i generate a game object inside an empty game object? (tagged empty game object)
Instantiate takes a parent parameter
Is that what you mean?
pretty sure
Yeah just look at the instantiate docs for the syntax
im meaning on putting it inside a tagged object
likke i need the script to find that
Every object with that tag?
yea
What do you mean inside a tagged object
Like, at the same position?
generate a game object as a parent of the tagged object
same position
Generate as a parent or as a child
so how do i generate it inside every object with a tag ("obstacle")?
dis
ik
It would be a child then not parent
So, for each object with a tag, you want to spawn an instance of something as a child of that object
and then
obstacles = FindGameObjectsWithTags("obstacle");?
yeah
i meant the gameobject being a child of the tagged object
So, loop through a list of all objects with a tag, then spawn your object using the Instantiate overload that takes in a parent
GameObject[] obstacles;
obstacles = FindGameObjectsWithTag("obstacle");
But I am not very good at instantiating yet
Its just a function theres no skill barrier lol
Input system is set to use both, but after I updated the package, I can't use old input system methods like GetButtonDown() how do I fix this?
Do you get an error
Yes
What is it
Get button doesn't exist in input
Show code, show error
if (Input.GetButtonDown("Shift")
Input does not contain a definition for GetButtonDown
You have a class named Input
or just a variable
No
Also side problem, the unity stuff doesn't show in vscode autofill and some of the csproj files show up as not supported by c# dev kit, it's no biggie but it is bothersome
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Do you get the error in unity or just in the IDE
Seront in just unity
Show a screenshot of the error
Also ide was fine a month ago when I last used it, idk y it stoped working right
That was the error the one I gave
Show a screenshot of it anyway
I renamed PlayersController to SplayerController now it's gone and working
IDK why coding is so random like this
How does renaming a file fix this issue? There completely unrelated
The error came from a complete other script
Then it seems you didn't save your script
Renaming something recompiled it
It was saved I opened the project 2 min ago and changed nothing
All I did was rename this unrelated script and it works
Whatever if it works it works
But anyone know why vs code doesn't like the csproj files? It just bothers me the 33 by the red x on the bottom, also it would be nice for the autofill to work with unity methods, and yes I have the unity and c#dev kit extensions and vs code package on unity end
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I have it set up exactly like this for vs code already and I double checked
ok all I did was update visual studio package and it made visual studio code work
apparently the visual studio code packahe is obsolete or something
are there any alternatives to mlagents
um so my scene has merge conflicts that im not seeing on github desktop, do i have to use git to fix the merge?
Hi. I'm trying out raycast and have managed to get it to work and to detect tags. I'm trying to make it so text pops up on screen. For example, if you're looking at a picture then the text "This is a picture" will pop up on screen.
Ive got ui manager singleton controlling ui state on screen if u do that u just make public method there enabling ur text canvas and setting text element values in it then run it where u want
If you had read the instructions Digi linked to you, you'd have known that already.
Guys what do I do if my camera is in the void basically and I cant get back up to the platform im working on
nvm I fixed tit
setting its position directly in the inspector can help
if you've flung it out to a wild position
use custom tags by a script, then reference that script to the raycast to detect and display the proper text needed, i dont really use the built in unity tags because it gets clunky when you have many tags
This is what I have managed to do. Only problem is if i walk backwards while I was looking at the picture. the text doesnt go away unless i go back to it and look away while i'm next to the picture
you havent made a condition that if its out of range, the text will be disabled
its better to have a guard clause at the very start that only executes the rest of the code if the raycast has hit something, if not just return
Could you explain what that is please?
which means that if you walk backwards, there is no condition to check if you have walked backwards or specifically, to check if the raycast hit nothing
Right, Gotcha. I'll save that for the morning. I appreciate the reply
Post the error
i am just trying to call a function from another script
here
Look at the example.. yours is missing something https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
That's the name of the object, not the component.
Is the component called auth manager as well?
they are all called AuthManager
i followed tutorials on yt but theirs work and mine doesnt
That's not how you call a method
I think what you are doing with transform.TransformDirection(direction * range) is incorrect, because you are giving it a vector scaled by range, then also later using range in the raycast parameter. You could just replace
transform.TransformDirection(direction * range)
with transform.forward.
yo wut does dis mean
everytime i try to make a project
it doesn't work
and i get this message
Not a coding question, try asking in #💻┃unity-talk

both is set to if (task.IsFaulted) but one works and one doesnt
when the sign up is faulted, logText.text changes but when the sign in is faulted, logText.text doesnt change, even though they are the same script
when the first one is faulted, only debug.log(signin failed) works, the code logText.text = "password is incorrect" underneath doesnt work
Major difference between the two
ContinueWith vs ContinueWithOnMainThread
You can't touch Unity objects from a background thread
oh
wait lemme change
the first one to ContinueWithOnMainThread?
mb because i was copying this code online so i didnt notice
you can get TMP_Text component with GameObject.GetComponent<TMP_Text>(), right?
i have, everywhere says it works and i get null
show the relevant code, the error + stack trace, and the object you are calling GetComponent on
so if line 21 is throwing the NRE then the issue isn't the GetComponent call. it's that your GameObject.Find call is returning null
which means either that object does not exist in the scene at the time this code runs, it has a different name, or it is not active
yep, GameObject.Find does not find inactive objects
https://docs.unity3d.com/ScriptReference/GameObject.Find.html
This function only returns active GameObjects.
you'll want to get a reference a different way if you want to refer to an inactive object
https://unity.huh.how/programming/references
No reaction images thanks, just use words/emoji, keeps the chat cleaner
understandable
I've been scraping my head with this one for ages. all I want is the text on the screen to go away as soon as I'm not looking at one of the objects. If I'm close to the object, it does disappear but if I'm on the edge of the raycast beam, it'll stay on my screen until I look at something else.
If (raycast) returns true only if you hit something. False only when you don't (not including using layermasks)
you need an else for the raycast if statement
Also, best to use CompareTag instead of equality to check for tags
Also, I would do
if (picture)
Else if (chair)
Else if (table)
Else
Instead of the else after each if statement
Or a switch with a default for when you add more things
or better yet just using the name or some string from a component directly rather than handling it all here.
If we're gonna go all the way on suggestions, I would make the raycasting script perform no logic, and have it handled by a component on the objects through an interface
but it's complicated for beginners, so simple is fine
Agreed. Didn't want to stray too far, but yes
That was what I wanted to do then confused myself out. I used a long cube with no mesh before so I'm new to raycasting
So what exactly is my problem here? I would of thought the else then the SetActive(false) would automatically disable the text when not looking at it
I probably sound stupid but I want to understand and not just nod my head not knowing whats going on.
You need an addition else AFTER the raycast if
If (raycast)
All that stuff
Else
Set false
Because you can only get to your current code setting it false when the raycast SUCCEEDS against something that isn't those three things.
You also want it to set false when it fails (not pointing at anything)
The last part is what I have tried finding online for awhile. I found a few things but none seem to of worked
Hi everyone, the code itself isn't that difficult, so I'm writing it here. How do I get GPGS services to work on iOS as well? iOS doesn't use Google Play Store, so I don't know how to develop it
Just to be clear, I meant something like this. This is trying to keep it as close to how you have it as possible. Definitley not the best way. I would have the object have an interface like Vertx said and turn its OWN text on, but this is along the lines of how you have it, but what you need to fix it
if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
if (hit.collider.CompareTag("Picture")
{
picturetext.SetActive(true);
}
else
{
picturetext.SetActive(false);
}
if (hit.collider.CompareTag("Chair")
{
chairtext.SetActive(true);
}
else
{
chairtext.SetActive(false);
}
if (hit.collider.CompareTag("Table")
{
tabletext.SetActive(true);
}
else
{
tabletext.SetActive(false);
}
}
else
{
picturetext.SetActive(false);
chairtext.SetActive(false);
tabletext.SetActive(false);
}
Trying that now.(Just trying to fix errors about the compare tag) I also tried the last bit with the false' earlier.
You did the false's OUTSIDE the if of the raycast already?
That should have worked. hmmm
i only had 3 false' like yours at the bottom. you have them in the if too
They are not in the if
to show it clearly:
if (Physics.Raycast(theRay, out RaycastHit hit, range))
{
// all the checks
}
else
{
picturetext.SetActive(false);
chairtext.SetActive(false);
tabletext.SetActive(false);
}
the top if closes
sorry. I've been at this since midnight. It's almost 7 am
Can u tell me the problem once again??
Well, right now. I'm trying to figure this out. But the original one is Raycast. I have it so when you look at an item, text appears on screen for what the item is etc. while looking at the item, if i walk back, the text still stays on my screen unless i look literally up to the sky or go onto another object. (range is 4).
If your IDE is not giving you error highlighting and autocomplete you need to configure it !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
OH CRAP, sorry! My bad
I'm a bit shot too, my code was messed up. I need to go to bed
Hmmmm
Send me gui configuration
Corrected the code I sent
You run CompareTag on the collider, not the tag (of course) headslap
What is "gui configuration"?
The configuration of the layout
@summer stump I WOULD KISS YOU RIGHT NOW. Thank you so much. It works.

I don't understand what that means either. Sorry.
Are you talking about the IDE, the Unity Editor? Why would they send it to you?
When I hear Layout, I think the Unity Editor layout, like this
https://learn.unity.com/tutorial/exploring-the-editor-layout
All good, glad it worked!
I'm going to study that code and compare it to my one. THANK YOU
Oh wait, sorry sorry. I thought this was the roblox studio server
Sorry boys
Regardless of fixing the issue, if you've not got a configured IDE (underling errors and giving autocomplete) you need to set that up!
I'm doing that as we speak. I stopped making game because my pc died so just got a new one and reconfiguring everything. Thanks 🙂
Why my Unityevent can't send arguments well?
Show how you have configured it
wait
private void OnBlockStart(MidiData.MidiBlock block, int idx)
{
Debug.Log("Start Event Send =>" + idx);
NoteStartEvent.Invoke(idx);
}
private void OnBlockEnd(MidiData.MidiBlock block, int idx)
{
Debug.Log("End Event Send =>" + idx);
NoteEndEvent.Invoke(idx);
}
ahhhh indent
public void OnNoteStart(int noteidx)
{
Debug.Log("Note No." + noteidx.ToString() + "Start Received");
changeScale(2);
}
public void OnNoteEnd(int noteidx)
{
Debug.Log("Note No." + noteidx.ToString() + "End Received");
changeScale(1);
}
i want to change the cinemachine body from transposer to do nothing via code how to do that ?
hi every one.
i want to make some identification paper like paper please. i have some problem with that data type and do i need use object to make all of them
What? 
i want make some thing like this but i so confuse about structure
use a regular poco
so i just working with string and make some method to check?
make fields in the class for those sure they could be string
ok i will try.
https://hatebin.com/gkaypcmbgb | Bug in the Video (should move smooth, jiggles around) line 40
any idea
- your last
)is in the wrong place - you do not need to cast to GameObject when using Instantiate. that hasn't been necessary for like 4 years or more
How do I make OnPointerEnter work with Unity Visual Scripting? I have a Script Graph on an Image with that node, but it just doesn't trigger. I don't think it's a raycast issue, since that same graph has an On Mouse Input event that works just fine
...Can't believe I didn't notice that channel before. Thanks for directing me to it
how to begin c# for unity
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
besides the learn site which was linked already, there are some beginner c# courses pinned in this channel
thanks
personally, i recommend learning c# separately from unity then learning how to use it in unity
Could someone explain to me why the if statement (if (currentWaypointIndex >= wayPoints.Length) does not immediately assign currentWayPointIndex to 0 when the maximum number of indexes of the wayPoints array is reached? Don't get me wrong, my code works completely fine, I just wanted to ask as why it is like that?
What do you mean? If the code inside the if statement executes, currentWaypointIndex becomes 0
If you're confused at how it's working you should use the debugger and step over your code to see it execute
You might want to be checking wayPoints.Length - 1
The logic is correct
Genuinely correct me if I'm wrong but would currentWaypointIndex == wayPoints.Length - 1 be more accurate since the check is specific to the actual logic your trying to check?
Right now from that code alone it looks like if it fails the check it's just going to ++currentwaypointindex until the if statement clears since that distance check is going to keep hitting true (unless some outside code is changing stuff)
The problem is that there is no context to explain what they are doing or how they want it to work, but the logic is correct.
if they changed the if statement to if(currentWaypointIndex == wayPoints.Length - 1) then the last index will not be used because when they get to the last index they will immediately go back to 0. their current logic is correct because they want to go back to 0 after passing the last index. which will be when currentWayPointIndex is greater than or equal to the length of the array
Heard
In theory the greater check will never run because the equal check will always reset it before that point, Right?
Correct. Though, I generally perform checks like that too
if I do it that way all the time it saves the load to think about the other options if they're ever in my code
Why is the privot of the tower back there?
This is the coding channel, maybe ask in #💻┃unity-talk
this is a code channel. but also make sure that your tool handle is actually set to pivot and not center
why is there an error
what does the error say?
} expected
then you probably have a missing } somewhere
of course you aren't showing all of the relevant code here so i don't know why you expect anyone to just know that
no i dont have a missing }
show the code then
Maybe show more
share the entire class 👇 !code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
yep, missing a }
Where's your closing curly brace?
For the class.
wdym
you have an opening curly brace for the class. where is the closing one?
that second one you have circled is the closing brace for your Update method
The one you circled is for Update according to indentations.
it's literally the one you have circled here
If you had just trusted the error and added the curly brace you would have saved a lot of time 😂
gameObject.transform.position = new Vector3(x, y, 0);
Why do I get an error from this?
what class is this in?
you've probably got that inside of a static method
It's inside a class I made
Am I unable to referance gameObject inside a class?
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float enemyHealth;
public SpriteAttack killedEnemies;
// Start is called before the first frame update
public void Start()
{
enemyHealth = SetBaseEnemyHealth();
}
// Update is called once per frame
void Update()
{
}
public float SetBaseEnemyHealth()
{
float health1 = 100;
health1 += killedEnemies.killedEnemies;
return health1;
}
Hello, I wrote a code like this, but it gives the following error:
NullReferenceException: Object reference not set to an instance of an object
EnemyHealth.SetBaseEnemyHealth () (at Assets/Scripts/EnemyHealth.cs:22)
EnemyHealth.Start () (at Assets/Scripts/EnemyHealth.cs:11)
I'm sure I selected the sprite attack file in the inspector, and the killedenemies variable was initially set to 0 as follows:
public int killedEnemies = 0;
you can, was wondering if it was a c# class not derived from MonoBehaviour or inside of a static method as boxfriend said . . .
the only object in that class that could be null is the killEnemies variable. where did you assign a reference to a SpriteAttack object?
This is the script
exactly what i thought. it's inside of a regular c# class. it has no idea what gameObject is . . .
So how can I referance the object the script is attached to? do I need to create a variable outside the class?
gameObject is an inherited property from a MonoBehaviour but your class does not derive from MonoBehaviour . . .
Do I need to call it with void start?
what? you need to assign something to that variable
you need to create a GameObject field and assign that field in its constructor . . .
Isn't it enough to set it to 0 anyway? like this: public int killedEnemies = 0;?
that's not the issue
oh I see
the issue is the killedEnemies variable of your EnemyHealth class. it is a SpriteAttack variable and it is null
where do you assign to that variable?
when BodyPart is initialized, the calling script must pass a GameObject to its constructor . . .
Do I need to reassign to killed enemies? bruh. Shouldn't it already be assigned in the other script?
Can I just make a public variable outside the class and attach the gameobject to it in the unity editor?
where have you assigned it at all
It's already written in my code, look, I assigned it to the sprite in the attack, and while writing the variable, I gave it the value 0 at the beginning.
and still you are thinking about the wrong variable because you've decided to give the variable the same name as the one inside the SpriteAttack class.
read this message again carefully #💻┃code-beginner message
There is no other killed enemies variable in my enemyhealth script. I'm trying to get it from the spriteattack script.
look directly to the left of what you have highlighted. that is what is null
it is my script file. I just asked above whether should I assign it with void start
where do you assign anything to that variable
hint: you don't which is exactly what it is null
Hello, someone can explain me why my Tilemap is outlined by orange glow ?
you have gizmos enabled
it's just a gizmo showing the selection outline. it will not show in the actual game
Isn't it enough to assign in the inspector window? Do I need to create getComponent with void start?
assigning in the inspector is enough. provided you do that for every instance of that component
I already did it.
I understand but how to disable it ?
disable gizmos. there's a button toggle in the upper right. but also this is a code channel
Do I need to make the gameobject variable type pass by by refarance? will the changes I do to the gameobject variable in the method change the actual object in the scene if it's passed on by value?
Sorry , thanks
not for every instance you didn't. otherwise it wouldn't be throwing a null reference exception. add this line to Start: Debug.Assert(killedEnemies != null, $"Oh look, the component was not assigned on {name}", gameObject);
If you have a BodyPart instance in a MonoBehaviour class, you can drag a GameObject into its GameObject field, yes, but since it can only be constructed in code, you should have a constructor where you assign the GameObject variable as well . . .
Nothing was written and no warning was received.
put it before the line that was already in Start
I don't understand. Orc clone spawns with random enemy spawn, but why shouldn't it be assigned, I get it from prefab. Isn't it assigned to prefab?
you probably didn't assign the variable on your prefab and only assigned it on the one in the scene
yep. it's isn't assigned to prefab
tysm @slender nymph
Why does the type mismatch occur when I select it?
prefabs cannot reference in scene objects. you need to pass the reference to it when you spawn it
I have no idea why the instantiate isn't working, it just doesn't create anything when the game is running
private void OnCollisionEnter2D(Collision2D collision)
{
placement.CanPlace = false;
}
private void OnCollisionStay2D(Collision2D collision)
{
placement.CanPlace = false;
}
private void OnCollisionExit2D(Collision2D collision)
{
placement.CanPlace = true;
}```
the issue is there is a single frame when switching between 2 collisions that CanPlace becomes true and I need that to not happen
i would personally recommend use physics queries instead of relying on collision messages. you can use something like Physics2D.OverlapCircle (or whatever shape you need)
what steps have you taken to ensure that code is actually being run?
ok so i runned into this little problem with the IK foot. So when i move the model up and down, the leg's target stay down on the ground, but when i move the cube forward the leg's target moves too and is dosen't stay on the ground to move the feet back. I know this i caused by the parenting of the target to the model, but how can i get past this issue without unparenting the targets from the model ?
public class IKMovement : MonoBehaviour
{
public legTip[] legs;
public float heightOffset;
private void Update()
{
foreach (var leg in legs)
{
Ray legRay = new Ray(leg.tip.position + (Vector3.up * heightOffset), Vector3.down);
if(Physics.Raycast(legRay, out RaycastHit hit, Mathf.Infinity))
{
leg.tip.position = hit.point;
}
}
}
}
[System.Serializable] public class legTip
{
public Transform tip;
}```
Im using the old input system. How to check if the player is using keyboard or controller controls?
is there an inverse of vector2.ToString()?
string.ToVector2() thingy something?
or do i have to write it
This code is running, this method is the same method that moves my character, and my character moves
then Instantiate is being called therefore the object is being spawned
you have to write it - but it would be very simple
yea figured i can just splitty thingies
what would you need to convert a string to a Vector2 for anyway? 🤔
public string FromToTarget( Vector2 main, Vector2 target) // used if there's a position in the string
{
string toret = "";
float magni = (main - target).magnitude;
if((int)magni == 0)
toret = "0 C";
else
toret = $"{Mathf.RoundToInt(magni)} {lyx.func.CardinalDirectionWithTwoVector3(main, target)}";
return toret;
}
void OnEnable()
{
string toDisplay = NoteString;
toDisplay.Replace();
noteText.text =
}````
btw, i wanna regex a string with any vector2 strings, how can i feed the matching results to FromToTarget then replace it that
is there a regex that outs something?
Regex.replace dont, does it?
Well it isn't, idk why, no object is spawning
it is. it might be destroyed immediately but if that code is running and you don't see errors in your console then it is being spawned
I don't see how the object is destroyed, nowhere in my game is there a line of code that destroys an object
well like i said, if that code is running and you don't see errors in your console then it is being spawned
add this line directly after it and show what it is printing: Debug.Log($"Instantiate has spawned a clone of {BodyPartPrefab.name} from {name}");
preferably screenshot the entire console window
public string FromToTarget( Vector2 main, Vector2 target) // used if there's a position in the string
{
string toret = "";
float magni = (main - target).magnitude;
if((int)magni == 0)
toret = "0 C";
else
toret = $"{Mathf.RoundToInt(magni)} {lyx.func.CardinalDirectionWithTwoVector3(main, target)}";
return toret;
}
Vector2 StringToVec(string ss) { return Vector2.zero; }
void OnEnable1()
{
string pattern = @"\(\d+[.\d\s]*,\d+[.\d\s]*\)";
string input = NoteString;
string result = Regex.Replace(input, pattern, FromToTarget(MainCharacterController.MainPosition, StringToVec( ""/* regex match */ )));
}``` How can i make this work?
Ok it is instantiating the object, but why can't I see the objects in the viewport?
in the game*
is this 2d?
sorry too much using blender
then either the objects are not being spawned within the camera bounds or they are behind the camera
it has the same transform as the character before it moved, so I don't believe it is hidden anywhere
screenshot the inspector for it
not the prefab, one of the objects actually in the scene
okay so it is at the same exact position as whatever its parent is. now keep in mind that child objects will also move when their parent moves
ohhhhh
Hi i just started today and i ran into a problem . The script i make for the ball doesnt work and it gives me no error
it should look like this but mine doesnt
the second parameter you are passing to Instantiate is a transform. that specifies the parent
have you saved?
is your code exactly the same?
Does the file name match the class name
oh wait wait let me take i step by step so
ah yeah, didn't even catch that
that should be both the file name and the name of the class in the code, yeah
although now that i think about it, if you're on latest LTS that won't really matter
It doesn't matter what you call it as long as the file name matches the class name
this is it by far
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public Rigidbody2D rb2d;
private void Start()
{
rbd2.velocity = Vector2.left;
}
}
yeah the class name is NewBehaviourScript. you'll want to change that to Ball
so i should say public class Ball
yes. just like the tutorial you are follow does
alright thanks a lot, i was a bit confused, this is really my first time having any encounter with coding
Assets\Scripts\Ball.cs(11,9): error CS0103: The name 'rbd2' does not exist in the current context
i got this now 😭
yep, you had that before too 😉
and it still looks like this
If your !ide is not underlining errors and giving you autocomplete you need to configure it
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
I searched the issue on google but i can't seem to find an answer to why i dont have the game development for unity worload
just follow the instructions to install it?
assuming you are using visual studio and not vs code, that is
i just figured it out now, i confused them with eachother
void MoveSnake()
{
if (!(snakeDirection == Vector2.up && snakeY == 4) && !(snakeDirection == Vector2.down && snakeY == -4) && !(snakeDirection == Vector2.right && snakeX == 8) && !(snakeDirection == Vector2.left && snakeX == -8))
{
prevFrameSnakePosition = gameObject.transform.position;
gameObject.transform.position += new Vector3(snakeDirection.x, snakeDirection.y, 0);
}
previousSnakeDirection = snakeDirection;
snakeX = (gameObject.transform.position.x < 0)? gameObject.transform.position.x + 0.5 : gameObject.transform.position.x -0.5;
snakeY = (gameObject.transform.position.y < 0) ? gameObject.transform.position.y + 0.5 : gameObject.transform.position.y - 0.5;
GameObject bodyPart = Instantiate(BodyPartPrefab, prevFrameSnakePosition, new Quaternion(0,0,0,0));
}
How can I save the bodypart variable at the end so that I can access it after the method finishes to do an operation on one of it's public variables every time this method runs? I thought of using arrays but that complicates stuff and means I need a 180 elements long array of gameobjects...
And I want to keep this simple as this is a game of snake
new Quaternion(0,0,0,0) is not a valid quaternion. use Quaternion.identity instead
it works tho
that doesn't make it correct
wdym
whats this
Guessing foreach and modifying the collection
i mean new Quaternion(0,0,0,0) is not a valid quaternion. use Quaternion.identity instead
Yeah I did it can you please help me with the question
but what does it mean, cant I modify a dic?
What was your intention using 0,0,0,0? What orientation did you want to end up at?
you probably want a list of your body parts in the class. then just add to the list when you instantiate one. you're already storing the clone in a local variable, just add that to the list
It's a 2d object and I wanted it to have the default rotation
And 0,0,0,0 isn't that. Quaternion.identity is, which is 0,0,0,1
alr, it didnt actually make any difference though
You cannot modify a collection when you're traversing through it with foreach. Foreach promises that every element will be visited (unless you do an early escape) thus you'll get an error as you're violating the promise (probably more complicated stuff under the hood but that's the gist of it).
got it
so I dont really get what was the point of doing that
so how do I modify it without
creating an exception
and iterating thru all objects of a dic
I mean all keys
Maybe post more of what you're trying to do. Likely you need to take a different approach to this.
Lots of folks are here. I'm on mobile and just doing what I can. Other dudes here are outstanding though.
How to post !code btw
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
foreach(GameObject enemies in enemiesToBeSpawned.Keys)
{
currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
if(currentNumberOfEnemiesToSpawn > 0)
{
int number = enemiesToBeSpawned[enemies];
while(number > 0)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemies;
number -= 1;
currentNumberOfEnemiesToSpawn -= 1;
}
if(number == 0)
{
enemiesToBeSpawned.Remove(enemies);
}
}
}
The quick and dirty solution would be to copy the keys collection and iterate it
Allowing you to modify the actual dictionary
yah that would work if I put them in a list
since they would be the same keys as the objects of the list
var copy = new List<...>(keys);
What's the reason for this code?
if(number == 0)
{
enemiesToBeSpawned.Remove(enemies);
}
yeah that's what is causing the error
Reminder, it's the dirty solution so if performance is a factor you may want to consider a different approach
so this dic is basically the enemies I will spawn in an area so if there is no more enemies that will be spawned
why keep the key
I was thinking that
and it seems like they just remove the object when done spawning them and are doing it for every key in the dictionary. so why not just clear the dictionary after the foreach loop?
So it's a Dictionary<GameObject, int> ?
yes
how do I see my particle system? Like turn it on when colliding with something?
well because when a certain number of enemies are spawned it waits and when I kill them all the others get spawned
so there arent so manny enemies
Hi I have a idea and don’t know how to do it
then instead just add the enemies you want to remove from the dict to a list and loop over that list and remove them from the dict after the foreach loop. your entire issue stems from attempting to remove them during the foreach loop
This error keep on popping up
"MissingComponentException: There is no 'ParticleSystem' attached to the "Bird" game object, but a script is trying to access it.
You probably need to add a ParticleSystem to the game object "Bird". Or your script needs to check if the component is attached before using it.
UnityEngine.ParticleSystem.Play () (at <b6edb49129684880865710f98e97a458>:0)
BirdScript.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/BirdScript.cs:55)
"
did you read the error?
i did
and what conclusion did you come to?
im missing something
is that the best way to do it? will I get optimization issues later?
well it's certainly better than what you are trying to do now
ur "bird" has no particle system in it, click add component and add a particle system
alright thank you!
oh ill try it now
thanks
yes, your "Bird" gameobject does not have a ParticleSystem on it, but a script is trying to access it. You probably need to add a ParticleSystem to the game object "Bird". Or your script needs to check if the component is attached before using it.
either that or you are calling GetComponent on the incorrect object 😉
oh ok thanks 😄
foreach(var enemyToSpawnKeyValue in enemiesToBeSpawned)
{
var enemy = enemyToSpawnKeyValue.Key;
var count = enemyToSpawnKeyValue.Value;
for(int i = 0; i<count;i++)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemy;
}
}
//If I interpreted your code right you always just spawn all of them, so just clear the dictionary.
enemiesToBeSpawned.Clear();
Oh I missed this part
currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
if(currentNumberOfEnemiesToSpawn > 0)
{
well I dont always spawn all of them
You want to only spawn max allRooms[CurrentRoomType].NumberOfEnemiesAtATime enemies?
yes pretty much
Is there a way to remove an element from a list and make all indexes after it shift one place to the left so that it wont leave an empty index number?
I have this exact same script as the tutorial i watch but i get the CS0103 The name 'rbd2' does not exist in the current context But the guy in the tutorial doesnt get it
can u show the rb and the script in the inspector?
you need to drag the rb2d
The guy in the tutorial didn't write "rbd2" like you did
into the inspector
Your code doesn't have rbd2. Check it again . . .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
public Rigidbody2D rb2d;
private void Start()
{
rbd2.velocity = Vector2.left;
}
}
This is my code
or you can add rb2d=GetComponent<Rigidbody>() in the start
rbd2.velocity = Vector2.left; its not rbd2
its rb2d
ur have an error
Read how you spelled the variable . . .
rb2d.velocity = Vector2.left; @fading slate change it to this
This is kind of messy, because dictionary doesn't have remove if. Should mostly work though.
var currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
var toRemove = new List<GameObject>();
foreach(var enemyToSpawnKeyValue in enemiesToBeSpawned)
{
var enemy = enemyToSpawnKeyValue.Key;
var enemyCount = enemyToSpawnKeyValue.Value;
var count = Mathf.Min(enemyCount, currentNumberOfEnemiesToSpawn);
currentNumberOfEnemiesToSpawn -= count;
var enemiesLeft = enemyCount-count;
enemyToSpawnKeyValue[enemy] = enemiesLeft;
if(enemiesLeft == 0) toRemove.Add(enemy);
for(int i = 0; i<count;i++)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemy;
}
}
foreach(var enemyToRemove in toRemove)
{
enemiesToBeSpawned.Remove(enemyToRemove);
}
paste it there
Also, configure your !ide to fix these simple errors . . .
Oh yeah... I saw it sorry guyz
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i have it configured
thank you so much, I'll use this to guide myself into remaking it
thanks a lot and sorry 😦
no worries we all make mistakes
now 0 errors good
That's what happens when you normally remove an element with Remove . . .
there should have been an error there, have you got ur intelisense working?
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 131
Number of times it was exactly like the tutorial: 4
Number of times the code literally did not exist: 1
2022-07-19 to 2023-09-16
Yes idk, i mean i just downloaded everything today and configured it so i think it should be working, i am a bit confused
why this funny af
cause it is
if you type your rigidbody name and then add . does it show some stuff?
😭 😭 So it will be a long journey
I remember when I started copying tutorials slowly and always having errors lmao
The reason for this mess is that you can't edit a collection while iterating over it. If you used a list like this
public class EnemySpawnInfo
{
public GameObject Enemy;
public int countLeft;
}
And then a list like this List<EnemySpawnInfo> enemySpawnInfo;
You could just iterate over it backwards and remove elements as you go Like this.
for(int i = enemySpawnInfo.Count-1;i>=0;i--)
{
var enemyInfo = enemySpawnInfo[i];
var count = Mathf.Min(enemyInfo.Count, currentNumberOfEnemiesToSpawn);
currentNumberOfEnemiesToSpawn -= count;
enemyInfo.Count -= count;
if(enemyInfo.Count == 0) enemySpawnInfo.RemoveAt(i);
for(int o = 0; o<count;o++)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemyInfo.Enemy;
}
}
some could say its a cannon event
Which would simplify things
yup
got it thank you so much
Just ecountered a Wasn't exactly like the tutorial again rn 😦
I assign ball to Rb 2d and when i run it the ball simply dissapears and it shows none like i didnt drag it there
and now it randomly works
nvm
I'm trying to change the color of a UI image from a button script, but I can't get a reference to it
"Image" isn't a class apparently
neither is button
Vector2 roomPos = rooms.RoomPos.position;
List<GameObject> EnemiesToBeDeleted = new List<GameObject>();
if(enemiesToBeSpawned.Count > 0)
{
foreach(GameObject enemies in enemiesToBeSpawned.Keys)
{
currentNumberOfEnemiesToSpawn = allRooms[CurrentRoomType].NumberOfEnemiesAtATime;
if(currentNumberOfEnemiesToSpawn > 0)
{
int number = enemiesToBeSpawned[enemies];
while(number > 0)
{
GameObject colliderCheck = Instantiate(Spawner, roomPos + new Vector2(Random.Range(-rooms.Point.x, rooms.Point.x), Random.Range(-rooms.Point.y, rooms.Point.y)), Quaternion.identity);
ColliderCheck colliderStats = colliderCheck.GetComponent<ColliderCheck>();
colliderStats.enemyType = enemies.GetComponent<EnemyHealth>().EnemyType + 1;
colliderStats.enemy = enemies;
number -= 1;
currentNumberOfEnemiesToSpawn -= 1;
}
if(number == 0)
{
EnemiesToBeDeleted.Add(enemies);
}
}
}
foreach(GameObject enemies in EnemiesToBeDeleted)
{
enemiesToBeSpawned.Remove(enemies);
}
@signal coral will this work?
I almost didnt have to change anything
instead of removing the enemies Im adding them into the list
and then after that foreach it starts deleting them
there is one case where this code works kind of wrong:
if allRooms[CurrentRoomType].NumberOfEnemiesAtATime is for example 2
and int number = enemiesToBeSpawned[enemies]; is 4
it will spawn 4 enemies. Even though I think you want to spawn just 2
That's why I did:
var count = Mathf.Min(enemyInfo.Count, currentNumberOfEnemiesToSpawn);
why would that happen
you only check if currentNumberOfEnemiesToSpawn is bigger than 0
would that cause any trouble?
If it's bigger than zero, but smaller than " int number = enemiesToBeSpawned[enemies];" it will spawn more enemies than intended.
Unity tells me it cant find instance of an object in ListItems() line 31
https://hatebin.com/wehhffnipf
this script is what the first references, cards get added to the list when bought in the buy script
https://hatebin.com/ehhqqjcpjf
You should go through that code and try to understand the difference between the code I wrote and the code you wrote.
obj.transform.Find("cardImage") is clearly returning null then
The InventoryCard does not have a child object named cardImage
what if my while statement
now is like this
Yeah that's one way to do it
okay thank you
i know but i dont know how to fix it
although there is one more problem if you do it like that. when you do "int number = enemiesToBeSpawned[enemies];" It makes a copy
make sure such an object actually exists in the prefab
at the end of your while loop you need to reassign it into the dictionary
like enemiesToBeSpawned[enemies] = number;
currently if i have a card it detects its there and generates a blank card image not the one inside the card from the inventory list
should I call it directly?
so it just doesnt grab the sprite for it
i don't knmow what that means but this error is straightforward
That's okay, but a bit slow. Should be fine in your case though
the InventoryCard prefab you assigned does NOT have a child object with the name "cardImage". To fix it, make sure such an object exists
and has an Image component. The rest is noise.
this way?
yup Im missing one
I'll change it now
Yeah
so i should change InventoryCard, to the prefab of the actual cards going into the inventory?
but other then that is it okay?
I have no idea what that means
those are currently as scriptable objects
show what object you assigned to the InventoryCard variable
like
Best way would be like this though, but this is not really performance critical code, so this is fine
does it have any children?
Your code is trying to find a child object of this
iwth the name "cardImage"
no it doesnt
yeah
so with that knowledge, you should be able to fix this, yes?
either changer the code
so how do i change it so it looks for the image on that card tho?
or change the object
is that not really simple?
