#💻┃code-beginner
1 messages · Page 85 of 1
you probably have some code doing that 🤷♂️
Your agent is snapping to the navmesh
Okay I managed to moved it to 0,0,0 and the same problem still persists
Apparently the agent is still not close to navmesh
well it appears that you are spawning the object with the navmesh after the agent has started so that warning is going to persist
as for why clicking it doesn't work, have you ensured that the object you are creating there actually has a collider?
This is what I coded it to do
So everything should be there once the mesh is generated
(hopefully)
You'll probably have a better time just using a terrain here
You should add debugs like if that raycast hit anything, and where it hit. Maybe even put a object in your scene which follows where your raycast is hitting so you can visually see what's happening
yeah and also actually check the object after you've created the mesh instead of assuming that everything is set up correctly
Yeah everything is there
okay and what debugging steps have you taken
I've managed to print out the position of where the raycast hit
I'm also trying to do the second option where the object follows it
so you're printing out where the ray hits, so is it hitting the mesh?
Nahh it's not - that means the mesh doesn't have a collider?
The simple solution is to change the collider to convex but that would mean that the object would just float a bit
just for testing purposes, make the mesh collider convex and try it again
Yeahh it works on a flat plane
Oh wait since NavMesh makes the agent snap to the mesh wouldn't that mean that the agent wouldn't be able to float?
it might be that raycasts don't work correctly with non-convex mesh colliders. i'm not 100% certain on that, i'd ask for advice regarding that in #⚛️┃physics maybe
Yeahh I'll do more testing and if nothing happens then I'll go into that channel - thanks for the help though 🙂
The agent should have a base offset to it, which you can use to raise it. Typically the base point is at the feet for models made properly
Hey all, I have a quick q. I have a list of 7 keywords, that get compared against a speech to text string. That all works fine, my issue is I only want my keywords to increase a score value 1 time and then not be able to increase the score value again.
Save the already used ones in a HashSet or List and check each time if it's been used or not
Or remove them from the list as they are used
thank you!
i was so blocked on that
removing them seems iffy, I think adding to list and checking against will be ok as it's only 7 keywords
Worked like a dream, thanks!
guys how i set the object that the player is carrying in the object holder?The objectHolder is an object that indicates where the object is positioned when you carry it, as in my case I placed it in front of the camera
the code part: void GrabObject(GameObject obj) { objRigidbody.isKinematic = true; obj.transform.SetParent(objectHolder); obj.transform.position = objectHolder.position; float yRotation = obj.transform.rotation.eulerAngles.y; if (yRotation < 90f) { obj.transform.rotation = Quaternion.Euler(0f, 90f, 0f); } else if (yRotation < 180f) { obj.transform.rotation = Quaternion.Euler(0f, 180f, 0f); } else { obj.transform.rotation = Quaternion.Euler(0f, 0f, 0f); } }
That rotation code is janky, and it's unclear where that rigidbody reference comes from. But otherwise looks ok assuming the references are ok
What's the issue you're having?
that rotation thing is something I'll ask about later
I wanted to make it so that by pressing E on an object the player could carry it
the objectHolder I think you will know what it is
Well like I said this seems mostly ok what issue are you having?
You can Raycast from the camera and if it hits an object with a certain component/tag, pick it up
that when I press E the object I want to grab is not placed in the objectHolder (I parent it, remove gravity and give it its position and none of those things work)
I actually want to do all 3
I wanted to make it not depend on a tag but rather on the mass of the object
yep i already did that if (objRigidbody != null && objRigidbody.mass <= 15f)
i have problem with this: obj.transform.position = objectHolder.position;
carrying object position = object holder position
What exactly goes wrong?
As I said, the GrabObject code method does not apply, that is only because I already did debug.log in everything.
It seems weird because it looks so correct
Do you have any solution or do you know which is the problem?
So is GrabObject even getting called? And do you get any errors while playing/grabbing?
Where do you set objRigidbody?
Showing the rest of the !code would be better
📃 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.
I'll give you the code in a while, can you wait for me?
Is it possible to return a bool from an inheritant class form the main one?
public class Dog : Ai
Depends on its access modifier. Assuming you mean a field in the base class
hey guys am i allow to copy paste code files here or no?
This is the bool im trying to return
I mean you can post it here and me or someone else will take a look
private is not accessible from outside the class.
the attack class is basically a collider that holds the transform inside it
right i can make it public forgot sorry
protected would be accessible from inheriting classes.
Python?
yep
How is that unity related?
its not xD i joined this awhile ago when i had a c# project so hoping maybe someone here maybe could lend a hand even though its kinda off topic
it was a last min desperate attempt
alrighti ll give it a shot
thanks
Might want to ask about python code in python community.
This is not the right place.
gotcha fair enough sorry about that
To be clear. Did you confirm with logs that GrabObject gets called?
Also instead of this; cs GameObject obj = hit.collider.gameObject; Rigidbody objRigidbody = obj.GetComponent<Rigidbody>();
Do this:cs Rigidbody objRigidbody = hit.collider.attachedRigidbody;
Otherwise it won't work on child colliders
if Dog:Ai has a bool called hasTarget it would override its parent class bool with the same variable name right?
https://hastebin.com/share/ohomupanom.csharp whys it not corresponding?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yes. It would also give you a warning(or error?) Unless you override with the new keyword.
awesome thanks
Presumably you assigned your references incorrectly in the inspector
BTW you should use arrays
aight
that wasnt it
but its my fault for not giving the gunscript too
the issue was that in the script i gave, it was able to go to previous and next when scrolling, but the gun script only had one direction for scrolling
How I get my NPC objects to move left and right?
private float speed = 1f;
public float direction = 1f; // 1 for right, -1 for left
private void Update()
{
transform.Translate(new Vector2(speed * Time.deltaTime * direction, 0));
}
This just moves it up
Translate takes a Vector3, you are giving it a Vector2
Also if your object is rotated it will move your object in the local direction relative to its rotation
Then your object is facing up
this is def X movement (left to right)
Guys, I'm having a problem with light2D:
"The type or namespace name 'Light2D' could not be found (are you missing a using directive or an assembly reference?)"
Does anyone know what I can do? I tried adding "using UnityEngine.Rendering;" and it's not working
did you save after adding using ?
if you're using urp its under UnityEngine.Rendering.Universal
Dude, I'm pretty new to this "assembly" thing, like I was doing some work and out of nowhere some assembly errors came up, I watched some videos, read a little, tried to fix it by creating an assembly definition, but these problems came soon after
Yes, I'm using URP, I've actually used it before, but this is the first time I've had this problem, right when I was building my game
Ah, I added a URP runtime assembly and the error stopped, now I just need to resolve the same error for something like "searchService" and "U2D", that's difficult.
Guys which is best normal coding or visual scripting??? And which is easy
And please tell me how to get water in unity
And also tell me how to make my fps game multiplayer and 10 max member each room capacity using photon
Hello. Can someone send me a link of a unity beginners coding guide to C#. I cant find it. thx!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
THX
Pls help me anyone for this thing
err if you are asking the first question, this one is the last thing you should worry about..
first question is pretty subjective lol
Heya, does anyone know how to prevent my camera from flipping upside down? I'm currently attaching it to my mouse movement using this code void Update() { transform.eulerAngles += LookSpeed * new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0); }
I don't really understand what attribute determines whether the camera is upside down so I can't lock it in place
Probably the y component of euler angle exceeding a certain amount
The euler angles are the same numerically as the transform right?
If so, the y doesn't seem to be the problem. It can have the same values whether the camera's flipped or not
Not necessarily
They can go negative while the ones in the inspector are positive. They don't always match, if that's what you meant
Is that's the only difference, then it's still not the Y component that's flipping the camera
Because the inspector does show both pos and neg and I can get the camera to flip without the Y val changing
The inspector shows both, but they simply may be different. Like the code may say -359 while the inspector says 1, for example.
I didn't see what the issue was from earlier. Just your last question about how euler angles work
Ah it's the X value being outside the range of 90 -> -90
Dunno how it happens but I'll try limiting it
Nope NVM wasn't that
Okay still confused on what value is different from the camera to be upside down
Okay so still don't completely understand why it flipped, however I managed to stop it from flipping by preventing the camera from looking directly up/down or any update that would've pushed it past. I used the eulerangles.x value to figure out how high up the camera was pointing. Thanks for the suggestions guys!
With these questions, I don't think you should even consider making a multiplayer game in a few years or something.
Making dynamic water is also difficult.
Gotta do small steps at a time.
Best to code normally btw. 
What have you made or done so far?
Sounds like a gimbal lock problem.
Equipment equipment = FindFirstObjectByType<Equipment>();```
Why does the 2nd line work but the 1st throws a NullReference?
Equipment is a Script reference on a character gameobject that references the equipment gameobject
character is null, if the line itself is throwing the error
the 2nd line has no relation, that searches for any loaded object unrelated to whatever a character is
yeah just tested that, character is set, but it doesn't find the equipment on character
then there is no equipment on the character
I'm missing something stupid lol
I can see the equipment script on my character, hmmm
Maybe you're looking at the wrong place. Like a prefab that is not in the scene.
dont see, use your code to debug
like dlich said, you could be looking at the wrong place, but you could be looking at the wrong time. What if you are doing character = null at some point
wat?
is there some way I can list all the components of my character?
yes, but i dont really think this is what you'd want to debug with. When debugging you can add a 2nd parameter, the context, and unity will highlight what object printed the debug
ah lol, equipment is a private variable on character
just had to do character.Equipment to use the get function
🤔 how were u seeing an Equipment component on your GO then?
that alone is just a way to provide a reference, it still not a component on the GO then. But glad you solved it at least
cant say much without seeing the script, did u google the error
Share the script 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.
your file name does not match the class name
it matched
Turretattribute != TurretAttribute
ah got it. thank much
{
if (input.Shoot)
{
gunController.OnTriggerHold();
playerController.PlayShootTrigger();
Debug.Log(input.Shoot);
}
if (input.ShootRelease)
{
gunController.OnTriggerRelease();
playerController.ResetShootTrigger();
}
}``` anyone know why my animation is refusing to trigger, i get no errors.
We're not here to go through all your code and images and find the error for you
If you narrow it down we can help - but this (at least for me) is way too much information to go through
Is there a way to programatically assign a Scriptable Object to a gameobject?
a scriptable object is not a gameobject, so you should clarify what you're trying to do. I assume trying to fill in the reference of an SO on a script you have
yeah
some script is either gonna have to use Resources (or something similar) to load them all from assets, or you'll need to drag the reference into a script with a public or [SerializeField] field
make a database of SO references if they are loaded already
depends what you're trying to do
I'm saving my items to a database
But I need some way to save the SO to the database and then load it in my game again
ids
why would you need to save a SO, these should be immutable data
just need to save a reference to it, like an id
but I'd still need to load the SO on the item once I create it
my item SO's hold the item image
i'm trying to Loop through a list of classes but for some reason unity throws a NullReferenceException unless i have the player selected in the Hierarchy
show the code, i'd bet something in the list is null, not the list itself
ah my misunderstanding, yes you'll have to generate your own ID. How u do this really doesnt matter, an ID can be an int, string, whatever you want as long as you have 1 unique per item. You could store a dictionary from ID -> SO but when you save you'll also need SO -> ID.
I think best would just be store the ID on the SO, then some database holds all the SO in a list (or you can still do a dictionary if you care to)
yeah the problem is not the saving
I just don't know how to load (attach SO to gameobject) my SO again through code, I've only used SO's through references
I guess Resources.Load?
Or should I make a gameobject that holds all my item SO's that I can reference instead?
the code works perfectly fine if i select the player but doesn't work if i didn't, i'm not sure if this is the correct way to create lists
Either one works, it does not matter as long as you make sure that game object exists at the very start of the game and gets placed in DDOL
it would likely be a singleton unless u are some die-hard DI fan
Resources.Load would be more automatic, but you have to follow its forced file structure
yeah it would be a bother to manage that dictionary
public class SerializeItem
{
public string storableID;
public List<string> modIDs = new();
}
public class string WriteItem(Item item)
{
if(value == null)
{
return null;
}
SerializeItem serializeItem = new();
serializeItem.storableID = item.Storable_ID;
foreach(String mod in serializeItem.ModIDs)
{
//Add mod ids
}
//Convert to JSON
}
public Item ReadItem(string value)
{
if (value == null)
{
return null;
}
//Convert back to type
return new Item(serializeItem);
}```
it wouldnt have to, you can directly plug them all into a list in one motion. then on awake, the script can generate the entire dictionary. Its technically more of a waste of space but 🤷♂️
oh yeah and your load manager should have a dictionary of SOs
too lazy to write that all
Dictionary<ID, SO>
implying your SOs are immutable
I would just paste my whole script but it's tangled in covariance bullcrap
I've actually not really touched much on Resource.Load but I should probably look into it. I feel like SOs are light enough as is for data objects.
what does the time.deltatime and the number 20 mean?
even on a unity learn page, it says its not recommended to use. if you can manage whatever the other solution is (addressables/assetbundle?) then i think that is better. But i also do just use .Load for a quick thing right now to get all items
20 is a number, Time.deltaTime is the time since the last frame. This value is very small so whoever wrote this used 20 to make it move faster. 20 would be your "movespeed", you move 20 units per second
thing is I feel like stuff for items I would never dynamically remove the SOs once loaded in so I feel like I should just upfront it all
yea for sure, makes sense for an item dictionary. i just find resources really awkward because of the forced file structure. I also dont know how the other solution works but i plan to learn it eventually
20 is your speed and deltaTime prevents those with quicker monitor refresh rates from cheating and getting ahead of everyone (worth a google)
Not sure if I explained it right.
My game is saved to and loaded from a MySQL database
So in the database a simplified item would have: ItemSO-ID, itemName, itemStats, ...
So when the player loads the game and I Instantiate their items, I somehow need to re-attach that ItemSO-ID as a Scriptable Object to the Item gameobject
The only thing I use the SO for is storing the item image (maybe there's a better way to do this?)
but then I'd have to manually drag all my SO's into that dictionary?
and they are subject to (a lot) of change
Eh, you can just do it in start()
Make a script to grab all SOs you want, then when you start your program it adds all SOs to a dictionary using their ID as a key
I'd still need to use Resources.Load for that then?
Resource.Load is for when you don't want to upfront the assets. As is, you load every single asset in your program if it's not bundled in a way or stored specifically. Actually stuff is somewhat compiled out I think if it's not part of game assets like prefabs, SOs, ect. Need to read up more on this.
so you're saying I don't need it?
then how to I put the SO in my dictionary?
The SO's don't exist in my scene, they're only in my assets folder
SOs dont ever exist in the scene. You start your program and you instantiate a single instance of each of them
and they live in memory
I might end up with thousands of items over time, so it's probably better to just load the ones I need instead of putting them all in the dictionary?
one player will only be using 10-100 items
but there might be 1000's in the database
item types, not items
Right, so this is what me and bawsi was saying that if you don't want these instances to be loaded on program start, then you need an alternative way to bundle them then load them via path or directory.
so Resources.Load?
Yeah, and assetpath/bundles
Depends how you want to manage the data, but SOs alone aren't heavy, it's usually what they are referencing is what you want to manage.
textures/models/ect
So I guess I just save the resources.load path to my database instead of an id?
it's just basic sprites, nothing heavy
2d game
path is pretty much unique so it can be an ID. May still be wise to give the SOs a guid.
this helped a lot, thx 🙂
ye
actually don't even need to save the path if I just make sure my item name is always the same as my SO name
gold.ItemSO = (ItemSO)Resources.Load<ScriptableObject>("Items/" + gold.name); 🙂
i manged to fix my issue by making a new animator
What is the word for unlocking cursor in Cursor.lockState = CursorLockMode. ?
if i make SmallClass smallClass { get; private set; } i can access it with bigClass.smallClass
how to "override" it so it returns other smallClass?
so it's not bigClass.smallClass(), just bigClass.smallClass
i know i can make it as virtual method and then just override it, but can i make it look like it is property?
You're wanting to make a property and not a function. The naming convention is PascalCase
bigClass.smallClass(), just bigClass.smallClass```
What is your expected return type here?
SmallClass
Yeah, but even if you override it, you're still expected to have an explicit return type.
Sounds like you'd probably want some generic constraints, but I'm not exactly sure of your use case.
You know what, maybe it is a property you need.
damn i already knew how to do that :/
already did that 3 months ago
sooo
if parent creates new list
public virtual List<Waypoint> waypoints { get; protected set; } = new List<Waypoint>();
but child override it without creating new list
public override List<Waypoint> waypoints { get; protected set; }
no new list will be created, right? or it will be created and removed by GC?
I'd assume the compiler is smart enough not to create it.
Looks like default value is a new instance
Override simply mutates the getter and setter?
Does that throw any errors? Pretty interesting design choice but if it works.
also still waiting on my struct initializer update ;(
I'm assuming the back field is made visible to the inspector and modifiable.
using System;
public class P{
public virtual int x{get;set;}=100;
}
public class C:P{
public override int x{get;set;}
}
public class HelloWorld{
public static void Main(string[] args){
Console.WriteLine(new C().x+" "+new P().x);
}
}
```outputs 0 100, looks likes the field initialization also be overridden not only the getter setter
may not be true inside unity btw
I want my enemy to turn around when it hits a wall but I can't figure out why it doesn't work this is my code
public bool TurnRight = false;
private void OnCollisionEnter2D(Collision2D collision)
{
print("turn");
if (TurnRight)
{
transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(1, 0);
TurnRight = false;
}
if (!TurnRight)
{
transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(-1, 0);
TurnRight = true;
}
}```
the collision is being called and the boolean is being turned but the velocity won't change?
Both if statements will be true if the first is true
You probably want an else if
Or simply an else
second->
first then second (after first if block sets the turnRight to false second if block got executed)
that makes sense, but an else statement still gets called, do i need to implement some sort of cooldown?
You could probably also do:cs { ... = new Vector2(TurnRight ? 1 : -1, 0); TurnRight = !TurnRight; }
Both cannot be called if there were an else
but it seems to call the collision entry 2 times so the second time it would be rediorected to the else statement
Is there such a data struct in c# that's a linked list, but instead of autosizing I'd keep the preferred size so I can reuse my struct data. It's an odd requirement, but I should never have a capacity larger than preferred, and would like to insert at O(1)
Enter only occurs once. You've got the component on more than one object or collision is occurring again immediately. The problem lies elsewhere.
just limits the size before insert?
btw linked list is not random access
yeah, but you always have the head
what's happening is that I have data being removed at different times
I'm working with buffers so I've got a capacity and stride I need to respect, but so each of these objects in the linked list will have an index to the buffer when it's read in
Link list implies memory is not continuous.
If the number of elements aren't too much, consider a regular list.
Yeah, but the thing is I need a 0(1) insert time while respecting nulls and capacity
buffers that were being updated every frame. It's something that probably needs to be as performative as possible.
Is insertion speed more important or avoiding garbage collection de-allocation 
just keeping a regular array and remove as swap back, since each element have the index pointing back to the array
linkedlist -> Knows where to add on last. Knows how to reconnect list when data is removed. But, is garbage collected when removed.
Yes.
instead of recreating structs of my data, I just need to change a variable from on to off
that's kinda what I'm trying to do
can't be nulls in the buffer and it respects a stride
Hello again 😇
So I have a GameObject Character that holds a Script Character that References a Script Inventory
How do I get my Character Script through code in the Inventory Script?
I've tried GetComponent, GetComponentInChildren and GetComponentInParent but can't seem to fetch it?
Probably doing something silly again
it really is happening twice to the same gameobject, I checked for duplicates of the script but there are none, could it have something to do with the fact that it is colliding against a tilemapCollider?
public struct Array<T>where T:IHasIndex{
public T arr;
public int count;
public void remove(T t){
count--;
T back=arr[count];
back.index=t.index;
arr[t.index]=back;
}
}
There's no continuous allocation - link list.
You can avoid gc collection by continuing to have access to the elements - the higher expense of allocating new memory.
use oncollisionstay instead of enter, collision enter can trigger several times in the same update
that doesn't work either...
we're gonna need some more info than that
Maybe create an object pool to avoid gc. I'm pretty sure that's where the expense is at with link list. @timber tide
Yeah, I swear I've used some library for this type of struct in c++ but doesn't seem to be such natively in c#
capacity with head and tail pointers that aren't removed
Just pool the data. I don't think adding nodes are the issue. The old nodes being collected are a concern though.
Its sending the message and changing the boolean, but the velocity isn't changing could it be protected somehow?
What's your current code look like?
he posted it above
I've only seen the previous with two if statements
just updated oncollisionenter to oncollisionstay I think
Which the second would behave the first - relative to the boolean turn right.
private void OnCollisionStay2D(Collision2D collision)
{
print("turn " + gameObject.name + transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity);
transform.parent.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(TurnRight ? 1 : -1, 0);
TurnRight = !TurnRight;
}```
He only wants it to occur once.
yeah OnCollisionEnter can trigger multiple times in the same update when colliding vs a tilemap, since you can have multiple collision points
I just added the velocity to the log and it does say it's changing so the problem is still the multiple calls
pretty sure the way you're trying to set the velocity is not correct, go look up some tutorials 🙂
Comment out the velocity statement and see how often it's printing.
If the object is intentionally returning to the collision point after being repelled, you'll get multiple events to be fired.
that's probably what is happening yeah
it should just go the other way thus not invoking another collision
That's what's assumed.
I'm assuming this is some pong variant that only traverses left and right.
Character character = this.gameObject.GetComponent<Character>();
How is this returning Null when the script I'm calling it from is referenced inside a Character script?
this is Inventory, which is referenced inside my Character 😦
Get component returns null if the object doesn't have the component
this is the console after 1 frame of collision
did you comment out your transform line and let it run to see how often it collides?
What's the console error from the unity console tab?
NullReferenceException: Object reference not set to an instance of an object
yes, and this is the second frame
Game Object property cannot return null so I'm assuming you're using the reference elsewhere that's causing the error to be thrown.
ah yeah my line just returns Null
so it is turning back in a different frame
no error
that means it should be fixable with a cooldown right? but it will be kind of janky
It could be that you're calling this from a destroyed gameObject.
I just want to get my Character Script from the Inventory Script
GetComponent, GetComponentInParent and GetComponentInChildren all return Null
Get Component cannot throw so the error is likely from elsewhere.
yeah the error is from the line below where I try to use it lol, error is not important here
I just don't get how it can return null - or how to fix iit
Maybe take a screenshot that shows more of the context.
And share more of the code.
When logging with debug, use the second argument of this to have the object highlighted.
Perhaps forcefully pausing the editor if the object isn't in the scene by default
{
public void AddItemToInventory(Item newItem)
{
//Character character = FindFirstObjectByType<Character>();
Character character = this.gameObject.GetComponent<Character>();
Debug.Log(character);```
tried that, doesn't do anything
Debug.Log($"Character: {character}", this);```
If you select the log in the console tab, it'll highlight the object in the hierarchy.
If present
if the inventory and character are in the same gameobject, why dont just reference it?
okaj that helps thx 🙂
What exactly are you doing in that code? Why are you using 2 separate methods for finding the character? And is your inventory script on the same object?
so my inventory script is on a totally different gameobject lol
It's very common 
hello, i may need some help regarding understanding this code. so i can understand the plater is link to the game object (main camera) but i am confused about the transform.position = player.transform.position + new Vector(0, 5, -7)
so will it repeatedly like go up since the y is a positive
Maybe the turn direction should be the difference in the position of the two objects? (assuming you're wanting the object to move away from whatever it hit)cs ...velocity = new Vector2(collision.transform.position.x - transform.position.x > 0 ? -1 : 1);It wouldn't matter how often it fired, it'd always be in the correct direction.
dopes this change the position of the gameobject?
It should set this object to the position of the player with some offset
If this component is on the player, you'll go up to infinity.
so the code i sent earlier, the player.transform.position + new vector(0, 5, -7) since its written under update does y goes up by 5 units repeatedly
ah explains why the camera shot up into heaven immediately
Or if this object's position is with respect to the player as well
ie child object etc
If the player is child then the camera and player will both go up infinitely
then i have a question since this code is in the components of the main (im doing unity tutorial), why does it still ask me to target a game object
shoudnt it by default bve targeted onto the main camerqa\
So, make sure the camera/player aren't children or parents of each other.
so i should leave this on none(game object) ?
You'll get a null reference exception error, if that is what you're wanting.
so with this code as it is now if i set the main camera as the variable of Player the camera will just fly up right?
You have -7 on the Z axis too, so not just up.
is your vs configured?
Your !ide looks unconfigured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
configured?
we should have youtube links to basic tutorials for stuff people ask here non stop
like basic movement of objects (player bouncing earlier, camera following player now, ...)
Hi I'm trying to figure how how to pool 4 different objects make them spawn every 3 seconds and pool them everytime the objects animation occurs
you mean this
Easiest way to verify is to post a screenshot of your whole IDE.
Break the problem down. Which particular step are you currently working with?
Are you able to do object pooling with a single object?
So I've followed a tutorial and made a quick item spawner what I'm trying to do now is use the animation of the object on its cloned version
But I haven't been able to do that so I thought of object pooling
Yeah I've seen a tutorial on it so far
What is this for, bullet pooling?
Uhh well it's a trash picking game
Basically when you click a button 2 animations occur 1 is a tenticle and 1 is a trash
its looks nice, better than mine
Thanks
I just need 1 last thing to implement
The waste management in my county takes paper and plastic together.. thus we've got to clean off food particles from recycled products before recycling them.
Btw its for enemy pooling
I want 1 enemy spawned every 3 seconds and dequeued or despawn after 3 seconds
but I want it to have the original animation
We're assuming you've got the spawn and despawn done?
yeah thats why i was confused on why with the vectors provided by unity how does it follow the car
since its going up sideways
Each instance should have its own unique animation timer. Maybe reset the animation state when spawning from the pool?
yeah
I don't understand can you explain it a lil more
Like each instantiated object should have the animation of it's original?
Well looking at it again, your IDE is indeed not configured, you really need to do that.
And there is a difference between transform.position and player.transform.position, if this script is on the camera it would follow the player instead of going of into the sunset
public float SellValue { get { return 3 * Level; } internal set { } }
Can I still use setter without creating 2nd variable to store it?
It might have some extra overhead but you could try Rebinding the animator component to reset the state of the component.
https://docs.unity3d.com/ScriptReference/Animator.Rebind.html
https://discussions.unity.com/t/how-to-reset-animator-controller/206359
the green tick is counted as installed right?
Thanks
Yeah, but in your Visual Studio in the top left it says probably Miscellaneous Files instead of C# project. If you just post a full size screenshot of it, we can see if its a solution problem, or a version problem or w/e.
full screenshot of unity editor or visual studio code
oh theres a miscellaneous files
the code that is written in the picture above was what unity wanted me to write
Yeah it's not setup correctly, spend some time on doing that.
yo, Animator anim = Instantiate(object, position, rotation).GetComponent<Animator>(); can someone explain what I should be putting in object, position, rotation in my 3d game
I don't doubt that this is what Unity wanted you to write, the problem lies with what you put as a player in your Unity editor as a reference.
thats where i get confused, do i have to configure it from visual studio or unity
main camera
heey, how could i add an image to the canvas without deformming it?
Why is the Player the camera then?
assign camera as the players position
But this script is on the camera right?
this is a deformed canvas? looks preety okay to me
yes?
So read what you have programmed then
hello
Don't blindly do things, you need to understand what you are doing.
i wanna make a script that when b is clicked that it summons a 3d model on the player. anyone know how i could be helped?
You're basically telling the camera to move away from the "player" which is camera itself. It will just constantly try to move away from it's own position
ah i got it ... i cahnged the target from the camera to the car ... now the camera is stuck to the car
can someone see my code and tell me why its not working please
Guys how do I put an objects animation on its cloned version
Just post your !code with some explanation on what you tried and what the problem is
📃 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.
using UnityEngine;
public class MeleeEnemy : MonoBehaviour
{
[Header ("Attack Parameters")]
[SerializeField] private float attackCooldown;
[SerializeField] private float range;
[SerializeField] private int damage;
[Header("Collider Parameters")]
[SerializeField] private float colliderDistance;
[SerializeField] private BoxCollider2D boxCollider;
[Header("Player Layer")]
[SerializeField] private LayerMask playerLayer;
private float cooldownTimer = Mathf.Infinity;
//References
private Animator anim;
private PlayerHealth playerHealth;
private MonsterMovement enemyPatrol;
private void Awake()
{
anim = GetComponent<Animator>();
enemyPatrol = GetComponentInParent<MonsterMovement>();
}
private void Update()
{
cooldownTimer += Time.deltaTime;
//Attack only when player in sight?
if (PlayerInSight())
{
if (cooldownTimer >= attackCooldown)
{
cooldownTimer = 0;
anim.SetTrigger("Attack");
}
}
if (enemyPatrol != null)
enemyPatrol.enabled = !PlayerInSight();
}
private bool PlayerInSight()
{
RaycastHit2D hit =
Physics2D.BoxCast(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z),
0, Vector2.left, 0, playerLayer);
if (hit.collider != null)
playerHealth = hit.transform.GetComponent<PlayerHealth>();
return hit.collider != null;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(boxCollider.bounds.center + transform.right * range * transform.localScale.x * colliderDistance,
new Vector3(boxCollider.bounds.size.x * range, boxCollider.bounds.size.y, boxCollider.bounds.size.z));
}
private void DamagePlayer()
{
if (PlayerInSight())
playerHealth.TakeDamage(damage);
}
}
it should display the attack animation and deal damage to the player when its inside the hitbox but it doesnt
Add some debug.logs in your code and see if it even goes through all the if's you made
where should i put them
through all the if's you made
You could also just attach a debugger and step through your code, but that's a bit more advanced. Also a useful tool.
Guys how do I put an objects animation on its cloned/instantiated version
okay thank you
Meaning? Cloned version already takes everything the original version has.
I made an instantiate script but I want the instantiated object to have a certain animation
Then put these animations onto the animator and play the animation you need
yes but it doesn't apply to the cloned object
is something wrong? text is "x", but it doesnt display coin count
Meaning?
lets say these 4 objects
they clone themselves when the game starts
you can use AddComponent<animator> in script ig
Yes, and?
Unity Can
ohh
I think I already did that
wait
yeah
I want them to have animations
but they don't only the original do
ur getting component, not adding🤓
💀
bro no way that's what the problem was
😭
add component and then get it
If the original has an Animator with an animation, then the clone will also have the Animator with the same animation
Well it doesn't for some reason..
you didnt forget to save prefab right?
If you did everything correctly and everything is saved, then it should have, no matter what
Unless you remove it manually, it should be there
easy save?
using UnityEngine;
public class TerrainGeneration : MonoBehaviour
{
public int worldSize = 100;
public float NoiseFreq = 0.05f;
public float seed;
public Texture2D noiseTexture;
private void Start()
{
seed = Random.Range(-10000, 10000);
GenerateNoiseTexture();
}
public void GenerateNoiseTexture()
{
noiseTexture = new Texture2D(worldSize, worldSize);
for (int x = 0; x < noiseTexture.width; x++)
{
for (int y = 0; y < noiseTexture.height; y++)
{
float v = Mathf.PerlinNoise((x + seed) * NoiseFreq, (y + seed) * NoiseFreq);
noiseTexture.SetPixel(x, y, new Color(v, v, v));
}
}
noiseTexture.Apply();
}
}
use !text
I'll check
help whats error?
!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.
use this
wats that?
📃 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 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.
JUST OPEN IT AND PASTE CODE INSIDE
ik
it helped to me
did you save your code, how your ide looks like?
it works thanks wierd
ye
https://hatebin.com/cbwzblsitd i dont know whats wrong
Hi i created an isGrounded bool variable and a few lines after its not detecting it for some reason.
:/
im gonna kill myself if i see that again
use isGrounded instead of isGrounded()
almost all text with () means function
isGrounded is method, it is not variable
yea right sorry
anyone?
at line 33?
everywhere
dont please 😅
everywhere, replace all isGrounded() with isGrounded
but than the other code parts lose the accessor
private TextMeshPro text;
[SerializeField] private SaveManager saveManager;
[SerializeField] private PauseManager pauseManager;
```why not just serialize the text (as the two fields below) and drop the instance to it in inspector?
im getting TMP as component
private void OnTriggerEnter2D(Collider2D collision)
{
// Read dmg then reduce health of player
dmg = collision.GetComponent<DamageDealer>();
if (dmg != null)
{
Destroy(collision.gameObject);
health -= dmg.GetDamage();
Debug.Log("Damage recived: " + dmg + " Player health: " + health);
}
if(health <= 0)
{
// Player Ship Destroy.
Destroy(gameObject);
Debug.Log("Player Destroyed!");
return;
}
}
you dont need to get it in Start().....
This seems fine, you destroy the gameobjects
what u want from us?
He got here from #💻┃unity-talk from me
just serialize the reference and set it in inspector
oh ok
The issue im having is taht its getting destroyed before 0 hp and its not printing the Log so i have reason to belive its not being destroyed through this code
ok ill try, thx
Oh
{
// Read dmg then reduce health of player
dmg = collision.GetComponent<DamageDealer>();
if (dmg != null)
{
Destroy(collision.gameObject);
health -= dmg.GetDamage();
Debug.Log("Damage recived: " + dmg + " Player health: " + health);
}
You instantly destroy on any damage
guys why i have to click E multiple times to make the code works
this is the code:
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, RayDistance))
{
if(hit.transform.tag == "Sofa")
{
if(FNum == 0)
{
InteractionE.SetActive(true);
}
else
{
EmptySlot.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.E) && FNum == 0)
{
FNum = 1;
_Sofa.SetActive(false);
SofaUi.SetActive(true);
}
}
if(hit.transform.tag == "Table")
{
if(FNum == 0)
{
InteractionE.SetActive(true);
}
else
{
EmptySlot.SetActive(true);
}
if(Input.GetKeyDown(KeyCode.E) && FNum == 0)
{
FNum = 1;
_Table.SetActive(false);
TableUi.SetActive(true);
}
}
Thats the other object not player though
Still, does the damage log even print?
i needed to use TextMeshProUGUI, thx
Yes it prints that play ship still at 98 hp cause i set dmg to 2
Interesting, I would think the component would have been destroyed the moment you Destroy that object. Anyhow, it's something else then.
i'm making some navigation with waypoints. Now i need to make A-B-C path calculation, where A and C are just single waypoint, and B is array of waypoints. So, first i need to find shortest paths from A to each of B, then shortest path from each B to C, then pick two shortest paths and return them. Is it just better to go with cached pathfinding instead?
idk bro thats why im here
try making it do smth before destroying
Like what
How about you chance all the Destroys to the end instead of the beginning?
idk what you want from this gameobject
It is there to simply deal me dmg and to check if im at 0 hp i die
i said same thing in different words
I dont understand what chance
Destroy destroys this gameObject you currently have your script on, that way it doesn't continue with the code on the next line.
Uff what am I getting myself into public static List<Dictionary<string, object>> LoadItems(int playerNumber)
its in a separate if statement
Destroy runs, kills the object, Debug.Log never runs.
Change them around, and it works just fine.
then your path is A-b b-C where b is a waypoint in B array
Ok il try to put it before
the Debug.Log will still run even the object destroyed, instructions are saved in different memory space
` if(health <= 0)
{
// Player Ship Destroy.
Debug.Log("Player Destroyed!");
Destroy(gameObject);
return;
}
}`
like this ig
E ye still desont
Thats why idk why my ship being destroyed when conditions arent met
The ship gets destroyed.
Ah, I'm not aware of the discussion. Maybe something else is destroying it 
assume you put your code in update, probably raycast detects nothing or the tag of object not match
and use comparetag instead
Il just make it die through a boolean variable and see what happens
comment out that destroy call and see if he's still being destroyed
The problem won't go away if this isn't the cause
my way didnt work il try urs
bro what i did it like this look
bool isDestroyed = false;
private void OnTriggerEnter2D(Collider2D collision)
{
// Read dmg then reduce health of player
dmg = collision.GetComponent<DamageDealer>();
if (dmg != null)
{
Destroy(collision.gameObject);
health -= dmg.GetDamage();
Debug.Log("Damage recived: " + dmg + " Player health: " + health);
}
if(health <= 0)
{
isDestroyed = true;
}
}
void isDead()
{
if (isDestroyed)
{
Destroy(gameObject);
}
}
its still dyin
il just comment out if statement and see what happens at this point
Maybe it's hitting itself?
I didnt add a damagedealer script to player
Obstical hitting my player
Is that what the log shows?
Debug.Log($"{name} was hit by {collision.name}", this);```
Did you save? Are there errors in the console prior to running the application?
Maybe you've got something else destroying stuff in the scene
Rigid body does not destroy hierarchy objects..
This is the coding channel, try #💻┃unity-talk
I had to add rigid body cause without it collision doesnt work
Rigid body doesn't destroy stuff
You've got a script destroying stuff
il try to find it ig
WEll
I found the issue
having mass lower than 1 was the issue
what a waste of like 3hrs omg
And also tell me how to make my fps game multiplayer and 10 max member each room capacity using photon
Nobody is going to tell you how to do that.
Nobody has the time?
So find a tutorial if you think making something as complicated as multiplayer is a feasible scope for you.
Okay sir👍👍👍👍
Heya, I'm working on an inventory system where you can toggle (Activate/Deactive the game object of) the inventory menu. Because of this I made a Method "ShowInventory" that runs after I Activate the Inventory.
For each slot I want to insert the corresponding item from GameObject array "items", which is done by a SetItem method taking a GameObject in Script "InventorySlot" assigned to each slot.
I'm getting a NullReferenceException telling me that the Object reference is not set to an instance of an object at line 69, and have no idea what causes it :/
Is the component on the object?
which component? Inventory(current script) is on an object called "UI" which has a child "Inventory" which the Slots are children of. InventorySlot is on the mentioned Slots
Debug.Log($"Found: {searchedSlot}", searchedSlot);```
Place that line before the error line
Select the log and see which object is highlighted
youtube has plenty of tutorials on making multiplayer games (probably some on photon)
you can even see I'm testing wether Child(1) is active before searching for Child(0)'s slots, unlucky haha
var values = JsonConvert.DeserializeObject<Dictionary<int, object>>(result);
// For debugging
foreach (KeyValuePair<int, object> pair in values)
{
Debug.Log(pair.Key + ": " + pair.Value);
}```
How would I loop through this next part?
What exactly are you wanting to do?
get to the individual key/values
Well, you've looped through and printed everything.
well hello guys I need some help with my car system
yeah but it prints json I think?
how do I access the values in it? I tried deserializing again or looping through them, but can't find a way that works
It's a dictionary and you've printed the key value pair
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Car_Controller : MonoBehaviour
{
public float steeringAngle, motorPower, powerToApply;
public WheelCollider[] wheelcolliders;
public Transform[] wheelObjects;
public Transform centerofMass;
public int gear, maxGear;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalculateMotorPower();
ApplyToWheels();
}
private void FixedUpdate()
{
//rb.centerOfMass = centerofMass.position;
}
void CalculateMotorPower()
{
powerToApply = Input.GetAxisRaw("Vertical") * motorPower;
}
void ApplyToWheels()
{
for(int i = 0; i < 2; i++)
{
wheelcolliders[i].steerAngle = Input.GetAxisRaw("Horizontal") * steeringAngle;
}
for (int i = 0; i < wheelcolliders.Length; i++)
{
wheelcolliders[i].motorTorque = -powerToApply;
}
}
}
how can I apply the rotation of the wheel colliders to my all wheel meshs?
Dictionary is a c# collection
var values = JsonConvert.DeserializeObject<Dictionary<int, object>>(result);
foreach (KeyValuePair<int, object> pair in values){
Debug.Log(pair.Key + ": " + pair.Value);
}
```do you know what is the type of "values"
it's a nested dictionary
the first one is <int, object> wich has 1, dictionary<string, object> and 2, dictionary<string, object> which is what you see in the screenshot
I need to loop through the inner dictionary, but can't find a way that works
So the element found in the dictionary is a dictionary.
You'd use the public members provided by dictionary to access it's data
Why not use a Dictionary<int, Dictionary<int, object>>?
cast the object to string
Or use a custom class for your JSON representation, like how it's meant to be used
how would I loop through that?
yes just deserialize the result as dictionary<int, your class>
What do you want to do in the first place?
sounds interesting, but never heard of that
I'm getting a list of items from my database
If you get a JSON payload from some API, then you should have a class that conforms to the structure of the JSON payload
[
{
"name": "Sample Sword",
"damage": 42
},
{
"name": "Wooden stick",
"damage": 1
}
]
Given this payload, this could be deserialized to a List<Item>, where Item is:
class Item
{
public string Name { get; set; }
public int Damage { get; set; }
}
yep that worked, thx 🙂
yeah I have an Item class with all these fields
no, you should create the class in c# side as spr2 said instaed of just cast it to string and generate other dictionary<string,object>
I want to save a GameObject visibility ( SetActive(true/false) ). What is the simples solution for it? Playerprefs.SetBool is not existing.... i read a workaround to make a SetInt for the bool 1 or 0 and do a if statment if that int is 0 then false, 1 return true. But i wonder if there is another easier method for this.
Then you should be able to just do List<Item> items = JsonConvert.DeserializeObject<List<Item>>(jsonString)
The library will take care of creating the class instances for you
The next more appropriate hurdle would be working with file reading and writing
I've used up all my brain capacity for today I'm afraid, would I need to change my API to return a list instead then?
I don't know how your JSON looks, so hard to say. The structure of your C# classes depends on the structure of the JSON you receive from the server
just deserialize the string as your class instance, change the generic parameter
I believe they're suggesting that you wrap up the collections and other such data in classes to better maintain not having to convert stuff.
i think the json format (ie what are the values to return) returned by your api is defined by yourself?
then create the class in your c# script
I can see a part of the payload here, so you'd need a Dictionary<int, Item>, where Item is a class that has the properties listed in the screenshot there
I think I'll just stick with the bad way of doing it for now, but I'll keep it in mind if I ever wanna refactor this
pretty sure it won't work with my current Item class, since that does some other stuff too and has more values than the json has
eg your api return an object which is
let name:string;
let numbers:Array<number>;
```then create a c# class to receive the json response
```cs
public class{
string name;
List<double> numbers;
}
Nah the serializer is pretty lenient on that. If there are properties in the class it can't find in the JSON, and vice-versa, it'll happily ignore those
You'll have to convert all the fields public int Sample; to properties public int Sample { get; set; }, or configure Newtonsoft to populate the fields instead
Im following this tutorial to make my own animated character: https://www.youtube.com/watch?v=cEqjkubspGo
but the code they used was fine, however when I import it- its completely broken to the point it doesn't know what unity even is.
37 errors of it now knowing what anything means.
In this Unity tutorial, I teach you guys how to make a basic third person character controller in Unity using the C# programming language. This character controller allows you to jog (forward and back), sprint, and rotate around for basic player movement. I also show a few easy camera methods as well.
#Unity #Unity3D
For more Unity tutorials o...
the first using SXXXX causes the parser fails
not sure what that means
this doesnt work, how else could I make the player face forward with the camera
player.transform.forward = .
phew thank you
Your version should report an error that will underline a part of this code in red. If that's not the case, you need to configure Visual Studio so it's linked to Unity
!vs
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)
Hey I'm trying to create an enemy that leaps forward if its close to the player, it mostly works but if I go towards the enemy while it close to me I get a bug that cause him to go to the other direction forever
https://gdl.space/cizohasini.cs
i used the logic from a tutorial but i think it's problematic
Hi there I'm having an issue where the first part of this code works, "currently on trigger" side but the "enemy took damage" does not display and instead "this is not an enemy" is displayed in the console. the colliding object other is tagged as enemy, can't figure out what could be the problem
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("currently on trigger");
if (other.CompareTag("Enemy"))
{
Debug.Log("enemy took damage");
enemyShooting enemy = other.GetComponent<enemyShooting>();
if (enemy != null)
{
enemy.EnemyTakeDamage(2); // Reduce enemy health by 2
}
}
else { Debug.Log("this is not an enemy"); }
}
is there a chane the is any issue with this method?
try and print 'other' maybe you have a typo or maybe you didnt tag the corrent gameObject
I have this bit of code that I use to control waves of enemies, and spawn a new wave from a set of waves when all the enemies in said wave are defeated.
...however, when a new wave is supposed to trigger, Unity just.. freezes. Stops working. Could anyone help, please?
using UnityEngine;
public class arenaList : MonoBehaviour
{
public List<GameObject> waveList;
public List<GameObject> enemiesLeft;
private Rigidbody2D rb2D;
void Start()
{
rb2D = gameObject.GetComponent<Rigidbody2D>();
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
enemiesLeft.Add(collision.gameObject);
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
enemiesLeft.Remove(collision.gameObject);
}
}
void Update()
{
if (enemiesLeft.Count == 0)
{
for (int i = 0; i < waveList.Count; i++)
{
i = enemiesLeft.Count;
waveList[i].SetActive(true);
}
}
}
}
are you doing the Blackthornprod course?
solved it after printing that thank you.
no, why?
nice. what was the issue?
i just did something similar a week ago
the enemy did not have a rigidbody2d and the sword was colliding with the projectiles enemy shot.
Does the unity editor/app crash or does the units simply not spawn?
unity editor freezes
if the units didnt spawn I couldve looked at the errors, unfortunately I can not..
That means there's an infinite loop (recursion or whatnot)
I guessed that couldve been the case-
try to print 'waveList.Count'
Pretty certain the script provided isn't the issue
i suspect it might loop to infinity
I wouldnt be able to since I cant access the console
Show us the units
do it before the loop
alright give me a second.
You're simply setting them active so I'm certain something else is managing their placement
hmm.. lemme see.
I set this up because some other scripts couldnt do the wave system frequantly. I am pretty sure I cleared them out but let me re-check just in case.
Wait.. you might be spawning infinitely 
Why set i equal to count (0)?
the first member of the list is memver 0
i = 0;//infinite```
I found one of my old level managers... lemme delete that and give it another try
...and another one
Unless something is changing the value of the enemy count, you'll get an infinite loop there.
yeah enemyCount constantly changes
Where?
Where in the loop?
OH
It's the problem
OH FU-
okay yup I saw the issue.
oh my god Im an idiot..
I used i to for both the wave count and the enemy count-
why did I have that line in there?!
you will get to the loop only if enemiesLeft.Count == 0 so you alwaty set i to 0
and 0 is always smaller than waveList.Count (probably not 0)
you will get stuck in a loop
the process now is
-
wave 1 is already spawned when scene loads
-
once wave one is defeated aka no enemies are left in the list, a new wave spawns and those enemies are on the list
-
continue until level clear
You'd probably want to populate the list with the activated objects.
As is, every unit will come out immediately
okay so a lot of things broke but at least unity works now thanks y'all
alright having another issue where the game is not entering "OnCollisionEnter2D(Collision2D other)", both objects have boxcolliders2d, and have rigidbody2d, one of the box colliders is set to trigger, the other one is not. This script is on the collider which has the trigger.
collided with triggered collider will not fire oncollisionXXXXX
OnTriggerEnter2D for triggers
changed it, neither of the colliders are triggers, still not entering collision
You need at least one dynamic rigidbody too
so you know how most games have like attack animations where if you have a combo it swaps for the next attack animation or whatever
so its not just the same animation over and over
how would i do that
ahh okay this was it, they were both kinetic. thank you
With the animator State machine
does that allow me to say like if this animation is called again within like half a second of another it does the next one
Is visual scripting easy?
How to get ultra high graphics in unity?
No no just say easy or tough
you're in a code channel dude
doubt anyone here uses visual scripting
Hey I'm trying to create an enemy that leaps forward if its close to the player, it mostly works but if I go towards the enemy while it close to me I get a bug that cause him to go to the other direction forever
https://gdl.space/cizohasini.cs
I used the logic from a tutorial but i think it's problematic
is there a chane the is any issue with this method?
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
Not a code question. Google it(HRDP)
so does it allow for this or do i need to make a script for it
heyy Im back. (context here)
newer waves dont make the unity editor freeze anymore, however, multiple of them spawn at the same time now.
you should use https://gdl.space to send the code
Make a bunch of ints in animator as transitions and use diff Int to trigger dif animations
done
oh... why?
cuz AI is often wrong
this is basic logic problem
it's very good at those
yyup it was wrong lol.
you should be more spesific and with 2-3 answers youll get it haha
doesn't matter the reason
just dont
also yeah dont.
Not really guessing, it doesn’t understand anything, it can just calculate the next word to fill in its answer and with enough context it can generate an answer, when the problem us logistic it usually can predict the error
But you do you haha
its like asking someone who doesnt know C# to fix C# code
since its a chat algorithm and not a Code algorithm trained on C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName ="Attacks/Normal Attack")]
public class AttackSO : ScriptableObject
{
public AnimatorOverrideController animatorOV;
public float attackDamage;
}
i cant create the scriptable object in unity like it doesnt show up any clues
Any compile errors?
nope
Is the file name the same as the class name?
yeah
how do i recompile
Like this
Like spr said
so i think i know the problem unity keeps making me restart it to add a new script
yep works now
I accidentally copied the answer to the new chat I sent you 😅
really weird how i gotta relaunch unity everytime i make a new script
aanyhow.. could anyone help me with this please?
Try updating the C# project files by going into Edit > Preferences > External Tools, then hit the Regenerate Project Files button
so I'm now having another issue, I've finally managed to set up a working trigger system using OnTriggerStay2D instead of on collision which works great for the most part. My intented purpose is that when the sword collides with an enemy and a mouse button gets pressed, enemy takes damage, however since enemies are shooting projectiles and they spawn from the center of an enemy at the player and towards the sword, the projectiles are triggering the OnTriggerStay and it takes multiple clicks to kill an enemy because the ontriggerstay is focused on a projectile collider instead of the enemy collider. Is there a way I could fix this?
You update i in the loop, preventing the increment (i++) to do its job properly.
Infinite loop successfully created!
this is the new issue
apologies-
nothing in this code spawns
EnemiesLeft is never updated
!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.
wdym? its updated
After the loop
It'll always be zero at some point, so it'll activate the wave continuously
its supposed to update when a new wave spawns because there are new enemies in that
Make sure OnTriggerEnter2D runs when your objects are enabled
isnt it meant to run ever frame?
Only when a collider enters the trigger
yeah it does run
As many times as there are enemies under the waveList[i] game object?
mhm
the new enemies spawned appear in the list
maybe the new waves spawn before the list can update?
Okay, it might be due to the fact that Update and OnTriggerEnter run at a different rate yes
Update runs each frame, varying, while physics messages try to run at 50 times per second (by default), fixed
so.. is there any way I can check that every frame?
If I were you I'd revamp the whole thing to use events instead
and I'd check only when enemy is added/removed (when list is modified)
Or check the list frequently to see if all its elements are destroyed
I could put the for loop under ontriggerexit...
brb, I have to go for a sec, Ill try that afterwards.
hello.
im trying to set my audiosource to a value that changes over distance but having a problem with the maxdistance value. if its 1 it works perfectly fine but every other value breaks it. i dont know why. appreciate any help
using UnityEngine;
public class HorrorLightSound : MonoBehaviour
{
public float maxLightSoundDistance;
public AudioSource lightSound;
public LayerMask mask;
private void Update()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, maxLightSoundDistance, mask);
foreach (var hitCollider in hitColliders)
{
var distance = Vector3.Distance(transform.position, hitCollider.transform.position);
// check if la playur is in distancey wancy
distance = Mathf.Clamp(distance / maxLightSoundDistance, 0f, maxLightSoundDistance);
// Value = now between 0 and 1 :cool:
var normalizedDistance = 1f - (distance / maxLightSoundDistance);
// volume is el normalized, now we apply it
lightSound.volume = normalizedDistance;
}
}
}```
Audio Sources already expose settings for volume-over-distance parameters
You do not need to do this in the code
did not work..
well i have a lot of objects that should make that sound so putting a audiosource on every single one isnt a option
It is the option lol
but arent audiosources expensive for the gpu?
its gonna be for the quest2 and 3 so it should be as optimized as possible
Audio is not graphics
i meant cpu mb
- Make it work
- Make it pretty
- Make it fast
well how do i make it work
By tweaking the audio source's settings in the Inspector
but isnt fixing that script way easier and better then putting a audiosource on every single light (around 500)
Tbh one OverlapSphere() called 90 times a second (that's the ideal framerate for VR, if I remember correctly) on 500 objects is way more expensive than audio sources
those 500 objects are around the map. this script is only on 1 object
how do i get if the current animation has ended
If the light object is a prefab, add the audio source on the prefab and it'll be reflected on all instances
its not a prefab its already placed around everywhere
Yeah...
Filter the Hierarchy with the search bar, and select them all, you should be able to add the sources all at once from the Inspector
Because you're reinventing the wheel for something that is already way more flexible
Audio Source volume over distance supports curves for the volume falloff
How can I add forces to a object?
And more stuff
Rigidbody.AddForce
thanks
i have images but how do i make it better resoultuion as its 16x16 rn
where code question llol
SOLVED IT HA-
using UnityEngine;
public class Gun : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform firePoint;
public float bulletForce = 20f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();
if (bulletRigidbody != null)
{
bulletRigidbody.AddForce(firePoint.forward * bulletForce, ForceMode.Impulse);
}
}
}
is this code right?
its on the left
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody bulletRigidbody = bullet.GetComponent<Rigidbody>();```
Prefab should be Rigidbody , skip GetComponent
not a code question #🏃┃animation
ah shucks i forgot
Not sure if this is a question for code, but I get "Cant add script" because the script class cant be found. I copied and pasted the name to be sure it wasnt a mistype, but the class and file name should be identical.
The only issure I can see is that I'm using "public class _ : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler", like alot at the same time
why do you have _ as name..
If you're sure the Class and Script name are the same and you're inheriting MonoBehavior, you could try restarting Unity.
I assume he did that so we can't see the class name for some odd reason?
because I wanted to give a general example?
so how's that help us verify that script name matches class name
you cant see the script name either, how will seeing the classname help when I already copy-pasted it because I wanted to make sure its not that
so doesn't that tell you perhaps share that the Filename and Class match?
Seeing the class name will help because that's literally the most common cause of that problem
📃 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 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.
bruv
after restarting unity it gave me a popup for Safe Mode, I ignored it (thinking that its nothing game breaking) and now I have these two errors
IndexOutOfRange is runtime error unless the editor is bugging out or have editor script
I hope this is enough for Scriptname and Classname
looks fine
woah!
Okay, good. You have no idea how many times people have sworn they match only to finally post them and they're entirely different words
you have error you can't do anything
you cant add new script if you have compile errorrs
Clear your console and see if any errors stick around
That gui one looks like an internal editor thing that probably won't affect anything
i didnt know that you couldnt add scripts when there were errors, that fixed it though. Thank you!
make sure to configure your IDE as well if you haven't already
I tried once but I dont think I did it correctly
how long ago ? they changed the whole process a lot. its only 1 extension now and updating a package
!vscode
would highly recommend you don't code without this
otherwise VSCode is no more useful than a text editor
yeah I followed that, just updated the VSE package
there is more to it, also try Regen Project files
double check .NET sdk was installed, if not install it manually
pls help me by writing a code that when will the player go to a certain cube the health will decrease til 0 and the health ui also get updated
you mean a trigger ?
what does "go to a certain cube" mean
i mean when player will touch the special cube players health will decrease by 10 each second
@rich adder
use Trigger Enter and Trigger exit and toggle a bool timer
or make a coroutine
ok sir
using UnityEngine;
public class CameraSwitch : MonoBehaviour
{
public Camera mainCamera;
public Camera secondaryCamera;
void Start()
{
// Ensure only the main camera is active initially
mainCamera.enabled = true;
secondaryCamera.enabled = false;
}
void Update()
{
// Check for right mouse button press
if (Input.GetMouseButtonDown(1)) // 1 represents the right mouse button
{
// Switch between cameras
mainCamera.enabled = !mainCamera.enabled;
secondaryCamera.enabled = !secondaryCamera.enabled;
}
}
}
code not working its saying that display 1 no camera found
that warning is usually inside Unity editor when you dont have an active camera
btw you can do
mainCamera.enabled = !mainCamera.enabled;
secondaryCamera.enabled = !mainCamera.enabled```
You may want to disable "Warn if No Cameras Rendering"
How to make Cut scenes?
You can use Timelines for that
not a code question. Timeline + cinemachine
where is one supposed to start learning unity
Everyone learns their own way. You could watch a few beginners tutorials on YouTube, or you could just mess around in it yourself and when you can't figure something out, look it up online.
I always prefer learning myself 🙂
help , i make a script of movement and the player doesn't collide with the walls
Do what ever you prefer, you can't do something if you don't enjoy it
but i cant find a good resource
Does the player and walls have colliders?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
can we talk in md and i send you pictures?
and we solve it faster
You can send pictures here although Im not sure if this is code related
Can you move to #💻┃unity-talk and send the images there
Most of the beginner tutorials on youtube are just rapidly produced garbage. The best thing imo would be learning c# independently of unity, so you arent learning 2 things at once. None of the unity tutorials really teach you to code either. If you dont already have a good foundation then all you can do is copy paste while assuming you understand it
i know basic c#
but idk very well stuff like lambda expressions and generics
so my plan was to learn a bit of c# while using unity
cuz the only thing i can do to practice c# is just to write console applications over and over
Best thing is just experimentation then, use tutorials to find out what exists (like functions you weren't aware of), or to find out what a decent structure is for implementing a certain game mechanic
Honestly, you just need to know the bare minimum of C# or other languages to get started with Unity
You could do online coding challenges, like on leetcode or whatever other website exists these days. It's very helpful to develop the debugging and data structures skills
If you dont have an exact goal in mind for what kind of game you want to make, then likely you wont be learning much c# in your current way.
@minor raptor If you understand things like functions, variables, syntax, etc you should be fine to learn with Unity
anyone know how to instantiate a prefab after clicking a button at a custom position I can set?
You will need to use Instantiate() in a script
Split your problems into steps. This is 2 different problems in 1
1 is about instantiating at a position
2 is about doing something when a button is pressed
Which do you struggle with
instantiating at a position
Ok
Also, most of the docs have 1 or more examples for each function. You can just read up on this most of the time yourself.
how to make the rb.velocity of an object equal to the transform.translate() of another?
1 velocity along an axis should be 1 unit per second of the same axis of translation as far as I know
But you can just 
yo how do I paste a code here
!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.
rb.velocity = (Vector3.left * speed);
transform.Translate(speed * Time.deltaTime * Vector3.left);
like this?
Sure
🤷♂️
Read?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Idk
does it want me to say cs or what
Hey, guys! Do I have to save all my values in player prefs inside a single method or do I have to use PlayerPrefs.SetFloat etc on other methods and not all of them on a single one?
Yeah, exactly what it describes there, 3 backticks + cs, then code, then 3 more backticks
But you already posted a link... so no. Just use what you did
Yes, do that if you post short code here next time
public class MyClass()
using System.Collections.Generic;
using UnityEngine;
public class WavesLogic : MonoBehaviour {
public float gameTime = 0 ;
public float spawnDuration = 3;
public float deSpawnDuration = 3;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("Timer", 0,1);
InvokeRepeating("SpawnElements", 0, spawnDuration);
}
void Timer()
{
gameTime++;
if (gameTime == 60)
{
spawnDuration = 2;
spawnDuration = 2;
}
if (gameTime == 120)
{
spawnDuration = 1;
spawnDuration = 1;
}
}
void SpawnElements()
{
Invoke("DeSpawnElements", deSpawnDuration);
}
void DeSpawnElements()
{
// Destroy (Elements);
}
}
I have a quick question
Cs on the same line, but yeah thats the idea, now you don't have colours.
If I go ahead and put an instantiate on this wave script
will I need to deal with the position pain again?
basically where do I put a instantiate script on this for 4 different objects
You need to tell it where to instantiate, yes
Otherwise it will at origin I think
What? Can you explain more clearly what you're asking how to do?
What I'm trying to say is do I make a seperate script for instantiate and put both of them in a gameobject?
For what purpose?
!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.
You just need to put it in this script
To spawn an object every 3 seconds and despawn it after 2 seconds after 60 seconds and spawn it for 1 and despawn for 1 after 120 seconds
how do i make this object only move along the x axis?
https://hatebin.com/dirtepkuzq
Not for the wave system
a coroutine would be 1000% simpler than whatever this is
I have zero logic on this ngl
its basically something that you can use to execute code over a specified period time
I'm just tryna make these 4 trashes spawn but not all at the same time along with the wave system script I wrote
like StartCoroutine(SpawnWave()); ?
Yes
But you need to make SpawnWave() an IEnumerator and actually code it
Yh
how do i make this object only move along the x axis?
https://hatebin.com/dirtepkuzq
Vector2 direction = new Vector2(mousePos - transform.position, transform.position);```
im getting an error that tells me i cant convert a vector3 to a float
Vector2 direction = mousePos - transform.position;
direction.y = transform.position.y;
you need to pass x,y, not entire vectors as a parameters
@sterile radish
Vector2 direction = new Vector2(mousePos.x - transform.position.x, transform.position.y);
Happy? lol
lol
there's probably 1001 youtube tutorials that teach this, go look one up
How do I make an instantiated object despawn after a button click?...
You could put all of the objects in a Parent object, then when the button is clicked, iterate through the child objects and destroy them. You could also store them in a list when they're instantiated, iterate the list and destroy them
Store a reference to the instantiated object when you make it, then you can destroy it when a button is pressed
do I use a foreach loop to iterate