#💻┃code-beginner
1 messages · Page 459 of 1
whats the current issue?
like this?
yes, because the prefab needs to have it? do i need to put the prefab in the scene and attach the text that way and make it a prefab again maybe?
Wait it's an array?
what do the locks on inspector project and hierchy do
no its alist
Prefabs cannot reference objects in scenes
ahh didnt see its a prefab..dammt cutoff inspector..
Then just AddListener(rollMejoras[0])
i need to make my Text TMP also a prefab?
wtf u have an array of delegates?
no chat gpt made that sorry
You need to set the reference on the object in the scene after you create it
nothing wrong with that though
There is not, though I don't think that's what he has
I want "right -> middle -> left"
but it goes "right -> left"
I wanna make it like subway surfers like when you on the right you need twice input to go to left but in this code it takes one input to go to the left from the right
We all probably suggest not to use chatgpt it will run you astray
Not unheard of, especially since Unity can actually serialize a list of UnityEvents for you to populate in the inspector which is pretty neat
but how would i do that with a prefab?
?the little small locks on top
You wouldn't. You'd set the reference on the instance in the scene after you create it
Define three x positions and then cycle between them--if you put them in an array you can do left xpos = xPositions[(curInd+1) % 3] and if you go left xpos = xPositions[(curInd + 2) % 3]
Prevents you from accidentally dragging them around in the scene view
ah ok
You could just make them an array and switch betweem them
A locked object won't be selected
so i want a text to be displayed when the player dies so i should do this in the player object script?
i pressd play and it deleted the stuff in hiarchy i dont understand why
The button didnt do that
Show a screenshot of your Unity window before and after you hit play
Well what exactly did you press
btw if you're using rigidbody, stick to moving it via rigidbody instead of transform.position
rb.position =
or , rb.velocity . AddForce can work too if you make it velocity mode
Whatever spawns the object should probably set the reference to the text
i have no idea
I dont want it to be smooth
is there a way I can teleport with rigidbody?
its not about being "smooth" its about your collisions being accurate
its just a capsule
oh we can do rb.position?
irrelevant
yes
at least that moves it on the physics loop so its accurate
so i did this and now i get this error "Only assignment, call, increment, decrement, wait, and new object expressions can be used as a statement"
that's not a function
Well yea this doesnt make sense alone, what are you trying to have it do?
Right now you're just accessing the first element and doing nothing with it
You are getting an instance and not doing anything with it
doing what digiholic said gets me this error
do i send the sc in here?
yes
What's the error on this one?
nvm it fixed it didint delete anything
the one i replied to
but i still dont what im pressing to make it delete
thanks tho the script worked
how do i fix the pop ups not poppping up
Edit: Oop misread - ignore me 👍
button.onClick.AddListener(() => rolleMeWatever[0].Invoke());
Ah, I thought your list was of System.Action already, my bad
Navarone has the right answer then
!ide
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
which do click
is it not? (havent tried what navarone said yet, just curious about this)
click the one that matches your editor ?
ah ok
Oh, right, buttons take specifically UnityEvents, not just ordinary Actions. I was wrong about which end of the thing I was wrong about >_>
UnityAction 😢
i want to make it so you bounce of walls and your momentum is kept is there a way to put it on the player instead of putting a bouncy physics material on every wall?
blame google translate on that one
Vector3.Reflect 😛
wdym by that? no its just Unity wrapping their own version of c# Action called UnityAction
im making a 2d game and whenever i have the velocity flipped on collision it works unless you go full speed into a wall
oh sorry i thought you were referencing another thing ignore it
are you making like a ping pong type thing
I try not to rely on physics material when i can, just using reflect so it bounces nice and accurate without losing force
im trying to make a game in the genre of like jump king where its hard and ur constantly moving and i want it that if you hit a wall it just makes you keep going into the other direction
you can just make a move speed and just make it negative when you hit a wall
ive tried it but for some reason when it hits the wall the speed just goes to 0
show code
Can someone tell me why Debug.Log("Trying to spawn an item"); isn't being outputted? (the SpawnItem function doesn't seem to work at all)
!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 havent got to it working on certain angles and only on walls yet
but im assuming the problem will still be there even if i do
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so what is this, normal user input but when they let go of "d" the velocity just keeps going?
and if it hits a wall you want it to flip?
or do you want it to be automatically moving left/right like an NPC
i want it so that when the user clicks d or a it adds speed in that direction and they are always sliding
and if they hit a wall it should just bounce them the other way keeping their momentum'
i think what you gotta do is reset the velocity and add velocity again but in the other direction
unless theres some built in method
so just store the current velocity and use that
GetKeyUp is only true for the first frame that the key is released. so if the h key is released before that other condition is true then the if statement as a whole will be false until the key is pressed and released again after that other condition is true
oh and you don't start the coroutine correctly either
? but there are no problems with detect key thing cus Debug.Log("Cube"); outputs well
if only you'd bothered reading the other message before you replied too
and also next time, you need to provide that context
how can I start it correctly?
have you looked up how to start a coroutine?
Keep in mind if you are using a rigidbody you need to be using rigidbody. Addforce()
yes, I don't know what I did wrong
what did you find in regards to starting a coroutine
he is doing that?
Go to unity docs, they will tell you exactly how
I believe I remembered him using one
yeah hes already using AddForce
He shouldn't be += his velocity then
https://docs.unity3d.com/Manual/Coroutines.html
oh I need to put the startcoroutine function
where is he doing that? im confused.
ok thanks it worked
Ah nvm I read wrong 😅
by the way, your waitforseconds inside of SpawnItem does literally nothing at all
there's nothing after the wait so it just waits for no reason
wait nevermind, it's inside the loop. your nesting of the coroutine inside of the if statement in update makes this a real pain in the ass to read
yeah np, i was gonna say because the code looks fine to me lol
when i jump on the floor it works it flips my velocity fine
but its when i go into a wall that it just doesnt flip
and goes to a weird small number
show current code
well your trying to flip X velocity?
what would the X velocity be against a wall
like nothing
you would need to store it before you hit it i guess or not sure exactly
so would i need raycasts?
wouldnt that still be the same issue tho?
if i do it on hit then on hit its gonna lose all its velocity
unless im misunderstanding how it works
If you flip the velocity as soon as you hit the wall or if you get close to the wall it shouldn't stop velocity
UNLESS the object is already stopped
record the velocity before the hit, then reflect the same velocity
yeah and to record it would that mean i need to use raycasts to check before its gonna collide?
You can use raycast or triggers, etc. whatever floats your boat
I mean its not really necessary you pass in the velocity, before it got reduced just reflect the same one with same magnitude
So im working on this project and i need to be able to get the x, y, z position of a gameobject once i click on it, and im able to use that data in a script as real time data. so it updates as the object moves. is there any website i can learn something like this? or any example codes, something that i can teach myself
Pls someone should help me with this for 1 week now try to solve where the problem comes from
!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.
How to shoot
also is that really monodevelop..
hope this helps!
The hard part of this is detecting when you click on an object. There's actually several ways to do this. Depending on how your project is set up, whether the object has a collider, whether this script is on the object vs on some manager object, etc., but this goes over a few of them:
https://learn.unity.com/tutorial/onmousedown
Once you know which object you clicked on, it's as simple as getting that object's .transform.position to get the XYZ
Dang I was gonna post that but I was typing something else
I shall steal this image for future use 😈
i already have a script that detects when a object is selected, im just going to add the script to the event. i need the part of the script that actually gets the objects data that im clicking on
Ah, good. Then it's just .transform.position. Whatever component you have access to, or even the GameObject itself, should have a reference to its transform
i dont exactly get it, this isnt with a specific item. For more of an explination i have a script that generates a "rope" around two circles and i use the splines addon to do that. I use a bunch of math to find where the points the rope needs to be placed. The user is suppose to place two circles, and then click on both circles and it will generate the rope around the two circles. I need the position of both circles to calculate the math, so i need to be able to use it as a variable. and these game objects dont have a defined name so how will i be able to import it into the script?
learn how to get and pass references to other objects: https://unity.huh.how/references
Nah bro that was foul 😂
Here right
📃 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.
Where is the code guide line
mate, you've been directed to those guidelines like 5 times now. instead of completely ignoring them every time they are posted, you should try reading them
Alright thanks bro
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Inventory : MonoBehaviour
{
public List<Item> Items;
public int InventoryIndex;
public static Player_Inventory instance;
// Start is called before the first frame update
void Awake()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(instance);
}
}
public void PickupItem(Item item)
{
Items.Add(item);
Destroy(item);
}
public void DropItem(Item ItemToRemove)
{
if(Items.Exists(i => i.Equals(ItemToRemove)))
{
Items[InventoryIndex] = null;
}
}
}
public void Interact()
{
RaycastHit hit;
if (Physics.Raycast(_camera.position, _camera.forward, out hit, interactRange))
{
GameObject target = hit.collider.gameObject;
if (Input.GetKeyDown(KeyCode.E) && target != null)
{
if (target.CompareTag("Item"))
{
Debug.Log(target);
Player_Inventory.instance.PickupItem(target.GetComponent<Item>());
}
}
}
}
Hello, I'm having an issue i've struggling with and I can't think of a solution. The thing is that I want to be able to pickup and drop items that are stored in the player inventory. My problem comes when I pickup an item from world space and try to store it in the inventory: my Destroy(item) line also destroys the reference to that gameObject and it's data. I thought about using an Instantiate to clone it and add it but I don't know if that would be effective since what I want to do is to make them dissappear from world space until dropped.
you could just set its gameobject as inactive
hide it
I thought of that too, but in terms of performance, is that ok to do so?
better to do
well if the player were to pick up and drop the item multiple times then simply disabling the object would be more performant. however if the player were to pick up the object and then never drop it again, then technically just storing the item data to later instantiate it would be more performant. so really 
instead of spawning a new projectile everytime ur weapon shoots.. the more performant way is to use a pooling system
that recylces the gameobjects.. just enabling and disabling them.. (more performant than spawning/instantiating)
yo so im tryna check if any anomalies (the car in this instance) are within the circle, but it keeps giving me back that no anomaly is detected. attached is my code and a video of it https://pastebin.com/MJZUqL9L thank you very much :)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how would i go about setting up an on screen button to be clicked, and when its clicked it runs Application.Quit();
use on click
Have the button call a method on a script that THEN calls Quit (using OnClick as shown above)
Or subscribe the button directly via code instead of using the inspector, if you know how
thanks 
of course you will need to be aware that Application.Quit is ignored in the editor, so put a log to show it works or use some editor code to stop play mode if you want it to do the same thing in the editor
have you figured it out?
im trying to run unity in sandobxie plus
idk if you call it a virtual machine but ye
but in unity hub it says I dont have any licenses
even though I am signed into my account
ngl im struggling
is
public class CloseGame : MonoBehaviour
{
public void Quit()
{
Application.Quit();
Debug.Log("QUIT");
}
}
not enough for it to reference it on the button?
where is that info usually stored? I may need to add the file or folder to the sandbox
go to the settings there should just be a button to add licence
thats all you need for code yeah
then just need to hook it up to the event in the inspector on the button
im not getting an option to reference the method ;-;
you need to add in there a game object with the script
instead of the script itself
ye it does nothing in the sandbox
adding debug.log is really useful
im assuming there is a folder or .exe I am missing but im not sure
i was trying to figure out why my menu was spazzing out but i added a message to it and it was freezing the game every frame 💀
i gave it access to both the unity program folder and unity hub folder so it has everything in them
but why?
your supposed to build the project no 🤔 ?
and test it like that
or there is solutions to run multiple on 1 pc im pretty sure
ye i could do that i was just trying to see if i could get the editor working
yanking it out of update should fix it
yeah probably should
putting things in update has unexpectedly been a large cause of my bugs because i just kinda instinctively do it
okay well now its just not working 
sorry no
i was just bout to go to bed but are u available to help now lmao
i think a good way is to just use a raycast
and check if it hits something
i was doing that but it wasnt very accurate for some reason
like on some objects it worked
on others it just wouldnt hit
i ran this exe i found that had to do with licensing
i got this im wondering if it explains anything lol
okay this is the last thing im going to work on
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hmm maybe something to do with layers? not sure cant really help without seeing that code lol.
maybe go to sleep and rewrite and show tommorow?
whats wrong
i originally put in void update, and then that caused it to run every frame, which resulted in my mouse glitching in and out, and usually getting sent back to the center
nah i can just get this old code back gimmie like 5
now its just not running and im actually not sure how i fix that
i remember it pretty much
what was in update? whats the problem what are you trying to do
ah ok, you should be checking Input in Update
and then in the if statement of the key press, changing the state
because rn it would just do it constantly if these methods are in Update?
private void Update()
{
Inventory();
Menu();
}
was what i had
i wanted it so the player could click esc, or u, to their corresponding UI, and then it would disable movement and camera movement, but allow them to move their mouse around
line 33 to 41 should also be in the if statement of the Input, not sure why it isnt
you can go back to this code
and then just move lines 33 to 41 inside of the If statement for the key press
like this?
yeah, should work
well originally i just had them separate because i wanted it to make sure it
hold on give me a second i probably had a thought
i think the intention was to make sure that first line ran first but now that im looking at it now, i think it runs it first anyways
i seem to have broken something unrelated
okay heres the code grass: https://pastebin.com/BUkym4rd
im tryna get a video of it not working just give me like a hot moment
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the bench in the middle is a anomaly
well i tried to move it up but now menu isnt being acknowledged
gonna see if i can fix it
not sure why your checking layer AND tag? perhaps theres something wrong there
wait hold up u right
yeah that was the problem, why would that have an effect tho? every anomaly had both the tag and layer because I was orignally gonna do tags but I switched to layers and just forgot to change the code, so why wasnt it working anyways
thanks for the help tho
ig adding private in front of it just puts it back together what is this 
so it works now?
yee
great
if it had both correct layer and tag then it should work yeah, so not really sure unless it did actually have the wrong tag
im incredible i broke another thing
i mean i got the glitchiness gone but
its kinda fun
ok yeah this was just me trying to put too many things together
i just needed a separate script
https://pastebin.com/nT9S9spv nevermind its still broken that left building should be getting fixed
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
its weird how certain parts of the building work and other parts dont
where you click on it determines if it works or not when it should just be whenever u click on it no matter where
just wondering because the couroutine waits 4 seconds THEN sends the raycast.
could it just be your moving your mouse of the building so the raycast isnt sent at it 🤔
or am i wrong here
wait hold up i think ur right
let me fix this
okay i think its good now but if i see any more problems ill let you know
nice, ill probably go to sleep now anyway though so probably wont be able to help
no problem, glad simple fixes worked
yea i never notice the small things
which makes coding a weird hobby to be into but ah well
im confused on what this means and how to fix it
You've got a duplicate script
Change the name of the class
thank you
why is brackeys bad
Basically: his beginner stuff isn't good because he doesn't actually teach_code_ well. He teaches systems, and the code is often purely demonstrative and you should not be copying it directly
yeah even as a beginner I noticed some sloppiness in his content
Brackeys is probably more of an intermediate level tutorial series, his videos going into a specific system like navigation or post processing, etc., are great broad overviews. But like most people who are good at something they don't really know how to explain the early stuff they've long since encoded into muscle memory
three is a spot where he is good, and that's if you already know how to code well and are looking at learning what Unity is capable of. He does a wide range of things for that
ahhh. i didnt finish his first person movement video because it felt like i wasnt really understanding most of what he was doing.
so i kinda just kept looking for different videos
unfortunately my flaw was not immediately going to learn.unity and all their resources
its been far more helpful than the tutorials i tried to follow tbh
GMTK's intro tutorial is actually not bad. Not the best but it's hard to find someone who is good at coding and good at teaching and good at producing videos.
I followed thru with his tower defense tutorial start to finish and I felt like it covered a lot and I learned alot along the way
You'll probably just need to try a bunch and figure out your own path
One I am particularly fond of is Sebastion LAgue, he covers some more complex systems and is very calm talking about them at a laymen's level
Brackeys is really nice for quickly getting up to speed with an aspect of Unity you haven’t engaged with much, but it definitely expects you to be able to understand why he codes something, which takes experience
Can somewone tell me why my terrain aint showing up?
Can somewone tell me why my terrain aint showing up?
This is not a coding question and don't crosspost
mb
Anyone have any clue how to get the normal of the collision of a OnTriggerEnter()?
You cannot
Because there isn't one
so then how would I get the normal when a kinematic rigidbody hits another GameObject?
cause OnTrigger doesnt work for kinematics
OnTriggerEnter works fine for kinematic objects
I suppose, this should be the difference between the hit point and the object's position
You could do a Raycast of some kind from the object's previous position and its current position
And take the normal from that
It really depends what you're actually trying to accomplish
but I can't get teh hitpoint
Because there isn't an actual hit point, the objects intersect
when I want a particle to appear
when my rb hits another GameObject
So this is a projectile?
yes
So a bullet hole
Do a Raycast from previous position to current position each FixedUpdate
collider.ClosestPoint(transform.position);
https://stackoverflow.com/questions/31641522/how-to-get-contact-points-from-a-trigger
And you can get rid of the OnTriggerEnter entirely then and just use the Raycast for hit detection
Was testing out the new Raycast interaction script and hit an Object Reference not set to an instance of an obj. error. I googled the error and its said to be if the Main Camera in question is not tagged properly.
I went to check the camera, but it is indeed tagged properly.
Did I miss something out while I was checking camera tags?
show the line of code in question
then cam is not set. It is null
no. cam is a variable in your script
Sup. Should i combine two if's? If so then how?
Oh man, and i was curious why this IF was not taking two lines of code like the previous IF... Thanks 👌
It'll do.
Ok, finally refurbished the PlayerMouseClickInteract code and now I'll need to connect it to the InteractableNPC code: https://hastebin.com/share/icusijicoc.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I already got the InteractableNPC code from a youtube video but I'm unsure if I should add an interactable for the PlayerMouseClickInteract to work?: https://www.toptal.com/developers/hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
private void OnValidate()
{
if (!gameObject.name.StartsWith("[ENEMY]"))
{
gameObject.name = "[ENEMY] " + gameObject.name;
EditorApplication.delayCall += RenamePrefabAsset;
}
}
private void RenamePrefabAsset()
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
if (prefab != null)
{
string prefabPath = AssetDatabase.GetAssetPath(prefab);
if (!prefab.name.StartsWith("[ENEMY]"))
{
AssetDatabase.RenameAsset(prefabPath, "[ENEMY] " + prefab.name);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
im trying to add [ENEMY] prefix to the prefabs, but it doesnt change the prefab names at all, only the objects on the scene do have the prefix added, what am I doing wrong?
Have you read the docs? You are changing the name of the asset file not the name property of the asset
i see
i should change prefab.name then?
should i also keep the RenameAsset?
should I also call EditorUtility.SetDirty()? so mayn questions lol @languid spire
Mornin' all.
sooooo, I have this little bit of code and I'm having a bit of a brain fart with it.
if (newRecipeItemRequiredNumber < newRecipeItemAvailableAmount)
{
newRecipeItemName.color = cannotBuildColour;
newRecipeItemCost.color = cannotBuildColour;
newRecipeItemAvailable.color = cannotBuildColour;
canBuild = true;
// Turn component text a different colour to show there's not enough available to build the module
}
else
{
newRecipeItemName.color = canBuildColour;
newRecipeItemCost.color = canBuildColour;
newRecipeItemAvailable.color = canBuildColour;
canBuild = false;
}
if(canBuild == true)
{
newItemButton.interactable = true;
}
I know it's not doing what I want, and I know why. Essentially I'm spawning a bunch of prefabs with 'construction component' details and comparing the require value of said construction component to a master list of available components. The buttons start off as non-interactable (non-clickable), what I'd like is for the buttons to be interactable only if all of the require Components are available, I figured a simple bool would be the solution, but I'm having brain issues figuring out how to do it. Anyone have any ideas? 😕 ((Apologies if the codeblock is too long))
Does anyone know why this script to make the player swing around a point wouldn't be working? I included a screenshot of the debug log that I inserted and as you'll be able to see it doesn't make any sense... The player does reach the correct starting position but never moves past that.
https://hastebin.com/share/majeyamewa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
private void RenamePrefabAsset()
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
if (prefab != null)
{
string prefabPath = AssetDatabase.GetAssetPath(prefab);
if (!prefab.name.StartsWith("[ENEMY]"))
{
prefab.name = "[ENEMY] " + prefab.name;
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
this still doesnt work
yes, because you forgot the SetDirty
private void OnValidate()
{
if (!gameObject.name.StartsWith("[ENEMY]"))
{
gameObject.name = "[ENEMY] " + gameObject.name;
}
EditorApplication.delayCall += RenamePrefabAsset;
}
private void RenamePrefabAsset()
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
if (prefab != null)
{
string prefabPath = AssetDatabase.GetAssetPath(prefab);
if (!prefab.name.StartsWith("[ENEMY]"))
{
prefab.name = "[ENEMY] " + prefab.name;
EditorUtility.SetDirty(prefab);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
it changes in the inspector when i have the prefab selected
but not here
if you want it reflected in Project and Hierarchy then you need to do both
That is what will appear in the Hierarchy when you instantiate
but i want to change the name in the project assets
so i can use the project browser and type [ENEMY]
So add your RenameAsst back
thats the code rn
but you just told me to change the name property instead?
I did not say 'instead' I simply pointed out what you were actually doing
private void RenamePrefabAsset()
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
if (prefab != null)
{
string prefabPath = AssetDatabase.GetAssetPath(prefab);
if (!prefab.name.StartsWith("[ENEMY]"))
{
var newName = "[ENEMY] " + prefab.name;
prefab.name = newName;
AssetDatabase.RenameAsset(prefabPath, newName);
EditorUtility.SetDirty(prefab);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
If you don't understand what you are doing, why are you doing it?
huh
if you are not willing to help, stop wasting my and your time, thats the server for to "ask questions"
im trying to understand but you are just rude
wtf dude? He really isn't. lol.
ok
i just asked one question, how to add [ENEMY] prefix to prefab file name, instead he giving me riddles and stuff that doesnt work without explaining, what is this serevr for then if you cannot ask questions, instead all the answers you got is "you dont know what yuo are doing, then why are you doing it"
You're not going to get spoon fed a solution tbh, but you will get pointed in the right direction on what to look for so that you can understand. From what I've read (it is beyong me a little tbh), but you've been pointed in directions of where to look and research/read up etc.
read your original post #💻┃code-beginner message
you mention nothing about file name
Did i get poitned into a right direction?
well duh, its later in the converstaion
adding RenameAsset didin't do it
And you got the correct answer
tbh, you were asked if you'd read the documentation, but ignored the question. 😕
Yes, I've read the docs. Thats why I did RenameAsset at first
it didin't work so I asked here
what's your problem
anyway, managed to get it to work, thanks
it was just about using GetPrefabAssetPathOfNearestInstanceRoot instead of GetCorrespondingObjectFromSource
Evening, I have an issue with randomizing my map.
void Awake()
{
falloffMap = FalloffGenerator.GenerateFalloffMap(mapChunkSize);
System.Random random = new System.Random();
int seed = random.Next(-2147483647, 2147483647);
Debug.Log(seed);
}
void Start()
{
GenerateMapAtGameStart();
}
Everything else is working fine, and my seed is changing (in the console), but the map stays the same
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You're not setting the state of your Random object with the seed anywhere
Or rather, that seed variable you're using isn't used elsewhere in the code anywhere
It's just a local variable
O gorreltjies
Oooo okok
I see my mistake
Dankie
How to call a method of a script from another script using "OnCollisionEnter2D(Collision2D collision)"? Unity keeps getting angry because "TakeDamage" is not there.
You need to configure Visual Studio before going any further.
!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)
Fix your IDE like SPR2 said, but the problem where you're strugglig with is that the TakeDamage method isn't public, so outer scripts can't reach it. If you have a correct IDE, then it saids it for you
I just had a quick question, is there a way that I can make a trail renderer a solid color ?
Solid as in fully opaque? opacity is dictated by the color gradient, if the shader used supports vertex color and transparency.
So either use a non transparent shader or set alpha values on the gradient to fully opaque
Yes , I want it to be fully solid I don't want it to be a gradient isn't that possible ?
Modify the gradient so it only has 1 key, of the color you want
Or two keys both of the same color
I have already done that but I want it to be same as the sprite color I change 1 color only because in my game in every scene colors change , so changing both keys will take very long time
Changing a gradient from the code isn't complicated, and if you need to do it from the Editor, you can select multiple objects in the Hierarchy and you should be able to bulk-edit the gradient once
Alright
I think he means he tinted his sprites and wants his trails to be the respective sprite tinted colors
so yeah, set it via code
Bro it isn't that hard to understand I just want instead of gradient I want it to be solid
"Bro" you have more than enough information to accomplish your needs
Alright thanks for your support :)
It's not hard to understand for you, but I had some issues parsing that sentence here #💻┃code-beginner message
Other channels are just dead so I said my qestion here
Nevermind
Yep there's a communication / translation issue here, my remark wasn't about being in the wrong channel
My brain is braining rn lol , I'm just tired its been like 5 hours making my unity game
I'll just close for now
Thanks btw
Done. It does says so, method isn't public, but i'm not sure what to do
Make the method public
same way how you'd make a variable public
When you don't specify an access modifier, private is the default. So void Sample() { } is identical to private void Sample() { }
-# Only valid for class members. For types (classes, structs, etc.) themselves, internal is the default
The method i want access have to public? Done. Unity still angry because "TakeDamage" is not there (i think)
You're referring to gameObject
not collision
why would gameObject have a TakeDamage method ?
You had it correct on the previous screenshot. You basicly removed it for some reason
oh no. gameObject doesn't have TakeDamage indeed
you're trying to access a method in a gameobject (which is the object itself). The method isn't directly in the gameObject, but in a script
how do i freeze the rotations of a rigid body?
rb.constraints = RigidbodyConstraints.FreezePosition; i tried doing this but with freezerotaiton instead but it doesnt work
rb.freezeRotation = true; then this
at this point i have no idea what to do
That's right. So how about accessing that script (attached to an object)?
go and read the docs
rb.constraints = RigidbodyConstraints.FreezePosition; this works
rb.constraints = RigidbodyConstraints.FreezeRotation; this doesnt
thats what i did
and i only found these 2 that are simple
i need a simple code and i need to freeze the contrains of the rigid body
wait why does
rb.constraints = RigidbodyConstraints.FreezeRotation; freeze the position?
collision.GetComponent<script-name>().TakeDamage(DMG);
For OnTriggerEnter2D is it:
collision.gameObject.GetComponent<script-name>().TakeDamage(DMG);
you obviously did not read this
https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.html
@strong wren So rb.freezeRotation freezes rotation on all axes as intended. Are you manually rotating the object outside of the physics API?
no
but when it collides with other gameobjects it moves
Well yes, it should move, because you did not freeze the position. Was that your intent?
i want it to just completly be frozen, no movement at all
@strong wren You could freeze the position as well, but you can flag rbs as kinematic and they won't be affected by the sim
i want both to be frozen position and rotation, the position is frozen but the rotation isnt
The docs example show how they combine multiple constraints
ok i found a way i did this
rb.constraints = RigidbodyConstraints.FreezeAll;
This is an alternative to using = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
That's how you combine flags enum values, with | (bitwise OR)
Indeed it worked, thanks!
np
Evening, anyone know why my mesh collider is doing that?
https://hastebin.com/share/odicatehiz.csharp
https://hastebin.com/share/pemorobipa.csharp
it's supposed to be on my mesh
Nvm I found why
Coroutines are probably your best bet.
https://docs.unity3d.com/Manual/Coroutines.html
thanks
IEnumerator BeklemekBiraz(){
yield return new WaitForSeconds(.2f);
}
(void Update)
if(Input.GetKey("d")){
if(canChangeRoad == true){
canChangeRoad = false;
if (xvalue < goingSide){
xvalue = xvalue + goingSide;
Debug.Log(xvalue);
}
StartCoroutine(BeklemekBiraz());
canChangeRoad = true;
}
}
can I use it like this
should it work
dont look very working to me
I'm going to assume that the (void Update) is like, psuedo code because that is in no way valid C#
But right now your coroutine does nothing whatsoever
You start it, it waits, then ends.
Nothing happens after the wait
wanted to make key delay
If you want to delay something happening, you should actually have that something after the wait
yes yes I just cut all of it
Starting a coroutine does not pause the function it's in. It runs alongside the code
that's what makes it "Co"
Your coroutine does nothing
There's no code in it
yeah
Doing nothing, waiting 0.2 seconds, then doing nothing is the same as just... doing nothing
after I press d, I change x value and I change the bool to false so it cant work and after waiting .2 seconds bool again turns into true so I can change the x again
how do I do that I ask
I assume its not going to work with coroutines
put it after the wait
If that boolean is declared inside of Update than it literally only exists inside of that function and it would be impossible to carry its value across multiple frames
so I make it public
You make it a field
field?
Hi, is there a way to find out the origin of a log when using Debug.Log("message....", gameObject) ?
read the stack trace
the second parameter will highlight the GameObject in the scene hierarchy. the log will display the stack trace . . .
Of course, you can double click on the console message and/or read the stack trace (below the log)
how can i find a gameobject within a gameobject that has no children?
Yeah if by 'origin of the log' you mean the object, then single click
How can a gameobject have gameobjects within it if it doesn't have children?
also, double-clicking on the log from the console will go to the script where the log was called . . .
nono
how to find a gameobject, within a gameobject
and then additonally find if that second gameobject has children
I understand "gameobject within a gameobject" simply as a child
how can a GameObject be within another GameObject if it's not a child?
okay then uh how do i find a child that has no children?
yeah I know about the double clicking but I wanted to do a LoggingComponent where it would be given to multiple objects with logging features, and I wanted to quickly differentiate where the log is coming from (To somehow add it to the log message), without me having to manually add it into every log message
check it's child count . . .
wait let me explain a lil better
how do i go down this, checking each gameobject trying to find the first one that has 0 children?
(theres more than 6 btw)
Not exactly what you asked but for different systems I might add its own log function, something like cs void LogX(string message) => Debug.Log($"X: {message}");
And logs support rich text so you can also use color tags
I use a helper function that takes a string and a color and outputs a colored text
not a problem. loop through the children of the parent GameObject. you'll find tons of ways how on
. . .
allright thanks
Hey guys, I have an error where my player can't jump when it's going up, like this
yeah sorry if I wasn't clear enough, I'm currently using something like this ->
if (!_showLogs) {
return;
}
Debug.Log($"<color={HexColor()}>{_prefix}: {message}</color>.", sender);
}```
Where the prefix is the component (E.g. PlayerLogger, or NetworkLogger) and I wanted to add the Script / object the log is originating from. I thought of somehow using the sender Object but with no avail
I tried scaling up the GroundDistance but well this happen
So you want to know what code called this Log?
You would need to click like the second newest link in the stack trace to open that code in the IDE
Or do you want to highlight the object itself?
can't you pass the script as a parameter?
You should be able to just single click the log
Aren't they already doing that with Object sender?
something like the object / script its originating from
E.g. I have this line in MainMenuScript
_logger.Log("Switching to Main Menu.", this);
and I wanted the log to look like ->
Debug.Log($"<color={HexColor()}>{_prefix}: {message}</color>.", sender);
Which would ultimately do something like
"MenuLogger: MainMenuScript: "Switching to Main Menu.""
Hi. I decided to rewrite the text localization script myself when it changes. Example: We have the source text: "I love you:", and I add 100% to it, that is, it turns out: "I love you: 100%". By changing the language to another one: "100%" will be lost. That's why I needed this script. But there is something written in the script that then completely erases the text if you turn off the enable instance. I tried to comment on void OnDisable (because the text was disappearing because of it), but then nothing worked at all. I'm dumb. Please help me
uh, i use edge so i have bing-gpt built in and it gave me this
foreach (Transform child in gameObject.transform)
{
// Do something with the child
}
would this work??
(i didnt use it just automatically gave it to me)
that'll give them the object but not the script (on teh GameObject) that logged the message . . .
What's wrong with the way you are currently doing it though?
It looks like it does what you are asking - except for the "`MenuLogger: " prefix
the originating Script isn't present, currently, the result is only
"MenuLogger: "Switching to Main Menu.""
no way to tell unless you try it and see . . .
Then you are probably passing in a null object
Which prints as nothing
ig? ill just change the gameobject with my gameobject
guess were experimenting
I Don't think I am passing null, the stacktrace is there
@vital gale Can also try object.name but I think UnityEngine.Object.ToString() always gives the name anyway
i recommend searching and finding out how yourself. plugging in AI for results won't help if you don't understand the code (or try to) . . .
i didnt ask ai im asking because im curious
cuz i looked at some forums and i dont see something this simple
@vital gale Oh I just realized you aren't inputting the object's name anywhere so use sender.name for that
(in edge, bing is just there off to the side and gives summaries)
weird, the first three results all give me that same simple code . . .
gotcha . . .
Debug.Log($"<color={HexColor()}>{_prefix}: {sender.name}: {message}</color>.", sender);
almost there
Instead of MainMenuCanvas I wanted the script name (second to last line in the stacktrace (MainMenuScript))
the exact same code that i got from bing?
Okay, maybe try sender.GetType().Name then
a link or webpage should accompany those results. take a look to see if they explain it or see if you understand the variables in the loop and what it's doing . . .
yes, it's really common and the main way to achieve what you're asking for . . .
that's the one, thanks a lot 
i understand how the code should work but im a little skeptical because it looks too simple to work
did you try passing the script itself and changing the parameter type?
The sender.GetType().Name recommended by @verbal dome was exactly what I needed 😄
amazing
yeah, i was just saying from before, switching the type to MonoBehaviour would give you the name of the object and the type at the same time. doing sender.GetType() will only display the type if you want that . . .
public void Log(object message, MonoBehaviour sender) {
if (!_showLogs) return;
Debug.Log($"<color={HexColor()}>{_prefix}: {message}</color> | {sender}");
}```
you will need to. and for the love of god don't share screenshots of single lines of code
had you not actually saved the code before?
If that's not instantiating it, that line isn't running
if i uncomment this then it stops working and doesnt even instantiate it
it does
its not in the hierarchy
meanwhile when i comment the code i outlined it does instantiate it?
show the actual context for this code, because on its own there's nothing wrong with it
allright 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.
My guess would be that the conditions for reaching that instantiate line stop being fulfilled if you don't spawn this as a child object
the point is to make the object a child tho
now put some logs in there, remove the entire Start method because it is completely redundant, and make sure that the inventory gameobject and its children are not being destroyed
so what
Just to prove to you that Instantiate doesn't just decide not to work for no reason
if you comment out the line that sets the parent, chances are your own if conditions are no longer satisfied
so the code does exactly what you tell it to do
how does that work if its not a condition in the if??
uh i should log the postfab right?
if you don't set it as a child, then the children likely don't have children so their childcount remains at 0
which means your condition is true
so it should instantiate it then right??
log everything that is related to this
yes as you've pointed out that is when it works. when you are not setting them as children of those objects.
so when i do set it as a child it becomes false and it doesnt instantiate it right?
can you just fucking put some logs in your code instead of making assumptions
im not making assumptions im asking so i can wrap my head around this
So ask your code what it's doing. By putting logs in it
You can literally just run the code and have it print what its doing
you don't need us to interpret it
put this in the loop before the if statement
Debug.Log($"{name} is trying to Instantiate {prefab} on {inventory}'s child: {child} with {child.childCount} children. Possible: {child.childCount == 0}", child);
any time you see that "Possible: true" it will have instantiated the object
and you can click the log to highlight the object it was set as a child of
so what do you think that indicates
hey guys!
is there a reason that when i create these "node" objects, that all derive from the class Node, they work fine and have the right type, but after i make a change to a script and re-open unity, their type, turns into the type of the base class?
you can see the types in the console, before and after reloading a script.
here is the code for creating, and storing the nodes in a list of type Node:
https://hastebin.skyra.pw/tuhiqezodo.csharp
the object isnt instantiated?
So, your code is correctly not running instantiate, since the condition you wrote isn't true
oh you know what, it's transform.childCount not child.childCount
oh
it clearly indicates that the childCount is not 0
As I said, if that line runs, then an object is instantiated
what
what do you mean what? what do you think the condition is?
literally what condition is it checking?
wait wait
i found another issue hold on
ok i fixed that issue now everything works....kinda
it instantiates it right in the right child
in the right place
well that sounds like it is working
help pls.
its so weird that these objects turn into their base class xd
Might be a better question for #↕️┃editor-extensions
except its both not and it is?
it acts like its there, which it is, but it doesnt show up
the question dosnt have anything to do with the editor
i cant click it even though its a raycast target and its missing in the ui
you're gonna need to be more descriptive than this
You appear to be making a custom inspector window though?
Or at least custom nodes for one
okay yeah but its gonna be a mini textwall so wait a few min
yes, but the question has nothing to do with that.
i create these objects whos type derive from a base class (which is node) and it works correctly, but as soon as i save some random script or reimport an asset, the objects TURN INTO THEIR BASE CLASS for some reason
like, it dosnt make any sense
why would their type randomly change
polymorphism 
is it because the type of the list is that base type or something like that? this is beyond my comprehension and im just making theories tbh
if only there were a channel dedicated to the code related to custom editors and the like
dude
Well, technically, they always were the base class. Anything that is a sub-type is also a parent type. All BoxColliders are Colliders
I really don't have enough context behind these nodes, I've literally never touched any custom graph editor code
No idea where it's getting its "type" info from
the nodes are a custom class
here is what happens:
-i create an object of type Start_Node which derives directly from Node.
-i add it to the list List<Node> nodes
-i log the type of the node to the console like this:
Debug.Log(node.name + " - t: " + node.GetType().Name);
Resault:Start Node - t: Start_Node
-i make a change to some random script and save it.
-i return to unity.
-i log the same thing.
Resault:Start Node - t: Node
so im very obviously making an inventory, currently im trying to make it so that i can pick up an item, delete it in the space 3d and "add it"(instantiate it), to my "inventory",
now all i did was instead of setting it so the whole inventory i set it to the part where the actual inventory is, because i have it broken up into parts, the main inventory, the gear area place whatever, item description etc
now it works, i press the button to "pickup" the item, it deletes it in the 3d world and instantiates it, then places it in the correct, first child, that has 0 children
issue is it doesnt show up, its an empty "inventory slot",even tho there is very much an item there, i cannot move it, click on it or interact with it, but if i try to manually drag a prefab and instantiate it on a different inventory slot, then try to drag it where the item is supposed to be, it wont let me drop it on that slot, so there is 100% something there and acts as if there is something(which there is)
but the issue is i cant interact with it, the image is missing and even though its a raycast target i cant click on it or move it, in the scene editor it is very much in the correct spot that its supposed to be, its active but still missing,
if i try to manually drag and drop the same prefab from the prefab folder onto any of the "empty"(has 0 children) "inventory slots" it works, but if the code does it it wont work right
is this actually causing issues?
provide screenshots of what you are seeing
are these files in their own asemdef?
a few seconds
yes.
any data that was saved to a field that specificly existed in say, a DebugLog_Node, will be lost after it turned into Node.
DebugLog_Node's have a message field, which the class Node does not. so i lose the message
also when displaying each node in the editor it needs to know what kind of node it is.
see the differance in these two photos? that because all of them turned into a generic Node after reloading a script
wait as in the script attached to an object literally changes it's type?
I haven't used Unity in close to two years... but I dont see how this is possible
the node class is not a monobehavior. it is saved in a list, that is in a mononehavior
so they are not directly attached to a gameobject
i'd guess however they are serializing this for the editor window they are using does not support polymorphism or they are just doing something wrong in that regard. of course they refuse to ask in the #↕️┃editor-extensions channel where the question would be more appropriate so i guess they'll never know
are you treating a class like a SO? 🤔
Ah right
why are you so passive aggressive
somebody booted up on the wrong side of the bios this morning
I'd assume editor windows get dirtied on a recompile
Might be the root cause
but I don't know enough to help further
picture one, walking up to the item, picture 2 i press the use button and it deletes the item and instantiates it in the right place, picture 3 i drag and drop the same prefab on a different slot, and it spawns correctly,fourth picture, i drag the manually added prefab to a different slot, but if i try to drag it on the very first block, where the item instantiated by the code is, it wont let me drop it on that space, but i cant move or interact with the item that is there
im creating these nodes through a script and just saving them to a list.
why does the editor matter here? i dont understand.
why do you refuse to ask your question(s) in the correct channel?
SoMeBoDy bOoTeD Up oN ThE WrOnG SiDe oF ThE BiOs tHiS MoRnInG
lmao
It's good to see beginner code hasnt changed
can you tell me why the editor even matters here?
im saving some objects to a list and their type changes
lists are a basic part of c#.
the editor just displays them
so i think something is wrong with my code
its like the vanilla icecream of code channels, you know exactly what youre getting
so just to be clear, the object is being instantiated and you do see it in the hierarchy, you just do not see the graphics you expect and cannot interact with it in game?
if that is the case, you need to check its inspector to make sure that the correct image(s) are applied
and of course that none of its components have been destroyed
i did try to save these nodes as SOs and it did fix this issue, but then again, no scene object refrances :/
yes that is it
and it doesnt have a sprite the only thing thats changed is the colour (for now)
show the inspector for the one that isn't working compared to the one that is
can someone at least tell me why this problem is related to the editor?
idk what to say if someone in #↕️┃editor-extensions asked me why i sent my question there
theres a single difference let me show you
boxfriend will take the blame
It looks like you are trying to create custom editor behaviour (creating nodes).... so that seems exactly what #↕️┃editor-extensions is for...
#↕️┃editor-extensions is obviously for code, since that is how you make them
probably related to whatever is in Itemscript then, so most likely you do need to assign that field
if you're using IPointer events, maybe parenting it breaks the interactability area
so after a drag, resetting it could fix it
we'll likely need to see that code for a proper diagnosis though
wait i think something just clicked.
so, these nodes are saved by the editor right?
and thats where the problem is? how the editor serializes these nodes when saving them?
yes, that is exactly what i've already pointed out. you just decided i was being "passive aggressive" and ignored that information
if ur making something change in the editor.. or have different functionallity that is default.. its editor related
trying to set parentafterdrag
show its code
again, we need to see the actual relevant code to determine if that is the case
this includes the Itemscript as well as any other code related to interacting with it
is character controller movement based harder than physics based one rn im struggling to do the oncharactercollderhit
interacting with it just activates the code at hand
ur just comparing (1) aspect of it...
"interacting" just finds the script, and calls the function that runs all the other code
but in that case Rigidbody uses normal OnCollision events
so id imagine that being a bit easier.. but OnCharacterCollider.. isnt hard perse
this is pickupscript not Itemscript
huh
wdym "huh"? these are two completely separate components and i asked to see the code for itemscript
this is the code rn for the game its confusing since when it hit an invisible hitbox that acts as a boost for the player it doesnt want to run the method
ah, well im setting the variable of item script in pickup script but here you go for itemscript
also i see you didn't bother removing the redundant code from Start like i suggested to you an hour ago
is this wrong in any way?
i did, i re-added it rn to set "parentafterdrag"
cause thats where its stored
that code is 100% pointless though
okay, ill delete it after we fix all this
heres item script
you have already assigned itemscript you're just reassigning it to what it is already set to by calling GetComponent on itself
Adding the [SerializeReference] attribute to the nodes list seems to have fixed it!
btw sorry for being so incompetent, my bad xd
oh okay
// method in the character controller script
void OnControllerColliderHit(ControllerColliderHit hit)
{
// Log the name of the object we collided with
Debug.Log($"Collided with: {hit.gameObject.name}");
}
``` - ChunkyBlock - Rigidbody + Box Collider
also you're not even assigning the parent on the instantiated itemscript in your new code, you're doing it on the prefab. or possibly on the itemscript on this pickupscript object, it is unclear how you've got this set up
so if i were to make a phaseable hitbox this doesnt count? this is my code rn
the pickup script object doesnt have an itemscript
if it is a trigger collider then you should be using OnTriggerEnter
well then you are assigning to a field on the prefab
also, oh what
yea, but as boxfriend said.. if its a Trigger use OnTriggerEnter() <-- Trigger functions work totally fine w/ character controllers
this is what i meant to clarify
itemscript is a reference to the prefab, not the instantiated object. postfab is the instantiated object
this collider is disabled, meaning it is not able to be interacted
from that screenshot no it wont work... for :
- the box collider is disabled
- for ~~OnControllerHit ~~or TriggerEnter to work.. 1 of the them need a rigidbody
that last bit is incorrect, no rigidbody needed for CC.OnControllerColliderHit
that's kind of its whole point. also i don't think it's needed for the CC to send the OnTrigger messages either
if its a trigger volume (where u walk thru it) you might as well use OnTriggerEnter
yea but parentafterdrag is in itemscript, but the instantiated object also has itemscript, so how do i change the parentafterdrag of the instantiated object?
postfab.parentafterdrag.setparent()?
again, your itemscript variable is a reference to the prefab. not the instantiated object.
you need to get a reference to the instantiated itemscript instance
this can be accomplished in one of two ways, either call GetComponent on the postfab variable or change the postfab variable to be an itemscript type, and use your itemscript variable as the prefab
okay ty but one more thing when i was experimenting when i use rigidbody and phase through a tag boost with a oncollisionenter with it disable it still works why tho
ill go the getcomponent route
the other option is the better option btw
so postfab.getcomponent<itemscript>();?
it would not have worked with a disabled collider
Heres a OnTriggerEnter setup..
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Boost"))
{
Debug.Log("Player entered the boost trigger");
}
}```
sorry that im gonna ask this question how do i make it so the hitbox able to phase through again 😦
make it a trigger
TriggerEnter only happenes each new time u enter the trigger
so if i make it a trigger it would make the collider phaseable?
you could use a cool-down timer... so it also counts and makes u wait so long before it'l trigger again..
or u can disable the trigger (box collider) and re-enable it later.. different ways to do it tbh
thats the definition of a trigger collider yes
wdym, they are identical
you're 💯 correct.. seems the CharacterController takes up the slack and handles that for you as well...
today i learned 🌈 ⭐, well, i've wasted alot of time adding unneeded rigidbodies for a while now
im doing something wrong and i dont know what but i know its extremely simple because ive done it before but i cant remember so can you help me just do this
show what you've tried
how do i refrence it
if i change postfab to itemscript it wont work, im trying to give itemscript a name somehow but i dont know how exactlyy
i know it was something within the parenthesies of the getcomponent thing
well postfab is still a GameObject variable so naturally that won't work. you also just throw away your reference to the itemscript on that object because you just call GetComponent but don't store its return value anywhere
you should do that anyway and use itemscript in place of prefab then it will work without the GetComponent
ding-dong-ditch of the code world
of course none of this is likely to fix the actual issue anyway 🤷♂️
how do i store the return value
is this your first time using c#?
or really any programming language for that matter? because you are doing it elsewhere but somehow not comprehending how to do it here.
no its late and im tired and i just want to get this over with
cough itemscript myReference = postfab.GetComponent<itemscript>(); cough
cover your mouth to not spread germs!!
but even still, the other option where you change the type of your postfab variable and just use the existing reference to the itemscript component on the prefab in place of the prefab variable will be so much fucking easier
like i've pointed out how this is easier and you've come so close to actually doing this several times, i don't understand why you don't jsut do this. it's better
because autism thats why
you should only be dealing w/ variables you need..
not sure in your case.. but if ur wanting to access a script directly as a variable
theres really no good point in instantiating it as a gameobject and then getcomponenting the script..
when u can instantiate it as the script (and it will spawn the entire object) [then you have the script reference from the getgo]
don't make excuses
PTSD i tell ya! ;0
i dont wanan do it because i dont feel like its in my comfort zone yet, i like to take everything at my own pace and understand it indepth
not that i wont ever learn it
just not now
additonally im stubborn enough to literally recode my intire game if i learn something new
so if i do learn the more effective methods i will change everything lol
my dude, it's literally an incredibly simple change. and should be how you are handling all of your prefabs. you are doing unnecessary operations by requiring yourself to use getcomponent, which you seemingly don't even know how ot use anyway. so use the more effective and better option
i will
just not rn
theres a very good chance ill just change it in like a few days when i do learn that
changing types
then you better learn how to use getcomponent, since you don't know how to do that now 🤷♂️
i won't be continuing this conversation any further though. so when you realize you're still having trouble with the instantiated object you will need to post a full description as well as all of the relevant code again so someone else can assist you
ive used get component so many times before my brain just isnt braining rn
thanks for the help tho
itemscript = itemscript.GetComponent<itemscript>();
this line begs to differ
one proof in an ocean of debunkery
you only see the mistake not all the other code that works
if there's other code that works, why did you not consult that code when you couldn't figure out how to use GetComponent in the code i suggested you use it in?
because i didnt think of that
and i was allready here
[SerializeField]
private ItemScript prefab; //assign ur prefab here like normally.. (altho we declare it as a ItemScript)``` then its just
```cs
ItemScript itemScript = Instantiate(prefab, transform);
``` now you have a reference to the ItemScript on the prefab u just spawned.. **and** the prefab in the scene.. w/o coding
they didn't even need to change the type of the prefab variable, they could have gotten rid of it completely and just changed the type of their "postfab" variable and used their already existing reference to the itemscript component on the prefab that is stored in their itemscript variable
ah true..
i was overcomplicating it myself.. making sure it wasn't a castable scenario
it'd been easier to know if they pasted their code like normal.. instead I had to retype it out.. and all the lowercase letters werent sitting well w/ my ide 🤣
it didnt, amazing, im going to pick this up in the morning
they did up here.
and it could have been easily changed to this https://paste.ofcode.org/36iCr5UV2tPLcjpuz7cZE2N
oh and i left their start method in since they didn't bother removing it when i suggested either 🤷♂️
nothing wrong w/ taking a break.. come back to it fresh-eyed and bushy-tailed
as my parents would say
im blind sry
well thanks for the help ig
i... did, i said id remove it after we fixed this but we havent yet...
i removed it, put it back in and im going to remove it now again
even though we havent fixed it ill clean up the code so its tidyer, tidier? tydier??
📌 pro-tip: utilize // comments so u dont have to completely remove/add things
if its redundant then ill delete it, but dw // is my best friend lol
got it there in the middle!
How can I create a component in which my slots have a Draggable behaviour(dragging and dropping items into other slots) but with different purposes once the object is dropped?. For example, when the item of the slot is dropped on a Hotbar slot , the Hotbar component does the appropiate operations, however if the Item is dropped on an Inventory Slot, then it is the Inventory Manager that should be called
cant wait for the english spelling reform cause this writing system is second worst, in the tierlist, first is french ofc
amazing im trying to make an inventory rn
what a coincidence then
ill send you the link to a tutorial about making just the inventory then you can figure everything out yourself, hopefully
Oh thanks men
Oh yeah, I know that one, it helped me a lot with the general concepts and behaviours of the different systems
also.. not sure you know but
/*
[code]
*/``` for multi-line comments
then thats everything i can give you
thanks anyway!
it really depends on what exactly you want those objects to do. if it's pretty much the same thing, then just have the object being dragged perform whatever operations when it is dropped.
Otherwise, i would create a component that has a UnityEvent on it that the dropped object will check for and then invoke that UnityEvent. then whatever holds the component can do whatever it needs to in response to the UnityEvent being invoked
but do you know ctrl+k+c?
and ctrl+k+u
select everything you want and itll auto comment and uncomment
That is a good option, I haven´t thought about it, thanks as always!!
i have problems remember that hotkey combo
its like trying to perfect a kick-boxing finisher move
/* very handy when doing specific parts of the code and not the whole thing
public void Something() { //Cannot close the method on single line }
public void Something() { /* Now we can comment single line */ }```
can anyone one help me with a problem i having on unity i im making a save and load game where i press play my camera, fixed camera angles all work but when i hit save and then quit the game and the camera get locked where it started and doesn't follow player or anything im using cinema machine and clear shot. but i don't know why when i load my game camera locks and i cant move it or anything i don't know if it my code because it works when game start but doesn't when i save and load
are you reassigning its follow target?
right so if you are reassigning it to something that either does not exist or to null on load then naturally the camera will no longer follow the object it should be following
Oh
i have a single idea and that is to instantiate the object directly where it should be instead of instantiating and then assigning its parent, but that will probably require that thing boxfriend said so im gonna tackle that tomorrow and change the type or whatever
@slender nymph so would I add to my game manger load camera certain spot or something like that
i have no idea what your code looks like mate, i only made a guess at what the issue could be.
📃 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.
click on one of the links, copy paste code, save, copy the link that you get at the top
also PASTE.MYST.RS???
.rs is the country code for republic of serbia
im just suprised lol
I mean.. its short domain
nono like, the balkans isnt really that known for uh good tech
its a domain, anyone can buy any country domain (ccTLD)
I think i have one from congo .cd
just suprised one of the sites for codeposting on the official discord of one of the most popular game-engines is from a country with one of the least developed tech industry
the server is in Germany
yeah, balkaners made it, its painfully obvious
anyway lets keep it ontopic of unity code 😛
yeah
wait
nvm, i thought serious sam was made in unity, forgor they had their own engine
@winter tinsel do I post that code in here once I use large code blocks
you go to the site, paste it there and paste the link here
share the link that contains the code, yes
after saving
📃 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.
https://gdl.space/lawezufuga.cs how can I manage to make the DropEvent to pass the list of RaycastResults onto the method that I assigned to this event??
make it a UnityEvent that takes a parameter of type List<RaycastResult> if that is the data you need to pass to it
Can I do Invoke(List<RaycastResults>)?
just like any other method you want to pass an argument to, you must pass an actual object. so you'd pass your raycastResults variable not List<RaycastResults>
but the raycastResults that I pass through the event are assigned in the editor right?
huh? what do you mean by that
the raycastResults list is populated by the EventSystem.RaycastAll method you call
If I do a public Event, I have to attach a component in the editor which contains the method I want to run
yes, that does not prevent any of what i've said
but then how can I pass the raycastResults from this component?
i just told you . . .
Okay, I´ll try and If I have any doubt I´ll tell you
thanks for your help and sorry for the confusion!
I want to move a 2d gameobject in a perfect circle, how to do it? Without using parent/child (with script) Tag me please
RotateAround() would probably be the easiest. Or you could set position vector components using Mathf.Sin() and Cos(). Or have it follow a circular Spline
(among other options)
use a rotation constraint component, or a script that follows a GameObject with an offset, then rotate the follow object . . .
Thanks
Thanks
How can I add a GameObject to a UnityEvent that is attached to a child object of a prefab?
prefabs cannot reference scene GameObjects . . .
What can I do to add it to the event?
https://gdl.space/exodeluyel.cs this is my game manger the one that holds all info https://gdl.space/sijavuxuzi.cs this is my mainmenu to start play load and save game there is nothing else to them and my camera is not regseting on load
Have you sprinkled some Debug.Log()s around to try and pinpoint the issue?
Debug.Log(json) in GameManager.LoadGame() would tell you if the method is running, if PlayerPrefs has a saveData key, and what the stored value is, for instance.
instead of having the event on the same object that you are dragging, you should put it on the object you are dropping it on like i suggested earlier. then the dropped object just checks for the component that has the event when it is dropped and invokes the event
so the method that the event Invokes should be in the object I drop the item on?
And the event
yes. the event should be on a specific component that your dropped object can check for so it doesn't have to check for those other types of objects that you wanted to run logic on. those other objects will have that component and will just subscribe to the event
Okay, let me see, thanks again! (dont want to sound annoying)
I can´t invoke methods that require RaycastResults
why not
it doesn´t appear
is the method public? if not, just add the listener via code
also does the event require that type as the parameter
do it through code. you can add the method to the listener . . .
Okay, let me try
oh, box is already here. listen to them . . .
what do you mean?
i mean exactly what i asked. if you are unsure, then show the relevant code (the method you want to subscribe as well as the declaration of the event)
from your previous screenshot when the event was on DraggableItem, the event does not pass any parameter
so show that you are using the correct UnityEvent<T> that passes the parameter you expect to pass
well you've not shown the actual declaration of the event, but it does appear that it passes 0 parameters. so naturally you won't be able to subscribe a method that expects any more parameters
public class SlotEventCall : MonoBehaviour
{
public UnityEvent Event;
}
this is my declaration
exactly, that does not pass any parameters. use the generic UnityEvent with the correct type parameter
and what about if the event needs more parameters?
I can´t reuse this then?
a UnityEvent can pass up to 4 parameters https://docs.unity3d.com/ScriptReference/Events.UnityEvent_4.html
if you need any more than that, realistically you need a struct or something that holds the data you can use for the parameter
for example, if I want to Invoke one event that needs the RaycastResult and an int and then I want to Invoke another that doesn´t need it, then I can´t reuse this SlotEventCall Component
so you need to pass different information to the two different objects that your draggable object could potentially be dropped on?
Yes, one object in which my item is dropped needs an int and the other one doesn´t
you can still add the method without any parameters to the event . . .
for future reference, please be forthright with that information, this is important information that determines how you can handle this. if you need to pass completely different information then you need to manually TryGetComponent for each of the two objects you are checking for on the draggable object and directly call the methods necessary there
the problem here is that the component which I call in one ocasion is the HotbarManager with a static reference call
why? is there a specific reason you cannot use TryGetComponent or GetComponent to check if that component is attached to the object being dropped on?
It is not attached since the component I want to get is in another Object
a HotbarManager
How do I fix my Playfab window not opening/showing?
where do I go for like help and shit
this is a code channel
!ask 👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
is it a parent of the object being dropped on?
no
why
because it calls a Manager which is a static reference
that makes no difference
is the hotbar manager not a parent of the hotbar? because if not, that's kind of silly design. make the hotbar manager a parent of the hotbar and you can just GetComponentInParent when you drop the items onto the hotbar instead of relying on the singleton pattern and hoping you dropped it there
Okay, let me try that
at this point i'm thinking you did something silly like pass those raycastresults to it because you aren't even doing anything to check if it was dropped on the hotbar until after you invoke the event and the hotbarmanager searches the results for that
Im really confused right now, let me try the parent thing and I´ll tell you
I could use some advice. I'm developing a boss rush bullet hell game, and the first boss consists of four shooters. Each shooter uses the same script but is attached to a separate game object. Would it be better to create a single 'BossShooter' script that controls all four shooters from one game object, rather than having separate scripts for each one?
you should actually describe what your code is doing and why you're doing it the way you are. then we don't have to make assumptions, like you assuming i have any idea about the structure of your code
There is an abstract "HotbarManager" and there is a UI Hotbar, that isn´t a component which actions depend on this HotbarManager which has a static reference
you don't need to keep saying "static reference" i am aware that the HotbarManager is using the singleton pattern
the only issue this one script is they shoot in 4 different directions which makes it harder to make one script for all
It depends what you envision the boss doing. If the boss is conceptually a single entity controlling multiple bodies and you want to coordinate them, then yeah you could create some supervisor class to pass instructions to each (though each should still have its own component to handle shooting logic and the like). If they're just four uncoordinated enemies they should be entirely separate
How do I use getComponent if I have multiple game objects of the same type
alr thanks i think ima go with just one script then
getcomponent is scoped to a single gameobject on which it is being called
You call GetComponent on the object you want, and you pass in the type that you want
If I have two cameras, how do I get specifically camera two
if you have gameobjects Go1 and Go2, Go1.GetComponent<Collider>() will only return a collider on Go1, it doesn't know or care about Go2
Make a public field and drag in the one you want
GetComponent not required