#💻┃code-beginner
1 messages · Page 39 of 1
Hey guys, I´ve a question regarding tilemap. Why are the children of the tilemap not in order form bottom left to top right? Is there an option to enable sorting? If not, what would be the easiest way to achieve this?
Thanks
Hmmm... okay, yeah... thanks alot! And any idea how to make that object be a "crosshair" of sorts? So it would make kind of an FP "controller"? In another words... how would I mKe the look object stay "relative" in front of the character? Not by parenting, obviously
.... position + offset?
its actually not really using the tilemap, the prefab brush just nests gameobjects into a tilemap gameobject to organize it, but they're not in the tilemap itself
so the order doesn't really matter, its all about when you drew/brush it in
Yes it's a matter of taking the position, where it's looking at and applying an offset towards that
t.position + (t.forward * distanceInFront)
Thank you very much! You saved my evening ❤️
you can also do t.TransformPoint(Vector3.forward * distance);
🫶
Ok, thanks for the feedback. I use Map Graph to create the map. I think I have to dig deeper and find another way for what I want to do. Thanks again
np. what is it you're trying to do exactly?
Navarone what happened with the pfp with the beautiful hair
its autumn 😛
Okay, in the right place this time.
I'm really confused about this raycasting thing. I've corrected my original code to use the correct way of raycasting. My control panel object is set to its own layer, but the raycast doesn't recognise it as it's own thing, it's returning the name of the 'Root' object. I'm very confused. lol.
[SerializeField] Camera playerCamera;
[SerializeField] int maxRaycastDistance;
[SerializeField] LayerMask interactableLayerMask;
private void Update()
{
RaycastHit hit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.TransformDirection(Vector3.forward), out hit, maxRaycastDistance, interactableLayerMask))
{
Debug.Log("I hit : " + hit.transform.gameObject.name);
}
}
It's been a while since I've done any interaction stuff, so seem to have forgotten a bunch.
hit.transform is your problem
If there's a Rigidbody on the root object it will jump up and grab that
if you want the exact object you hit, use hit.collider
Oh bloody hell, of course it is, thank you.
hit.transform is a little too smart for its own good sometimes.
Yeah, thanks though, one of those little things I forgot. lol.
minor thing but, you can use playerCamera.transform.forward, you do not need to manually calculate it with the TransformDirection method
@slender sinew Ah cool. Thanks for that. 🙂
Next hurdle. (I know an interface is probably better for this, but I don't know anything about them at the moment, that's tomorrows homework. lol)
I have a script on my 'target' object that has a public method that switches a bool. How can I go about 'grabbing' that from the interact script and switching the bool? I know how to get a reference to a script, but as far as I know you need to know the name of the script?
yes, you do need to know the name of the script
and you are right that an interface is probably better
well that's precisely why an interface is better
Yeah, it's too late and I'm too tired to learn about them tonight. lol.
if you had an interface such as IInteractable that had a method called Interact(), and your target object's script derived from that interface, your player interact script could run some simple code like
if (hitThing.TryGetComponent(out IInteractable interactable))
interactable.Interact();
Using GetComponent/TryGetComponent and calling the function
Also I generally don't even use an interface. I just have a general purpose Interactable MonoBehaviour script that I just slap on any interactable object
You can give it a UnityEvent to actually define the behavior
e.g.
public class Interactable : MonoBehaviour {
public UnityEvent OnInteract;
public void Interact() {
OnInteract.Invoke();
}
}```
yeah the composition approach is probably best
I'll be honest, I kinda glassed over a bit there. lol, long ass day. Just looking at the GetComponent/TryGetComponent stuff.
Thanks again, worked like a charm!
@wintry quarry Okay I actually prefer the interactable class idea better. Just looking at the Unity Docs on the UnityEvents thing but not entirely sure where the 'OnInteract' behaviour is defined. Unity Docs don't seem to be helpful (or I'm missing it lol.)
It's defined in the inspector
Ooooooh, I get you.
It will work just like how UI buttons work
or anything else with a UnityEvent
it can also be assigned at runtime with OnInteract.AddListener
Gotcha, thanks, sorry running a bit slow atm. lol.
no worries
Hey this might be a random answer
to the problem u are facing but giving the fact that u are using a camera with your ray Casting and if u get an error such as ("null reference to object or smth") make sure ur camera is set as the main camera in the tag just thought I'd tell u this given the fact it happens commonly when using camera with ray casting or other scripts
Nothing in this code uses Camera.main so the tag is irrelevant
Thought his playerCamera could be set up as one said just in case
They included the declaration of the variable in the snippet
Thanks for the input guys, all very helpful 🙂
@wintry quarry Hope you don't mind dude, just want to be sure I'm getting this right. lol.
And then I grab a reference to the interactable script and trigger the Interaction() Method?
Yaaaaay, it works. lol. Thanks man, really appreciate it. 🙂 Very cool way of doing it too 🙂
yep - and now you don't need to rewrite this logic ever again
Whats wrong with the base.start and select entered?
i don't see any error for base.Start . . .
the second function in this screenshot has no return type
also there's some other error above
that is cut off
= ga something has an error
What do the errors say
best to display the actual error for us to see and the entire code . . .
basic syntax errors
So, what do the errors say
missing semicolon.
assigning a GameObject value to a string variable
missing the entire rest of the function definition on line 21
Hmmm, I have an issue. I have an ObectPool<T> class that can recycle objects. When an object is recycled, it's appropriately despawned, reset (its state), and spawned again. However, the variable that referenced the object before recycling is still attached to the newly recycled object. How can I remove the variable reference when recycling?
either with an event from the pool object that fires when it gets deactivated or you let the object that is referencing it handle the deactivation
whats wrong with base.start
Missing semicolon
Assigning gameObject to a string
Start isn't an override
basic != base
IDk you tell us
is there an error?
What does the error say?
I highly recommend not doing a XR game as your very first project
Heyy, hi everyone, does someone know if is there any way to use bloom just for a specific kind of objects? Cause I've applied it to all the scene... But i just wanna have it on lamps... not on the skybox. Im currently using a URP project
you might be able to render the skybox separately and composite things together
alternatively, just make the lamps brighter and then adjust the bloom threshold
so that the sky isn't bloomed
the real key to this is, yeah what Fen said
basically your lamps are too dim and/or your sky is too bright
Anyway this is a #💥┃post-processing and/or #archived-lighting question.
so, its really difficult to do that?
here's an example test: https://hatebin.com/isouqhfudd
I considered passing the variable reference as an argument to the Get method, which will add a delegate to the internal OnDespawn event that will assign the variable to null . . .
Thats another thing, is it possible to reduce the skybox bright from unity?
of course
Window -> Environment -> Lighting
oh, i've done it doing reducing the exposure of the image
That will adjust how intense the light from the skybox texture is
you might turn down the exposure, then turn up the Intensity Multiplier on the environment lighting
that will let you make the sky darker whilst still providing the same ambient light
if you have a specific problem with it you can post the details here and get help #854851968446365696
you'll have to explain how it's supposed to work and in what way it's broken.
"it doesn't work" does not tell us anything
since you're, presumably, here because it doesn't work
if i use .normalized on a vector it should only return 1,0 or -1 ? Cause i keep normalizing my vector and getting weird numbers
no it will return a vector of length 1
but the individual x, y, z components of that vector can and will have any values between -1 and 1
for example (~.7808, .~7808, 0) is roughy a normalized vector
what happened to the one you shared a few minutes ago?
how can i set the value only to 1,0 or -1 then because i want to use the vector as a direction
.normalized
The vector is already a direction, it doesn't need to only have 1, 0, or -1 to be a direction
if you only want horizontal or vertical directions that's a different story
oki thats what im looking for i was searching the wrong thing thank you
wdym by "resets"?
what even
well, i don't know about that game, but you often "reset" a game by just reloading the scene
Which, by the way, is what the script you showed us earlier did, @queen adder
this is not a mascot horror enthusiast server. you will have to explain what you want
direction = (GameManager.mousePosition - transform.position).normalized; so this should return a normalized vector ?
yes
Well it doesnt :(
How do you know
I think it does
you just don't know what normalized means
Debug.log
which is printing what?
what did it log
show the code and show the output
` direction = (GameManager.mousePosition - transform.position).normalized;
Debug.Log(direction);`
and that printed what exactly?
Okay and what did it log
you have said this like 5 times
(0.24,-0.19,0)
that's normalised
it isn't but
How do you know this was actually logged from that Debug.log?
Also did you simplify the code from your script at all
its the only debug.log i have
because if the code is just what you said and it printed that, well I don't believe you
actually I think I know the problem here
direction = (GameManager.mousePosition - transform.position).normalized;
Debug.Log($"Direction vector: {direction}, magnitude {direction.magnitude}");
Put this in and then show a screenshot of the log
one of these vectors is probably a Vector2
so somewhere a z coordinate is getting lopped off
omg you might be right
direction is not a v2
its a v3 anyways i gotta go thank you tho ill bash my head against it later ahah
if i reference a prefab, will it only be useful to instantiate it or can i use it to modify the same prefabs already in the scene
like for instance
can i make an array for all the item slot prefabs that are in the scene?
You can modify the prefab, which is not particularly useful
changing a prefab at runtime won't update any instantiated versions of that prefab
how do i reference all the slots in the inventory to then have the item icon in the slot be able to change
and put them in an array
or list
To make this answer clearer think about this:
- There's no such thing as a prefab in the scene. The prefab is only the asset that lives in the project folder.
If you want to reference all the instances in the scene you need a collection of some kind, yes
If you want a list of all of the things spawned from a specific prefab add them to the list as you spawn them
i thought so
Heeey guys. I want to make a game where user will see figure and will try to draw something similar. Could someone point me some direction ?
you will basically need machine learning or something for a game like this
the inventory slots already exist i just need to have them all in an array but i don't know how to reference them
That suscks ;/
public InventorySlot[] slots;``` drag and drop in the inspector
If they're spawned from prefabs during the game, add them as you spawn them
drag each slot in?
ok
also
i know i can select many with ctrl
but how do i select a bunch all in 1 section
thanks
Is there a way to code shadow distance with URP?
Not sure, but can't you just change the angle of the directional light?
It has a day and night system.
so im trying to make sort of a Darksouls roll kinda thing. its top down 2D. how would i add force in the direction im moving?
You can constantly change the angle
Hi! I'm not sure if I'm asking too much, but I've written a code to move a player in Unity using the "Input System" package. Everything works fine, but I've added a variable called "speed" to control the player's speed. However, my player remains very slow regardless of the value of the "speed" variable. If any of you could shed some light on the matter, I would greatly appreciate it.
please send the c# script so i can look at it :)
all the script or just the line who called speed?
Yo guys!! all fine? I'm trying to make the Rig in the car but when I play, I notice that the car's wheels don't move together with the wheel collider, how can I make the wheels move together with the wheel collider?
I've included the most important lines for my issue; I've been grappling with this for 3 hours now. 😅
maybe following a youtube video or looking on the web is you best bet
there are thousands of videos covering movement online
I did this by following a video x)
Someone can help me pls?
Show the full !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.
I just wanna make my wheel follow the wheel collider
"I would like to be able to
Ty!!
ok!
okay ill attempt to help you. can you please further explain what your issue is?
I'm trying to make the Rig in the car but when I play, I notice that the car's wheels don't move together with the wheel collider, how can I make the wheels move together with the wheel collider?
When i play, the mesh wheel dont follow Wheel Collider's movement
!code, use a bin
like the suspensions movement
📃 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.
discord embedded text can't be searched
well can you maybe double-check the heirachy of the game objects? and maybe make a video showcasing exactly what the problem is
like that ?test ?
Use a bin site
let me 5 min to anderstand how it works ^^
tell me if Im true, I copy paste the url ?
You paste it, save it, and send the URL
here it is : https://paste.ofcode.org/QvmQnR8YZN943yCq7bgXGJ
And can you send a screenshot of the inspector of this script
Can I have an exemple of an inspector ? Sorry if I'm slow or asking maybe silly questions, I'm new and learning
The place where you put in values for your variables on this script
this?
this is a single component in the inspector, yes.
ow, speed isnt the same here wow
So, your speed here is 5, what happens if you increase it
the field initializer in your script provides a default value, but unity remembers the values in the inspector
You solved an issue I've had for 2 hours, I didn't think to change it here! I've been modifying it in the script all along, updating it, I feel foolish!! thx
Why didn't changing the value in the script and refreshing update the value in Unity?
thx ❤️
The reason it shows up in the inspector at all is so you can have multiple instances of this script with different values
So it wouldn't make sense if they all used the default value in the script
Does anyone know why this isnt working? The object has a collider with is trigger on and the player also has a collider. Both have rigid bodies.
even this isnt working
Have you made sure that the player game-object has the tag "Player" ?
by the way, if you are using 2D, then you have to write private void OnTriggerEnter2D(Collider2D other)
please provide the line 17 of the script
https://hatebin.com/qfopvjcqbq
so i have a start on my inventory but im not sure what to do next
i have an array for each inventory slot GameObject
and a List<> for the items in the inventory
but im not sure how to make the list of items inside of the inventory slots
y = Input.GetAxisRaw("Vertical");
sprinting = (x + y != 0);
jumping = Input.GetButton("Jump");
crouching = Input.GetKey(KeyCode.LeftControl);
Debug.Log(sprinting);``` why is "sprinting" returning true when i dont press any of the horizontal or vertical axis buttons
Okay so im trying to make my car tilt whenever i turn, and i cant make it work. I thought about making an anchor point to the cars as a child but idk how to implement it
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
public float MoveSpeed = 50f; // Acceleration
public float MaxSpeed = 15f; // Max Speed
public float Drag = 0.99f; // Friction
public float SteerAngle = 20f; // Steering angle
public float Traction = 1f;
public float MaxTiltAngle = 25f;
public float currentSteerAngle;
public float rotateSpeed = 10f;
[SerializeField]
public GameObject TiltAnchor;
public float curveAmount = 20.0f;
private Vector3 MoveForce; // speed
void Update()
{
//Moving
MoveForce += transform.forward * MoveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += MoveForce * Time.deltaTime;
//Steering
float steerInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * steerInput * MoveForce.magnitude * SteerAngle * Time.deltaTime);
// Tilt
currentSteerAngle = MaxTiltAngle * steerInput;
if (currentSteerAngle < 0)
{
TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, curveAmount), rotateSpeed * Time.deltaTime);
}
if (currentSteerAngle > 0)
{
Debug.Log("Tilting");
TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, -curveAmount), rotateSpeed * Time.deltaTime);
}
if (currentSteerAngle == 0)
{
TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, 0.0f), rotateSpeed * Time.deltaTime);
}
}
}
nvm animator was disabled
do you have reload scene stuck in update somewhere
time to debug the logic that makes your scene reload.
determine what conditions must be met for it to happen
direction = new Vector3(0.3f,-0.3f,0).normalized; direction should be (1,-1,0) but returns (0.71,-0.71,0). This cant be right ?
Show your code. Did you try to override start? Do base.Start()?
Oh, this is the code from earlier
Yeah, don't do base.Start()
That makes no sense when inheriting from MonoBehaviour
MonoBehaviour DOES NOT HAVE a start method (as your error clearly states)
Also there are the other errors that have been pointed out twice
https://hatebin.com/nvblciyaop
the item will show up in the slot of the inventory, but it replaces the item slot entirely with it even though in line 52 i had it use the child objects image
what did i do wrong?
It’s correct, normalizing a vector makes it so it’s length is 1
the item automatically goes in the inventories 5th slot for testing purposes
Here’s a visual
bump
foreach (ItemData itemInInv in itemsInInventory) { var itemSlot = inventorySlots[5].GetComponentInChildren<Image>(); itemSlot.sprite = itemInInv.icon; //Here I will make the items in the inventory actually show up in their slots, inventorySlots array is the slots }
the item sprite appears in the parent object not the child's
im unsure what im doing wrong
https://unity.huh.how/programming/player-movement/diagonal-movement
If pumpkin's diagram didn't do it for you
GetComponentInChildren grabs the first component it can find
inventorySlots should be an array of a component that has a reference to the Image you want
i.e. an array of InventorySlot or something
also, GetComponentInChildren can get a component from the game object you called it on
It finds a component in the object or any of its children
Same deal for GetComponentInParent
i decided to swap the inventory slot array to be just the child object that only has an image, cause the slots behind are just there to be designs so theres no reason to have them be referenced
now it works fine
but when the icon appears its sized very smushed instead of making itself smaller
how could i fix this?
you could keep the frames if you just stopped using GetComponentInChildren...
it'd also make your life easier later. you could ask an item slot what item it's holding, for example
Is the image scaled down? You should probably use the rect tool to resize it to be smaller
Its cause the item itself had a very odd size which none of the rest of the game used (i downloaded a random weapon design to test things around with)
but i replaced with something i made thats scaled correctly and its all good
https://hatebin.com/eplnieyoar - code
alright so everything from before works perfectly now, now how would i set which inventory slot the items go into, id want an item when added to go in the next open one from 0 -> 36
like
line 54
var itemSlot = inventorySlots[5].GetComponent<Image>();
i have in part of the script the inventory items list checks if the item being added fits or not
No . You use the debug.draw stuff. Look it up
im trying to set i to true whenever a player switches to home scene, but i also want it to be true when they leave that scene, basically make the i = true outside of the if statement only if the if statement was true once, im a beginner sorry if this is silly, any help would be appriciated thanks
You should probably start by looking up how to detect when you change scene or when a scene is loaded
I don't understand your question btw.
yeah i wrote it in a weird way
thanks though ill look it up
i havent thought about that
Usually if you're thinking "I want X when Y happens", you look up how to detect when Y happens, or how to make it happen
got it, thanks for ur help
u can subscribe to event instead of checking it in update I forgor which one tho one sec
UnityEngine.SceneManagement.SceneManager.activeSceneChanged
that is the event you want
public void ListItems() { foreach (ItemData itemInInv in itemsInInventory) { for (int i = 0; i < inventorySlots.Length; i++) //Checks for space in inventory { var itemSlot = inventorySlots[i].GetComponent<Image>(); itemSlot.sprite = itemInInv.icon; //Here I will make the items in the inventory actually show up in their slots, inventorySlots array is the slots } } }
currently a single item in the inventory fills every spot, due to the fact it enters a loop where its placed in each
how can i make it so that each itemInInv in ItemsInInventory enters the loop once
break keyword ends the loop early if thats what u want
but you really just need one for loop I assume u gonna extend it into something that need second
lol i fixed this issue 2 days ago
instead i use continue;
but now
public void ListItems() { foreach (ItemData itemInInv in itemsInInventory) { for (int i = 0; i < inventorySlots.Length; i++) //Checks for space in inventory { if (inventorySlots[i].GetComponent<Image>() == null) //Slot is open { Debug.Log("Item Slot Open"); var itemSlot = inventorySlots[i].GetComponent<Image>(); itemSlot.sprite = itemInInv.icon; } else //Slot is taken { Debug.Log("Item Slot Taken"); continue; } } }
It always detects slots as being taken
even when their not
so it must be a logistics issue
what ur doing here is checking if your inventory slot has image component and if it does it is taken
continue skips whatever is past it in a loop so it being the last statement is redundant
oh
should i be checking for sprite then?
cause by default that's empty
expecting to be filled
u should have some kind of bool or whatever to check if it is taken or not
I wouldn't check for a sprite
yea
true, slot is open false, slot is full
how would i find out whether the slot is taken or not?
is this a list or an array
what is inventorySlots rn?
So technically, if you have an index unoccupied, then it should just be null
all elements are filled
if you create array of like size 10 and dont set anything are indexes null? thats my question not to u btw 
then the elements image is filled with the items sprite
Ah, ok so you got a wrapper for the slots, and you populate the wrapper?
Sure, if it works for you. I don't see anything wrong with that.
so it works but now a single item still fills in every single slot
it's better tho
https://hatebin.com/sjbtsrrqph - whole script
a single item goes through the loop filling in every slot
You need to break out of your loops once you detect an open slot you can fill
yeah
it still causes one item to appear multiple times
even tho the loop should break
you've two loops there. What's the outer loop for? I assume it was some subcontainer.
the else?
the foreach is so every item in the inventory list goes through it
then for - is so that every item will take the next slot in the inventory
Little confused. You've got a list for all items in your inventory, but you also have a reference to all slots that contain those items?
list that contains every item in the inventory, so each element is the actual item (scriptable object) that has an icon
then an array that each element is the image where the item in the inventory will go
Ah, ok so this is like loading a set of items into all your slots
yeah a single item thats in the inventory going through the loop is filling every slot in the physical inventory
instead of breaking out like it should be
Seems fine, debug what items you're inserting into the inventory is correct.
wdym?
what in the world
oh wait let me think of this, gimmi a second. For loop inside of a foreach a little confusing.
the single item in the inventory filled in like 20 out of 36 slots and stopped
Well, for one, you reset the increment of the forloop everytime you break, meaning you have to go back to the start and check all the slots you just filled. But, it should still work assuming all the data you're putting into it is different.
so everytime i add a single item into it and the inventory is opened
its random how many items fill in each slot
one time it was 14 - it never fills just 14 in anymore i tried testing it multiple times, always filled every slot
but now it just fills every slot everytime
Well, what you have here should work. When you call ListItems(), it's taking whatever data is in itemsInInventory, then looping through each item in that container. In your forloop, it's checking for a slot, and when it finds a slot where there is a null sprite, it'll change that sprite to the current item then breaks. Repeat for next item; starting at the first inventory slot again.
start debugging the actual data you're inserting and not just by logging strings
im gonna test to see if the invententory slots are all connected therefore changing with each other
ok i think that was the issue
nevermind i just made a dumb mistake
how do i debug the data
Debug.Log(data)
you'd want to grab the current sprite data probably
otherwise it'll just continue to give you the type of object which is just the item
yeah
im not sure how to do this
ive never done it before
You are doing it there, but for just strings
foreach (ItemData itemInInv in itemsInInventory)
{
Debug.Log(itemInInv.icon);
}```
oh
think that gives the sprite name I think?
why is it named ItemsInInventory? isn't it just the Inventory? seems weird to see itemInInv and itemsInInventory. looks confusing, at least, to me . . .
it did
seems like they're just loading their inventory with items
it gave me 32 different messages
each the same item
even though theres only 1 in the inventory
no
1 item in the inventory's item list
and it ran the foreach (item in ItemsInInventory) enough times to act like it was in there 32 times
OH I GOT IT
ok so
i realized the issue wasnt from that
it was from when the inventory was opened
this is the menu opener
public GameObject[] inventorySlots = new GameObject[36]; //GameObject of each inventory slot```
How are you even getting an image component. I'm so confused.
and if i held down tab it would keep adding more and more continuosly running the ListItems(); method
its confusing but it does get it
it goes through a few hoops
anyways i basically just need a better place for the ListItems(); method to be run
When you new this here, you're making a whole new set of naked GOs, and I'm not seeing where you're giving them images.
GO ?
gameobject
var itemSlot = inventorySlots[i].GetComponent<Image>();
itemSlot.sprite = itemListInv.icon;
so idk what your confused abt
the slot gets the sprite of the item from
itemListinv.icon;
aka
https://hatebin.com/eokfeecedu - scriptable object
the items scriptableobject "icon" field which contains a sprite
If you're just getting the image component from all of these objects that should be the type of your array
everything i have is working fine
i just dont know where to have my method that displays the item's in the inventory
What you have currently has you calling an incredibly slow get component 30 times a frame that can literally be avoided by changing one word
oh
oh yeah your right im slow
https://hst.sh/edudowozik.csharp am I blind why it doesnt destroy all childs u can see correct child count and correct amount of slots generated as logs so how do I end up with more of them
Instead of a foreach loop try a reversed for loop.
huh that worked
u normally get collection edited bs if thats the problem so didnt even check
ty
Probably because transform is not a collection. It returns a new enumerable every iteration, I'd assume.
but then how I didnt get out of bounds or anything, I had normal for loop previously with same exact behaviour so I would definitely try get child which isnt there anymore
{
[SerializeField] Transform EquipmentsParent;
[SerializeField] EquipmentSlots[] EquipmentSlots;
private void OnValidate()
{
EquipmentSlots = EquipmentsParent.GetComponentsInChildren<EquipmentSlots>();
}
}``` i dont understand what is wrong with this, can someone help?
EquipmentsParent is null and you call getcomponentXX on it
wym?
EquipmentsParent is null, as in nonexistent, or empty. There is no instance of an object assigned to it
Yet, you try to get the EquipmentSlots component from its children.
would this not mean it works?
In your hierarchy, type t:EquipmentPanel into the search
Do you have more than one of that script?
Also, show that inspector again at runime if that is the inly copy of that script
can someone help? usually when you move your mouse up and down, the camera rotates along the x axis but mine rotats along the z axis https://hatebin.com/dzucbktiqp
what is a good way to globally check if the keyboard focus is being captured by an input field?
This is kind if hard do explain, but does anyone know how to make a list that kind-of creates its own points as you unlock them? kind of like an inventory but instead of pictures its words. does that make sense or do i need to try and make a better explination
nope
how would you make a for loop go down a list for some reason i cant find anything anywhere lol
unless i dumb
for some reason the for loop isnt able to go over 1
what's this underline about?
you must be returning or breaking in every possible iteration of the loop
presumably, at the end of the loop outside of your screenshot
hey guys, i have this game called "It's Raining Cubes" in this i catch cubes falling from above . i want to count the score (how many cubes are falling between two platforms i) to do that i have created a empty game object and made it child of the platform game object , but now to count score i have to make a new gameobject called "GameManager"(with GameManager script attached to it) but i dont know how to access ScoreLine in GameManager script which is attached to a completely different object, any idea how i can access that object( collision of that object to count score). sorry the ScoreLIne object is child object of player parent object
Well I had another system where all the (tile) gameobjects where under a mapParent. They were in order from bottomLeft to topRight and therefore I could get them by mapParent.transform.GetChild(childIndex);
With tilemap that isn´t the case anymore. I want functions like:
public Transform GetTileGameObject(int childIndex) {}
public Vector2Int GetXYFromChildIndex(int childIndex) {}
public int GetNeighborChildIndex(int currentChildIndex, EMoveDirection eMoveDirection) {}
I´m completly new to tilemap. I saw how RuleTiles work and wanted to switch from my previous system.
Update: Got it working saving the childIndex (which I calculated) and then using the .Sort function.
you there?
hello i need help with an bug that is happening in my editor. In my script i initialize 4 lists and when i press play it moves objects in the list around (this is only seen in the inspector), however when i exit play mode 2 of the lists don't reset to their original values and one of them entirely disappears. I also get a reoccurring error. this happens until i press play again and it returns to the default values as it should and the errors disappear. NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <a26505b064194c429b83f4a02cfddb4d>:0)
Share your code
sorry what is a good bin site so i dont have to send screenshots
!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.
Huh what is it now??
"error CS1504: Source file 'C:\Users\SuperNinja313\Documents\Unity Projects\Learn\Assets/Scripts/CodeNo1.cs' could not be opened -- The process cannot access the file 'C:\Users\SuperNinja313\Documents\Unity Projects\Learn\Assets\Scripts\CodeNo1.cs' because it is being used by another process."
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Your code tried to access a file that is locked/used by another process.
Wut- It's just Unity and Visual Studio, should I restart Visual Studio? It's updating, maybe that's the reason?
What file are you trying to access?
do you have any ideas?
There's literally nothing in the code, I just created it.
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class CodeNo1 : MonoBehaviour
{
public string firstName;
public string lastName;
private TextMeshProUGUI textEdit;
// Start is called before the first frame update
void Start()
{
textEdit = GetComponent<TextMeshProUGUI>();
textEdit.text = $"Hello {firstName} {lastName}";
}
// Update is called once per frame
void Update()
{
}
}
I don't see anything wrong in the code. Are you using any assets/plugins that modify the inspector? Or do the scripts have custom inspectors/editors?
Is that the whole error? When does it appear?
i have modified any internal scripts and im useing visual studio 2022
Are you or are you not using any assets that add features to the editor? Like Odin inspector.
no im not just a brand new scene with those 2 scripts on a empty
can anyone help me with that error?
i dont really know why its there.
thats what causes the error:
foreach (GameObject claws in Photon.VR.Player.PlayerSpawner.playerTemp.transform)
{
if (claws.gameObject.tag == "ClawLeft")
clawsLeft.Add(claws.gameObject);
if (claws.gameObject.tag == "ClawRight")
clawsRight.Add(claws.gameObject);
}
Okay, does the error appear again after clearing the console?
It's probably a unity ui bug. If it doesn't happen again, just ignore it.
Just today, I opened Unity after a while, restarting the both apps(VS and Unity) Fixed the problem 👍
What's line 73? Do you see the error in the ide?
yes it seems to happen every frame even when outside of playmode
Line 73 is the foreach line
And the second question?
Hmm... Try resetting the windows layout and restarting the editor.
nope bc VS doesnt show errors for some reason
i have already restarted the editor with no avail i dont see how the layout will fix it but its worth a try
alright 1 second
weirdly enough, It seems configured. Maybe because of the version? Looks old.
Anyways, the issue is that you try to iterate GameObjects in the foreach, but transform children are of Transform type.
yeah i already tried it with Transform. then the error is gone but it wont find the claws
Meaning there's some other issue. The correct way is to have the iterator as Transform though.
this didn't work btw
As I said, I don't see any issue with the code. Did you reset the layout?
Okay...🤔
did you see my pictures
Yes
hmmm maybe its the vertion of unity lagging
What version are you using?
i fixed it by doing that instead of foreach
for (int i = 0; i < transform.childCount; i++)
{
if (transform.GetChild(i).tag == "ClawLeft")
{
clawsLeft.Add(transform.GetChild(i).gameObject);
}
if (transform.GetChild(i).tag == "ClawRight")
{
clawsRight.Add(transform.GetChild(i).gameObject);
}
}```
Should be fine.
Can you remove the using Unity.VisualScripting; from one of your scripts?
Can you comment out your code in GameManagerS.Start?
it works when i remove //ns.MoveCards(Deck, Discard1, ns.randomCards(Deck, 1));
//ns.MoveCards(Deck, PlayerHand, ns.randomCards(Deck, Round));
//ns.MoveCards(Deck, BotHand, ns.randomCards(Deck, Round));
but only if i remove all three
where is the NameSpaceIGuess component located?
its on the same object
as GM
randomCards is also fine (it still happened when i removed it)
Can you reference it in the inspector instead of using the find function?
That's weird.
Can you share the error details again? It seems like the third error is different too.
unity support I guess?😅
Mornin' all. First time doing this particular thing, so getting a bit lost. I've got an fps controller, and I'm trying to interact with a button on a world space UI. (camera is firing out a ray etc.) Could anyone point me in the right direction please?
Probably silly question, I have value that can sometimes be positive and sometimes be negative, how to I make it always positive?
Math.Clamp or Abs or something.
By details, I mean the bottom of the console.
NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <a26505b064194c429b83f4a02cfddb4d>:0)
The first error we can work with probably. Share it's details.
And it's possible that it's causing the other errors too
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List1[T].get_Item (System.Int32 index) (at <b89873cb176e44a995a4781c7487d410>:0) NameSpaceIGuess.MoveCards (System.Collections.Generic.List1[T] a, System.Collections.Generic.List1[T] b, System.Collections.Generic.List1[T] indexs) (at Assets/Scripts/NameSpaceIGuess.cs:23)
GameManagerS.Start () (at Assets/Scripts/GameManagerS.cs:34)
Here:
public void MoveCards(List<string> a, List<string> b, List<int> indexs)
{
for (int i = 0;i < indexs.Count;i++)
{
b.Add(a[indexs[i]]);
a.Remove(a[indexs[i]]);
}
}
Make sure that a[indexs[i] is >= 0 and < a.Count.
I'm trying to get a top-down shooter working and normally I would get it working with the old input system. But I can't seem to get it working this time for the new system. How can I fix it?
Remember that after you remove elements from the list, it's indices shift and count is reduced by 1.
so should i add Count/1
You should make sure that the index that you use to access list a is within it's bounds.
Should probably use UI pointer events. raycasts only work with colliders.
I don't think that's the right way to calculate it's rotation.🤔
for starters, you're mixing screen and world space coordinates.
very cheap fix though
by errors i mean the range one not the stupid one
Very weird. That would imply that RandomRange returns negative numbers...
Oh yeah. So is Delta in screen space?
Yeah, though I'm not very knowledgable with the new input system.
i thought that because i was adding first it wouldnt do tht
nevermind its still there
That still doesn't solve the case when index is out of bounds.
Yeah, though so.
It depends on the random numbers that you get.
yeah to good to be true
Here's a tip:
step through your code on paper.
Specifically, with num here int num = Random.Range(0, outOF); being equal to list.Count - 1 twice in a row.
it seems to happen alot because it stopped it doing it if its negative and it only does it twice
ok ill try
Honestly, there's no way it could be negative.
so unity is lagging again
Did you fix the range error?
It's still a delta
in other words difference between current and previous frame
Though the values do look weird
Oh, you transform them
Try printing the raw value.
also, transforming it is not gonna help
im useing print to see num but i cant recreate the negative
As I said, it wouldn't be negative
but it could be bigger or equal to your list count
Would it be better if I had Position instead of Delta for the Input System?
The way you were using it, yes.
yeah got it the deck is 98 and it returned 99
by the time it moves cards to bothand it doesnt look like the list has updated it length
ok im gonna take a break thanks for trying for so long
I told you how to solve the issue already.
The reason is that when you generate the random numbers you don't account for the fact that the list would get smaller after each random element is removed from it. So it can give you a random number that is bigger than the list.
this is what i got... a.Remove(a[indexs[i - indexs.Count]]);
nvm that made it worse
!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.
Lol, why don't you just do what I suggested? clamp the index when you use it, or reduce the random range after each random number.
bro sorry im trying i dont really know how i would clamp the index but i added outOF-- after i add num to cards
If you have to ask I suppose it’s here
ok
Can someone help me i am not able to find the mistake using ```System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Testingscript : MonoBehaviour
{
public GameObject TriggeringObject;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player") && TriggeringObject != null)
{
Debug.Log("Trigger activated");
// You can also perform other actions on the TriggeringObject here.
}
}
} ``` this is my script i have checked the is trigger option to true in the inspector panel of TriggeringObject and also set the Player object tag To Player but still the "Trigger Activated" is not send to console. This script is attached to an empty Gameobject and i have also PLaced the Triggering object in the script
yeah that worked thanks
Hmm, okay, I'm obviously missing something really obvious here. Could someone please take a look and point me in the right direction please? I have a couple of scripts, one that fires a ray out of the camera, and one that 'lives' on an interactable object that simply holds a string. The idea being that when the ray hits the object, the script 'grabs' the script holding the string and relays it to a hud element.
Raycast script ( in Update() )
RaycastHit hit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
{
InteractionMessage interactionInstruction = hit.collider.gameObject.GetComponent<InteractionMessage>();
interactionPrompt.text = interactionInstruction.messageToSend.ToString();
if (Input.GetKeyDown(KeyCode.E)) {
Interactable interaction = hit.collider.gameObject.GetComponent<Interactable>();
interaction.Interaction();
Debug.Log("pow");
}
}
else
{
interactionPrompt.text = "";
}
Message Script (on the 'target' object)
[SerializeField] string interactionMessage;
public string messageToSend;
private void Start()
{
messageToSend = interactionMessage;
}
Issue I'm having is that the raycast script doesn't seem to find the message script (or the string variable). (Null reference exception when the ray hits the target object)
Your script should be attached directly to the object that has the trigger collider not to a empty one.
The trigerring object reference you have does nothing here
yeah but i don't want to do that are there any other ways to make the thing work
Well no. The OnTriggerEnter message will be sent to the object with the trigger collider, not to a random empty object.
alright i guess i will do it simply instead of dealing with complex things
There is no complexity here
How would the system know to send the trigger enter msg to your empty game object when the trigger of another object is entered?
Then what ever your ray is hitting does not have the script
i am telling i would go with ur idea
Again it is not an idea. It is just how the system works in Unity
@charred spoke It's okay I just figured it out. I was being a moron and got my layers mixed up.
I wrote a simple block of code for moving forwards with AddForce but for some reason instead of going forwards like it should do it's moving towards positive Z can someone tell me what's the issue ? here is the code : https://gdl.space/uyidoyedak.cpp
how do i make it so when i click on the tv with the button e, it activates the light in it ?
Vector3.forward is the global z axis. I suppose you want to use transform.forward in your code
You can use a raycast or a trigger collider
@teal viper i figured it out the unfixable bug
well I converted transform to AddForce because I had collision problems with transform
What was it?
No not transform.position
i mean like how will the script go
AddForce(transform.forward*5)
Google unity raycast interaction. Nobody here will write code for you
ok thanks for the help. To be more specific I had problems with transform.Translate
nothing to do with the code at all, it was a corrupt prefab file hiding in the scene. i figured it out when i started a new project with the same code and it worked.
FINALLY WORKING COLLISIONS
Thank you so much for your patience it's really appreciated
uhh..
code that instantiate the particles?
{
if (!base.IsOwner)
return;
if (Input.GetKeyDown(shootKey) && canShoot)
Debug.Log("Shoot");
Shoot();
}
[ServerRpc]
public void SpawnObjectServer(GameObject obj, Vector3 position)
{
GameObject spawned = Instantiate(obj, position, Quaternion.identity);
ServerManager.Spawn(spawned);
}
[ServerRpc]
public void DespawnAllShootParticles()
{
foreach(GameObject particles in GameObject.FindGameObjectsWithTag("ShootParticles"))
{
ServerManager.Despawn(particles);
}
}
void Shoot()
{
ShootServer(damage, shootFrom.position, Camera.main.transform.forward);
shoot.Play();
ShootSoundServer();
deagle.SetTrigger("Shoot");
if (Physics.Raycast(shootFrom.position, Camera.main.transform.forward, out RaycastHit hit, Mathf.Infinity, playerLayer))
{
if (hit.transform.gameObject == this.gameObject) return;
hitS.Play();
}
SpawnObjectServer(shootParticles, shootPoint.position);
StartCoroutine(CanShootUpdater());
}```
brrrrrrrt
You also have an error in the console
yeah thats the one frame that the camera isnt assigned but it assigns it straight after so its fine
where are you calling Shoot() ?
Ah it's this
if (Input.GetKeyDown(shootKey) && canShoot)
Debug.Log("Shoot");
Shoot();
If with no braces { } only take the next statement. So Shoot() is called each frame
Only the log is included in the if
oh yeah i forgot about that
it was happening before i put the debog log
debug log
but ill try again
because that could well be why
Also I wouldnt make the server spawn a gameobject each time a shoot is fired btw
its working now lmaoo im stupid
thanks for help
First you aren't deliting the gameobject and instantiating that many gameobject could cause perfomance and memory isues, you could use object pooling or maybe make that the gun itself has a child wich is the muzzleflash and send a RPC to make it play instead of instantiating a new game object
Well yes. Transform.Translate will complete ignore physics. transform.forward is just a direction. More specifically the local blue axis of the object.
Yep, this ain't python. 
ok ill add a timer before they get deleted
if thats the case, just do Destroy(shootParticles, 1f) or smthn like that
but you have also to destroy it on all clients
ill just a coroutine
are you using Photon?
FishNet
not the best idea but will work
if its not broken its working
take a look at object pooling https://fish-networking.gitbook.io/docs/manual/guides/spawning/object-pooling
doesn't tranform have any definition for stuff like up, forward, back, left and right ?
my console is telling me it doesn't but it seems weird
How do I lerp materials? I tried material.lerp, but that doesnt seem to work correctly, since it doesnt change the material 100% to the second one
yes it does
I'm getting errors anyway ( here is one of them ) : Assets\player scripts\PlayerMovement.cs(30,38): error CS1061: 'Transform' does not contain a definition for 'left' and no accessible extension method 'left' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)
try -transform.right
i dont belive transform.left exists, only .up and .right
so if you want left you do transform.right * -1
or down transform.up * -1
oh I just realised : I thought I had an error on every single transform. things but actually there are only ones about left
it works now?
yeah I'm gonna try that out ty for the help
I tried to write defintions for left and right but it doesn't work and I've got errors now. Here are the lines :
Vector3 left = transform.right * -1; Vector3 back = transform.forward * -1;
i have a question how can I turn on something within a certain area like when i close to it, I can then activate it
cause now when i click e from any distance it turns on automatically
i want it so i'm within near the area i can activate it
The easiest way would be using a trigger around your player, or checking the distance between you and the objects
Using the Trigger you can enable objects when they are inside and disable them when they are outside
how do i check the distance ?
I fixed the errors by switching transform.left to just Vector3.left (back one works fine though) but if I try going left I'll just go towards negative X
Hello im a beginner at unity what can i use if i want LAN Multiplayer (2d Game)
You learn Unity without any kind of multiplayer first. Adding a networking stack significantly complexifies the whole thing
@north kiln (`using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class cameraworks : MonoBehaviour {
[SerializeField] private Vector3 _offset;
[SerializeField] private Transform target;
[SerializeField] private float Smoothtime;
private Vector3 _currentvelocity = Vector3.zero;
private void Awake()
{
_offset = transform.position - target.position;
}
private void LateUpdate()
{
Vector3 _targetposition = target.position + _offset;
transform.position = Vector3.SmoothDamp(transform.position, target.position,ref _currentvelocity ,Smoothtime);
}
} `)
You are not using your target position variable
Hi everyone, I have an campfire prefab with this script attached to it: https://hastebin.com/share/xasaqaqebo.csharp in that script it says when player is inside of trigger of an campfire and he is pressing "E", and he has enough wood to make a campfire(woodCount >=3) it will make a campfire and it should take away 3 wood cause campfire costs 3 wood but the problem is it takes away for example i have 6 wood collected and i make a campfire it will take away all 6 woods for some reason. Can someone help me with that? This is script where I count wood: https://hastebin.com/share/zuyotiqici.csharp
your using OnTriggerStay, which means the code in that will happen every frame the player is inside that trigger. you probably want OnTriggerEnter instead
but then I need to click "E" exactly when I enter trigger right?
You're taking the wood in OnTriggerStay. So if you get in range of the campfire and hold E for more than 0.02 seconds, it's going to take 6 wood items
3 wood each 0.02 seconds
You need a variable that stores whether the campfire was already lit, and don't light up the campfire again if it's the case
^, Also, If you didn't know, Input.GetKey is a thing, which just checks if it's being pressed that frame, and not if it was pressed for the first time that frame like GetKeyDown
inside campfire script?
Of course
Input.GetKey is kinda the equivilent to OnTriggerStay if that makes sense
private bool isLit; and then if (ePressed && !isLit)
If E is pressed and it's not lit yet
Then set isLit = true
How to I do that?
my oculus quest 2 game is very laggy and i need help
I built it on my Quest 2 and its very laggy, i tried changing some settings and stuff but it dosent really work
The second if does not prevent the first one to be executed here. Code runs from top to bottom
it works now
Quest 2 games are very difficult to get running well because it needs to be at a stable 90fps or higher running off the quest 2's hardware. You might need more experience in how Unity works as a whole to help figure out how to optimise for it
but also when I press "E" and im inside of an box collider set to trigger in campfire prefab it doesnt always make a campfire its laggy i need to touch box collider thats not set to trigger, how can i fix that?
Now you don't need the last if statement
okay i will remove it
i made a game and it runs smooth with link, but when i build it on the quest its laggy and barely playable.
Your computer is likely a lot better than the quest's hardware
i think its the settings maybe, but i dont know its my first project
this is what my campfire looks like and bigger collider is set to trigger and smaller isnt but for some reason i have to touch the smaller one to make campfire not the big one
you see here im inside of collider and im pressing e but wont do it
Anyone have an idea what to do?
.
is there a tutorial out there somewhere that encapsulates how to preserve data ( like amount of ammo and hp left from level1) into another level?
and if you tell me that i shouldnt do it because i dont have experience you are a little funny man
@north kiln
DontDestroyOnLoad / save files ?
well yea but would it work if my player spawns in another area each time
Oh ok srry I get you now (I'm an idiot)
you see here im inside of collider and im pressing e but wont do it, https://cdn.discordapp.com/attachments/497874004401586176/1165252985702588497/image.png?ex=65462d69&is=6533b869&hm=36b9a0da6884dd3e82845144b885e9720f7cd0414b911cee5b356ad9cf8fbcd3&
can someone help with that
Someone might have a more comprehensive suggestion but my first implementation for doing stuff like that was having a singleton GameManager for my scenes and whatnot but then having a dontdestroyonload GlobalManager singletonthat exists throughout all scenes. then passing and grabbing data between the two singletons like that
Depends what is your setup
Is you want to spawn a new player on each level change then either just use a temp save file or make a script only used as a data container and preserve a singleton of that
i have a fps shooter dude that needs to move to an end area to get to the next level, and i have to preserve the hp and ammo remaining each time, the player is a prefab and i guess i gotta make it consistent as he goes thru each level with one clip of ammo
i see
have you made sure that your collision detection script is correct?
this script is on campfire object
looks like it should work. try checking if the values change as expected, by putting them in a Debug.Log()
first figure out if it enters the collision, and then if isEpressed, and then the last if statement
Turns out I didn't get you
So I does require explanation srry
everrthing works in IgniteStartHealing();
see here
its inside collider and E is pressed but nothing happens, it only works sometimes like when I touch the smaller collider but that collider is not set on trigger
hmm, then look for the script that makes the e-key turn isEpressed = true
that must be where the issue it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
this is code @rotund garnet
where u see when i click e
if im gonna do a dontdestroyonload do i put it at the counter of the ammo and hp or on the player (who has these values)
You could put it on the player, but then make sure to not spawn any additional players
i see thank youu
hmmm yeah, it all looks fine to me, try to log something inside the if statements regarding the keyDown, just to make 100% sure that they do indeed detect it
Unless ammo and health are for some reason references to some other gameobjects (?) scripts, then these won't be preserved. If these are normal fields on the player script / child of player then all is fine
Thank you
what would be a better way to implement dontdestroyonload
Then just go for a temp file save, less complicated.
Load the file on Awake or something
alr alr ill try thank youu
Or a script acting as a container for this data, whatever suits you
could be created just before a scene change and initialized with current data
on scene changed use this data to initialized newly spawned GOs and then delete it
basically a temp save file but as a GO
whatever suits you best
(or a scriptable object)
(but I'm not sure about that one)
@rotund garnet you see here it worked but when i was slightly on the left or anywhere else it didnt work, idk why cause i was every time inside collider...its buggy idk why is that
im not sure why that doesent work then. how does the colliders look?
In a tutorial it said to turn shaders off, but it isnt the same for me as in the video
player collider and campfire collider here @rotund garnet
is your player collider box set as "is Trigger" ?
no
try that
i set it to trigger and as you can see both are touching and im pressing e but still nothing
should the orange on player outline not collide with the campfire outline?
i want player to be able to set campfire the moment he is inside campfire trigger and thats bigger box collider thats set to trigger
hmm i cant tell what your problem is then. try to make sure that the desired collider is on the correct object
is there any definite way to stop objects from getting inside colliders, or pushing them out when they do? Making a game with magnets and they keep trying to go through walls when attracted
i'm moving the objects with addforce
Continuous collision detection.
that worked, thanks
the objects can also be pushed into walls with a little struggle, is there no way to prevent that?
You could try reducing the physics simulation step, but that might take more resources.
Games are a simulation of reality, which breaks at certain extremes. You either consume more procesing resources to make it more precise or avoid these extreme cases.
I have a list of objects referenced by interface List<IUnit>, and it might happen that unit will be destroyed and elements in that list will be incorrect, so i try to do before operations: "list.RemoveAll(Unit => Unit == null)" but it does not work, inspector shows me thst object is "null"
how should I remove it
how should predicate look?
I think it's because of the interface type. It tried to do equality on IUnit which bypasses Unity's override of == for Objects
You may need to do something like ((Object)unit) == null.
Or declare some IsDestroyed() method in the interface, which checks if gameObject == null or this == null in all the classes that implement this interface. Not sure if that would even work though, Unity object lifetime is weird
yes
when a unity object is destroyed, references to the object don't become null
that would be weird magic
what does ((Object)unit) == null accomplish?
it casts your IUnit into a UnityEngine.Object
but once the object becomes null wouldnt call isdestroyed get NRE?
UnityEngine.Object is the parent type for all unity objects: GameObject, MonoBehaviour, ScriptableObject, etc.
It's the type that defines the special behavior when comparing with null
aa cool
And it's the one that has the override of ==
Once the object is casted to that type, the operator can be used
or did it override Equals? i forget if you can overload ==
potayto potahto
no
the only reason you get an exception when you try to use a destroyed object is because you tried to use a Unity method/property
and Unity throws an exception if you do that
Destruction is not magic. The C# object still exists.
It took me some time to realize that. Unity certainly makes it look like it's magic
Hey how do I make my entire game lock to screen size, for example if the screen is smaller theres unused parts: heres an example
I have had this issue multiple times leading me to quit several projects, i dont know what to google to fix this.
UI anchoring using the Rect Transform
no like how do i lock the screen size
It tells the objects what sides of the screen they are bound to
You can't? In runtime at least
anyone knows why every time i try to open a script it gives me this window
In the Editor it's the dropdown named "Free Aspect" up there
do i change it?
oh tysm it helps
But you should make your UI adaptive to the screen size. Changing the aspect in the Editor will not be reflected in a built executable
From Unity go to Edit > Preferences > External Tools, and make sure Visual Studio is selected in the dropdown. It seems like it's Visual Studio Installer that's currently selected
anyone know how to maek it so when a method is called it changes anothers scripts canvas to be enabled
reference to the Canvas
well define your canvas first
public Canvas MyCanvas
and drag and drop the canvas in the inspector
doesn't matter, you can drag and drop any Canvas in there
oh yea
ill have to give it dif variable name
as i also ahve that same line for the otehr one
but if it works then ty
it doesnt let me drop it in
is it cuz tthey are from different scenes?
@eager elm
yes
do you have two scenes open at the same time?
no
you have two scenes open at the same time
because you can't, yes
You can't do it by dragging and dropping, that is.
You will need another way to find the canvas when the game is running.
such as?
one option would be to make them singletons
something like this
public class GameCanvasSingleton {
public static Canvas gameCanvas;
public Canvas theCanvas;
void Awake() {
gameCanvas = theCanvas;
}
}
You would attach this to the game canvas
When it wakes up, it stores the canvas into a static field
Anyone can now access it at GameCanvasSingleton.gameCanvas
dont really get that and i dotn wanna just copy and paste stuff in so ill find another way thansk tho
I never had to have two scenes open at the same time, are you sure it's necessary?
I didnt even knew thats possible how do u end up with two in edit mode 
idk how to NOT have that
Why does the main menu scene need to reference things in the game scene?
because
when the person click play
the menu scene script needs to disable itself and enable the otehr one
oh ok ill try that
what that wontr work
as the onplaypressed function is on the menu scene woops i mean method not function
what?
you push the play button
the play button calls a method
that method runs SceneManager.LoadScene("Game");
using additive scene loading and trying to do cross-scene references sounds a lot more fiddly than just loaded the game scene
yea im new and i sometimes just do it liek the less efficient way
this is why you should be following some tutorials, so that you learn the normal way to do things..
instead of getting stuck on weird patterns
Greetings, first time here and new to Unity/C#. Please let me know, if I'm in the wrong channel.
Can anyone help me with the following?
I'm using Resources.Load("X") as GameObject, but would like to load it not as GameObject, but as the type the prefab actually is, though the type is not known to the script, yet. Any way to resolve that?
You could make the method generic.
For example...
public T Gimme<T>(string name) where T : UnityEngine.Object {
return Resources.Load<T>(name);
}
It looks like loading 2 scenes at the same time in the editor. It's not possible in the build, so the two scenes wouldn't be loaded at the same time like that.
well, sure, it's possible. you just do additive scene loading.
Unless you're loading them additively, which you shouldn't really.
ah :p
Especially in their case.
I've been helping them in unity talk channel for a while, so I'm sure they're just misunderstanding the workflow with the scenes.
Gimme<Image>("hello"); will try to load an asset named "hello" of type Image
they were apparently unaware that you can just load a scene..
i.e. SceneManager.LoadScene("Game");
so is awake when the scene is opened or the game
ah
It is true that it runs on scene load for objects that are already in the scene, I suppose.
@Fen Thanks, but the "Image" in your example is not known. That seems to be my problem
Really, go through the beginner pathways, or read the manual.
surely someone has to know the type
Its a Prefab in the Assets folder
yea but it is so boring and ive already dont a few big tutorials and just forgotten most of it
I guess I'm trying to find that "someone" 😄
If you don't know the type of the component the object will have, there's almost nothing you can do with the object
Well, we can't make this discord into a google replacement either.
Explain what you're trying to accomplish
Not "load a resource with a type"
What are you trying to make your game do?
Ohh "I" do, but how to get that namespace into my script?
There's some basic level of effort that you need to put into your project.
if you aren't willing to help yourself, then we're going to be hard-pressed to help you either
Basicaly I just want to spawn Prefabs at runtime from a C# script and be able to access the variables of a component script of that Prefab
ive already done a 10 hour tutorial and liek 4 hours of anotehr 10 hour tutorial and neaither was that good so idotn really wanna do any more
Are you just spawning them?
Okay, so not just spawning them.
That's still very vague. Explain what your game is going to do.
I don't want to hear about your attempted solution
I want to hear about your original problem
I'f just been spawning for now and that worked well, now I want to access its script
You don't have to go through tutorials. You can read the manual/api docs.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
And you can easily find the relevant docs page by just googling:
"unity Awake" for example. It's gonna be one of the first results.
should i read all of it rn or only read a section when i encounter that error/ wanna know how to sue it
@Fen Ants crawling around droping pheromones to lay trails. I chose to create a Pheromone prefab for that with a script to modify its scent
Yo, not too sure if this is the right channel: is it possible to make the terrain (the ground) be affected by wind?
Something like in the photo, the snow on the ground is affected by the wind
(then again I'm not too sure this is the correct channel?)
Up to you. API docs you definitely don't need to read through, unless it's just to see what API is available.
so i should continue on my game just use that instead of coming here?
I would suggest starting with the Manual.
It talks about the broad ideas and what components do
Then consult the Scripting API when you need information about how to talk to those components in code
Up to you. You can also ask here if there's something in the docs or manual that you don't understand.
As for the manual, I'd at least skip through it's categories and pages once to know what to look for and where if needed.
specififcally, which bit in the manual
please share your !code properly
📃 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 should use one of the paste sites linked in this bot message.
sure
The manual has some really good information that I completely missed when I first learned Unity
all categoriews?
I never really followed tutorials when I picked Unity up, since I had a lot of programming experience and could intuit a lot of it
yes but should i do the scripting bit, working with unity bit. 2d unity etc?
Yes. Some more advanced or in depth stuff you can skip through, but try to at least remember some names and concepts.
"Working in unity", "UI", "Scripting" is probably a must. And since you're working on 2D, the relevant parts from "unity 2d" too.
ok
UI is one thing that I positively did NOT learn correctly
I only recently figured out how to...actually use Unity UI
instead of just trying random crap until it looked ok
Hello good day
im coding for my character running animation and got a problem with it.
i want my character double its speed when the left shift is pressed.
so i use (if) condition for it , everything is fine when i press left shift, animation will load, i can control it with WASD but my character speed wont double.
this is my code , where have i gone wrong?
https://gdl.space/viyidehace.cs
hmm, it looks ok
although you set the speed after using it, so it'll be delayed by a frame
it wont change at all
Is this the entire script?
It looks cut-off
If it isn't the whole thing, please share the entire script
Movement() isn't closed and using UnityEngine; isn't up top, so I know this isn't the entire script
You should always share the entire thing!
I want to see exactly what you see
You don't need to try to simplify or remove parts
(that can hide problems)
ok il fix it
Also, one thing: what is the value of _speed in the inspector before the game starts?
is it 6?
yes
ok, good
I was wondering if you had set it to 12 in the inspector
Does the value of _speed change in the inspector when you hold shift?
Everything looks good to me. So we need to start doing what i'd call "sanity checks"
checking really basic things
an aside: float TargetAngle = Mathf.Atan2(direction.x, direction.y); is wrong
Atan2 takes Y, then X
also, direction's Y value is always zero
perhaps you meant to do Mathf.Atan2(vertical, horizontal) ?
oh, you don't use TargetAngle
right, that makes more sense. i was wondering how you were moving at all 😛
wait -- is the problem that your character is moving through the world slowly
or is it that the animation is playing at the wrong speed?
oh i think thats the problem thanks
i asked this yesterday but no one responded, does anyone know how to make a list that auto generates points? its hard to describe but thats the best i can put it
i used a tutorial video for it , i wanted when for example player press WD character move at their vectors result
no problem :) - I had the same problem, not too long ago, its an easy one to miss....
It would be best if you can explain us what you want to achieve with this, this might give us some context to help you. Simply put your question is WAY to broad right now
no problem
Explain your original problem.
my character running speed when i press left shift is as same as my character walking
That does not answer my question.
Which one is it?
Is the character's change in position too slow?
Or is this an animation problem?
change in position
basically, you know how on social media you have a friends list or a followers list, kind of like this image. the "list points" are each person. does this make a bit more sense?
no, that doesn't make more sense. I don't know what a "list point" is
are you asking how to display a bunch of items in a vertical list in a UI?
each person

