#💻┃code-beginner
1 messages · Page 228 of 1
thanks, thanks, I'll keep that in mind 😛
Thought it's related to unity , so asked, is there a specific place for such doubts?
me too
Ok thanks , new here , very sorry
Hello, guys! I have a small issue. I want to pause/freeze my timer counting whenever my game goes over, so whenever my player enters the collider of the other object and triggering game over, as well as to trigger that game over and stop the timer whenever my player getting out of bounds. I have tried like to use Game States with Enum and make it happen but for one reason it doesn't fix. If you want I can provide more information and make a thread for that.
startpos.y will always be 0
so how do you get it up
I have started thinking if I have my UpdateTimer() somewhere else but as I have checked everything is fine at the right place.
set it to transform.position.y in start. as you are only manipulatiing the .x then you probably want that for .z as well
think about it, startpos starts as 0,0,0 what should it be?
0, 9.5f, 0
so set it to that
I did they work in the first loop but in the second it goes back to the same 0. Why?
look what line 12 does
Thnks, just had figured that out. Love you
Hey there, I am facing FileIOPermission present both System.Security.Permissions and mscorlib problem, anyone knows the solution?
you probably have using statements you dont need
@languid spire I was using Gamelift SDK , now i am trying to import Vivox and getting this issue
This is my code for player game object , it is a kind of geometry dash game , creating obstacle sprites in the game now , how do i stop the player if it collides with obstacles ?? i tried writing it in the last function of this code
that tells me absolutely nothing
!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.
AWS gamelift SDK uses System.Security.Permissions assembly as dependency and Vivox uses mscorlib assembly as dependency and both of them has defination for FileIOPermission
Thus I am getting issue
pasted my code here , what to do next?
Just use links for so large codes XD
you did not paste anything, you posted crappy photos of your screen, do it correctly or not at all
copy/paste your code to any of the sites from the links. no one is going to burn their eyes trying to read that code from your screen . . .
you as well, post screenshots not photos
@somber ravine We don't live at 90's or 00's you live in 2024 bro photos are an old way to show something to people XD
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.
This is a photo, not a screenshot. https://www.take-a-screenshot.org/
my bad , didnt know sorry
heres the code
this is the issue
No problem XD I am just saying
Here is the SS @languid spire
A meta data file (.meta) exists but its folder 'Packages/com.unity.adaptiveperformance/AdaptivePerformanceProject' can't be found, and has been created. Empty directories cannot be stored in version control, so it's assumed that the meta data file is for an empty directory in version control. When moving or deleting folders outside of Unity, please ensure that the corresponding .meta file is moved or deleted along with it.
how can i fix this?
that is, indeed, a problem, looks like Unity screwed up somewhere, that's trying to use a .Net 7 version of Security.Permissions which Unity does not even support
I'm in Unity2D and I have a piece of code that's supposed to trigger a scene change upon a specific item being picked up so the scene will play a cutscene and kick the player back to menu. I have an mp4 of the cutscene but I don't know what to do from there
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
@languid spire I am getting this issue while importing Vivox, is there any suggestion for alternative library for voice chat which I can use with similar features ?
No idea, I don't use 3rd party libraries
No issue, Thanks for help👍
The tutorials I'm looking at all tell my about a timeline is that the only method
timeline is for making cutscenes, you said you already have the cutscene so, no, that is not the solution you are looking for
i see
Can ya'll help me please. This is how you unparent an object, right? I don't know why but it's not working. I've confirmed that canMove is turning to false, I can see it in the inspector, so no idea why it's not working
Add a debug log or a breakpoint and debug with the debugger.
Does anyone know if this would enable mipmap generation:
Texture = new Texture2D(
(int)_lottieRenderData.width,
(int)_lottieRenderData.height,
TextureFormat.BGRA32,
mipCount: 0,
linear: false);
Its 0 but the default is -1 in the unity core
public Texture2D(int width, int height, [DefaultValue("TextureFormat.RGBA32")] TextureFormat textureFormat, [DefaultValue("-1")] int mipCount, [DefaultValue("false")] bool linear)
: this(width, height, textureFormat, mipCount, linear, IntPtr.Zero)
I want it disabled
is there a way i can detect if the app is opened the first time
@dusk minnow Write something to disk when the app is launched. If there is nothing written, you can assume it's the first launch
Is there a good tutorial for a simple idle, run, and jump animation, it would always turn out weird for me cuz the only tutorial I could find was a lil’ bit outdated
is there a function that floors to an int but if its too near by a threshold it doesn't?
something like
if value is 3.995 and it has a threshold of 0.01
it will be 4 instead of 3
does that exist?
guess you could call that weighted rounding
floor(x + 0.01)
SetParent() is a thing but idk if it does anything different
it might fix it
if it doesnt then your if statement isnt false
thanks a lot how did i not think of that
almost wrote a new function
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaypointFollower : MonoBehaviour
{
[SerializedField] GameObject[] waypoints;
int currentWaypointIndex = 0;
[SerializedField] float speed = 1f;
void Update()
{
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].transform.position) < .1f)
{
currentWaypointIndex++;
if (currentWaypointIndex >= waypoints.Length)
{
currentWaypointIndex = 0;
}
}
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, speed * Time.deltaTime);
}
}
Why am I getting this error?
SerializeField
Not SerializedField
Your ide should have caught that
Because your spelled it wrong
oh
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
Should this be unlocked?
Yes
You need to remove the "Engineering Feature" to unlock it
Unfortunately that feature adds a bunch of out-of-date packages and keeps them as dependencies
What engineering feature? I already unlocked it
I didnt remove any engineering feature either
Unlocking it doesn't really do anything
You need to remove the VS Code package
I don't really know where to ask but i have this error :
'hero' AnimationEvent has no function name specified!
my game run well on test, no bug at all, no animation problem, and the said animation are all named? like i don't know what he's referring to
You have an animationEvent with no function specified
on your hero
lol
for learning purposes
ye i searched the error and people are saying this, how do i delete the event?
then try it and see
if its correct
if its for learning purposes
why does it make you wait a day?
yes
why
its not an exam exam
Open the animation and check the top row, look for the event and then remove it
i found the button thanks ! it's really small x)
Then you should study and actually make an honest attempt at the answer and if you get it wrong, suffer the consequences.
Asking us to do your homework for you isn't gonna let you learn it any faster
It is a question and answer format where you can get things wrong... sounds like an exam
i have a question that may be very dumb but why isn't the bools recognized ? is it because of the class ?
Where is this second screenshot from
If that is a switch statement, then that is the wrong way to write it
Also, this is why tiny bits of cropped screenshots are useless
you mean before or after when you're saying where ?
What?
what do you mean where it comes from
Where is this code written
it's from the same script
📃 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.
See how they are in different classes though?
You have to reference the achievements inventory class to access the variables
how do i do that please ? ^^
just write the same line of code in the class ?
I don't see how that could be what you want
i don't know x)
Referencing is one of the most basic parts of programming. I recommend a c# course like this
https://www.w3schools.com/cs/index.php
It's a crucial thing to know before using Unity
thanks for the link ^^ i followed a few tutos and guides but there's still a lot of thinjs i havn't discovered yet :)
If they didn't go over referencing, then unfortunately they were not good tutorials or guides
I recommend avoiding youtube at first btw
yes i guess ^^
or maybe they were but i havn't understood well '-'
does anyone know what these errors are?
Something went wrong internally with the editor
Restarting usually fixes that kind of thing.
I sometimes see that when undoing and redoing things that modify a list in the inspector
e.g. "serialized object disappeared!"
if i change this script to an interface would that make it so i can reference and use it from other scripts?
https://gdl.space/duxisolubo.cs
so like if i had a rock that i could throw, i could pick it up and throw it but not in the same script
Interfaces are usually for specifying an implementation, and such that you could reduce what needs to be passed in a reference.
You've may seen examples of like an IInteract interface that people like to implement, and it's pretty helpful by exposing the character's interact method without having to pass the whole character reference.
so would using an interface be a good choice for my case?
And when it comes to polymorphism, it doesn't always have to be a character, as you can implement an IInteract on a box if it implements that specific interface.
It depends on your requirements, but for that specific script I can't think of many reasons why someone would have a IPickup implementation.
Some examples of character interfaces is having a root interface of IEntity that branches into IPlayer and IEnemy
well, what i want is to have different functions for different items that only can be used on Pickup()
in that case the implementation of that behavior would be on the item itself
how would i get it to only work on pickup() though?
IPickup
public class SomeThing : Monobehaviour, IPickup
{
public void Pickup() {} // this method is forced because of the interface
}```
Then you can do `GetComponent<IPickup>();`
When you pickup an item you can call a specific method that all items implement.
thing is, you probably only going to have a single type that you pick up and that being a type of Item.
so interfaces wouldn't make too much sense here either
what about abstract classes actually
But going back to what I said previously that you can implement interfaces to lessen the amount fields, properties, or methods that the reference of the item exposes, so sure you can add one.
GetComponent<IPickup>();
inside the items script itself?
I usually just stick to abstract classes, but I do have interfaces like an IInteractable because there are many types that you can interact with unlike picking up a single type. (Depending on your implementation, but usually everything I pickup derives from a type of Item)
so would making the script an abstract class be a better fit?
If you want items to behave differently on pickup, you would have a OnPickup() method that you'd implement as an abstract method.
on the items themselves
so i would need an OnPickup() method on EVERY item i want to pickup?
You don't have to implement the functionality, but if you add an abstract method it needs to be eventually there in the derived class.
alright gotcha thanks
How do I get a custom composite to show up in Unity's Input Actions GUI?
in a card game is it better to use cards as scriptable objects or objects of a class "Card"
The default data as SOs, but the actual instances and mutable data in the game as a class
by default data you mean stats and that stuff?
Yeah, and maybe images and stuff
Well, mutable means it can change.
I dunno what kind of card game this is, but in MTG, the attack and defense can change from buffs and things like that. You would do that in the class, not the SO
Do you know what an instance is at all? Not sure how much I have to explain for that part
yeah, dont worryu
oh okay so I could create both
Ok, then just the cards in someones hand I mean, and in the deck
Yeah
like a SO "Card" and a Class "Card"
Id give it different names
Okay, I guess it is less confusing that way
You could have ur "Card" class, but Id name ur SO script SO_Card
for values that do not change at all
and the Class for alterable values
And the deck should be a List of GameObjects or a List of objects of the class "Card"?
List of SO's
I would do CardData. Try not to have types in the name. It's recognized as a code smell
Whatever suits you 😅
Not sure if you have, but you could skim through this document about SO's
https://docs.unity3d.com/Manual/class-ScriptableObject.html
But I don´t really know how to use both
The class would just be generic and draw data from the SO to populate itself when instantiated
If you mean me, then yeah, that is awful lol
Pretty standard for unity docs though
What?
Oh, i thought you meant the name, since we just talked about it
so to make myself an idea, what values could be in the SO
image, description
Name
Depends on what the game does
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.6/manual/ActionBindings.html#writing-custom-composites
Using this doesn't give you a composite that shows up in the Input Actions GUI. Not sure where else to look
In MTG, you may have attack, defense, cost, image, name, landType, etc
yeah take that for example
Might wanna ask in #🖱️┃input-system
ty!
in MTG what atributes should be in SO and in Class
The list I gave should be in the SO
The Class should have all the same, which would be copied FROM the SO
And maybe more references needed to just run the game
i have read a few things about referecing but i still can't understand well what i have to do. does it have to do with inheritance ? should i use public class AchievementsInventory = new AchievementsInventory() ?
excuse my ignorance but I´m not getting it, sorry
No, nothing to do with inheritance
Which part?
i can't understand that x) excuse my dumb
which reference should i use ?
singleton ?
It looked like you were creating a c# class (not monobehaviour). So wherever you create that class, you would have a reference.
MyClass foo = new MyClass()
foo is a reference to that class
So, foo.MyValue
Are you following a tutorial?
could you make an example (little, not precise) of how you would do the Class "Card" Script?
I'm on my phone, so not really right now
i try to change the value of a boolean (fa1) from the AchievementsInventory class
public class Card : MonoBehaviour
{
public string Name;
}
And all the rest of those values I mentioned
Oh, dont worry bro
Hey, guys! I have an issue with a functionality of my game and I stuck like 3 days already can't find the solution. So, I have an UpdateTimer() method where I am updating the timer, whenever the game is not over. What I want to accomplish is whenever the game goes over to freeze that timer. I have tried to use boolean to make it happen but nothing happened. I have checked every possible way to fix it, like I have watched so many tutorials etc. I am really thinking if I just lost something or put something in my code and now I can't notice that. Please can someone help me with that in thread? Is someone available like for 20-30 minutes and help me find the solution.
both in Class and SO?
Show the code again
Yes
referencing each other?
No
You CAN do it that way I guess, but that gets muddier imo
okay so declaring it in both separately
I would just have the exact same variables in both the class and so, and just copy from the so to the class when you create a card in during runtime
Yep
i all the tutorials that i've followed i can't remeber any use of reference
but only alter them in the Class
inventory is the reference
Right at the top
Exactly, yeah.
Class will be in memory. SO is a file on disk. They are...kinda static. You can create new ones but that is awful
So in some way I am creating the same card but two times, one in so and one in class
so i should write that ?
Yes! You got it
Well the SO is an asset. You would create that in the editor
The class is so you dynamically create decks and hands from those card "prefabs" you made as SOs
is it possible to switch the value of a bool simply ? or do i have to use if/else
You mean like toggle it?
inventory.fa1 = !inventory.fa1
yes that's it thanks
it took me a long time to undestand x) but maybe i hardly understand guides due to my non-perfect english level
so in the creation of a deck, how would SOs and Class work?
The deck would be a list of the classes
Those card classes would be instantiated by drawing the data from SOs
How do you start/stop a particle system in scripting?
okay and SOs what function do they have
They would be used when creating the classes
OMG it works à merveille
I am getting errors for my code saying that in my MazeNode code there is not definition for RemoveWall but i have a public method right here and I've become more confused
The class has NO data in it to start with. You create it, get the SO you want the card to be, and copy the data into the class. Then from then on you only use the class
OOH
Show the full !code for MazeNode
📃 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.
No problem at all. Glad I wasn't too confusing lol.
I can be that way a bit sometimes
never bro, thanks again
Is there any command to copy the values of the Scriptable Object to the object of "Card"?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
theres the full code for everything so far
Save all your scripts and restart Unity. See if the error persists
And just for the final question about this, the SO I create is (I hope you understand) Charmander or Fire-type Pokemon???
it might not have compiled and you can force a recompile by restarting
alright thanks
Yeah -- assuming your IDE is working, it's not seeing the errors that Unity is seeing
which suggests that Unity hasn't seen the latest changes
Charmander
I think the SOs would make most sense as the most concrete thing, so the actual card itself.
after closing it, it just does this
I've tried using ParticleSystem.play() and
ParticleSystem.stop() but I don't seem to be able to start it again after?
Looks like the variable walls of MazeNode has not been assigned. You probably need to assign the walls variable of MazeNode in the inspector
Using GameObject.Enabled won't work since it hides the particles
Okay bro, thanks a lot
right, ill try change it and see what happens
I'm not sure how to properly pause a ParticleSystem
Im not sure why this is an issue because the code was working and now its saying its not assigned in the inspector im not sure how it isn't?
Did you check every MazeNode in your project? Type t: MazeNode in the search
and look to make sure they all have walls
You changed the scene
what is an enum exactly?
they do because they are all clones of the original
An integer in a hat
Did you check or did you assume
Because your error makes it pretty clear that there is at least one MazeNode that doesn't have walls set
fair point
so, you were correct, for some reason all my nodes have lost all their walls apart from the positive x
how do i fix this?
Assign the missing walls
https://hastebin.com/share/muyoqulaxe.java
Hi, can someone check over my code bc im trying to render 3d objects in a ui but it dosnt display it for some reason
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
that sir is a blank page
whats difference with the TMP and just normal text ?
Better performance, looks cleaner, more features
there's literally no reason to use legacy text, ever
That's why it's under the "Legacy" menu, you're not supposed to use it, it's provided purely for legacy purposes in case a project was made before TMP was a thing
owkay thx guys
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hell does this mean
and can u elaborate on the problem? does it just not show anything? are there console errors?
no errors, just dosnt show anything
is the texture present?
i dont think its being set correctly
!code
Can't see it as is
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Call to DeinitializeLoader without an initialized manager.Please make sure to wait for initialization to complete before calling this API
Seems pretty straighforward. You are trying to use some API (method calls and whatnot) before some manager has been initialized. You have to wait some amount of time before calling DeinitializeLoader
im trying to make a quit button as the first proper bit of code and ive gotten like 6 diffrenet error messages and none of what im trying works lol
Where can I ask cinecamera doubts?
Well, are you trying to quit right after starting the game?
ya, it doesnt appear to be complete..
i trying to make a main menu
Thnx
then im going to try make the game
ive spend like 2 days and all ive got is this
none of the buttons work unfortunately
Ok, can you show the inspector for the quit button?
just making the background on gimp took me 30 mins
And the code that it calls?
can u show me the rect transform?
coppied of a youtube tutorial since what chatgpt told me didnt work
Yeah, don't use gpt
also new error message with this new script
Can you show the inspector for the button?
just fyi Application.Quit doesnt work in the editor
alright.. i was making sure it wasn't 0,0,0
it is the only reason i have what i have lol
it seems the script is incorrect
if (renderTexture != null)
{
rawImage.texture = renderTexture;
}```
can make sure the rendertexture is being assigned correctly
!learn
And https://www.w3schools.com/cs/index.php
And Tutorialspoint
And the pinned materials here
Do not use gpt until you understand everything it suggests and can verify it. At that point it becomes useless though
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ive never done this but i have some friends who have for character weapons stuff
You can't put a script into the OnClick section
You put an object WITH that script on it there
The script could be on the button itself
is it possible to change a sprite or sprite color in a different scene if yes do i use getcomponent?
ye it outputs (UnityEngine.RenderTexture)
And just drag the button object into its own onclick funtion
🤔 not really sure.. if it were me id try to step thru the code.. one bit at a time
and find out where it faults out
If by different scene you mean one that is not loaded, then no
all this just to make a main menu
wonder how long its gonna take to even make a text based game
Have you done this?
#💻┃code-beginner message
i started it
making a menu is pretty easy.. you can have all ur menu functions in one script.. (public) and u can just assign the same script to all the buttons calling their respective functions
Finish the first two or three pathways before continuing with this project
dang ok
basically i want have a menu(scene) where i can change a skin, im just using cubes so changing skin would be chjanging color in sprite renderer i want a button in my menu scene to change the color in the sprite renderer from a different scene(game scene)
ud have to cache the value and then act on it when the scene loads in
Is the other scene loaded, or not?
yes
I mean at the SAME time as the main menu, to be clear
Or do you change scenes?
if its loaded in its the same thing as changing anything else.. u can search thru the hierarchy and find the object and change it
i stopped since i couldnt find what it told me to do the lego minigame thing
Then you need to use DDOL or an additive scene to have persistant data
if its not loaded in.. u got two choices.. u can cache the variable like i mentioned and change it once its loaded in.. or load it in to change it
id do the first.. b/c if u load it in.. ur gonna have to modify it so its not visible.. or functioning on top of ur menu
ty for ur help, just thought of a diff idea for this
ya sorry mate.. i dont see anything in the code that catches my eye..
if i had to guess it would be a setup issue..
but id step thru the code.. one part at a time.. and make sure its functioning as u go
u got alot going on in there
oh wait.. idk much about it but i see where u create the render texture but ur not saving it or applying it to any material or anything..
you create the texture.. modify the camera to look at it.. but then u just destroy the camera
and return the texture that u created.. but never done anything else to..
they are working seperately
@zinc warren https://docs.unity3d.com/ScriptReference/Texture2D.Apply.html i think
well doing a KeyDown/ButtonDown inisde an ontrigger 1 frame event, you will never have the required speed/sync to do it
solution is simple. Dont put input handling inside that
How do I access a TextMeshPro in my Logic? I was trying to access it with public Text HighScoreText; but it won't let be drag the object in. Despite being a text object
TMP_Text
Text is old component not textmeshpro
its not Text..
got it :P
and you'll need the using TMPro;
yo this is stupid but how do i get my scene and game view back :v My computer was asleep and the keys i pressed to wake it up made it disappear
Window
Looks like you just maximized the project window
Layout > Reset Layout
or shift + spacebar
Unmaximize it
ty 
now overlapcircle isn't working :((((((((
I've tried to reference the other walls in my code but it ended up messing it up more. How do i fix this code so that each node has all its walls assigned to it during grid generation and then walls are deleted during the maze generation?
https://hastebin.com/share/onohaligom.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i made 3 list that each changes the colour of the node and it should be fully green and then have a maze at the end
instead i get this
wdym "not working"
i made the range 0.001 but still when i click enemy dies
you should explain what your code is supposed to be doing and why do you have a trigger with overlap inside
ok ok i solved the problem
forgot to set a layer
:PP sorry
Hi all, I'm having a bit of a brain fart and can't for the life of me remember what I'm doing.
I want to cast a screenpointray at a certain distance (200m for example) and then have an object point at the 'end point' of the ray. But my mind is drawing a complete blank on how to do it (I can remember how to make the ray 'hit' an object, but not how to do it without hitting an object (if that makes any kind of sense. lol.)
in the code you showed there was no layer so I didnt even bother thinking about that lol
hit.point
is the Vector3 / (2) position of where the ray hit..
yep i should've informed you :P
then ud just look at that
Is that not just for when the ray hits something though?
so u want it to ignore all the hits up until the 200m mark?
I want it to ignore everything, period, but limit the ray length to 200m (this I know how to do, it's the ignoring everything part)
if its ignoring everything until the 200m mark why even use a raycast?
just use ur starting position and add 200m to it
in the direction..
raycasthit2D has a .distance field for how far it went
he only wants UP TO 200 m
i was going off of this
i think 200m is his max search range
I want the mouse position on screen to control the target point of a weapon (so that the weapon always points at the mouse pointer on screen), but I don't want any objects to 'interfere' with the distance (I know I'm not being very clear, sorry)
raycasts hit colliders
the point of a raycast is to ask about where colliders are
if no colliders are involved, no raycasts should be used
use a layermask.. and make an invisible plane or collider that ur ray can hit..
then it wouldnt be hitting walls obstacles etc
!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.
the UI system has a strange convention with using “raycasting” to hit UI objects, but i don’t think that is what you are looking for here
looking at your code will not explain what you want
you need to articulate it with words
//Player Facing Mouse
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if (playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
targetPointActual = new Vector3(targetPoint.x, 3.12f, targetPoint.z);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
targetRotation.z = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, mouseSensitivity * Time.deltaTime);
}
I've used this snippet before for top down, but brain is cabbaged and couldn't figure out how to translate it to 3rd person. lol.
oh now that i see the code, that changes absolutely nothing
my guess is hes talkin about something like this.. where that crosshair wouldnt be On top of the wall
but more on the ground.. where the mouse is
in which case id just use hte ground as the layermask
he wants a weapon to point at your cursor
but then something about objects interfering, which doesn’t make sense
if you can represent the position of your cursor in world space, you can rotate an object to point at it
not sure where other objects are involved here
Here's a screengrab of my scene. As you can see there are a crapload of different types of objects (trees/signs etc. etc. etc.) so I want the weapon to point at the mouse pointer at a distance of 200m at all times, without all of those objects interfering.
- why do any objects interfere
- mouse pointer exists in screen space. player is in world space. they cannot be 200m appart because they exist in different space
it the cursor is at (100,400), that means 100 pixels right, 400 pixels up
Hi hi I'm new here and I have a question to ask if anybody could help me.
then ask the question?
dont ask to ask
Which is why I want to use ScreenpointtoRay. So that I can get a point in 3d space to point at. With all the objects in the way it could lead to 'jerky' movement etc. if the mouse goes over something really close suddenly.
they could exist 200 meters apart.. when u use the mouse position to raycast into the world space.. u get that hit position.. and then it could be 1m from the player or 200m from the player
w/ a layermask my ray wont end up on top of object or w/e id just cast str8 to the ground
use a layermask and a singular plane.. ur casts will all hit that plane..
Y axis would always remain the same..
no jerky movement
So I could add an invisible plane 200m in front of the player (parented to the player so it sticks in front?) (sorry, just trying to be clear while I get it straight in my head. lol.)
that could work
Basically I'm trying to make a indoor navigation app for android using vuforia and navmesh. The problem I'm facing is that the documentation is quite old of Vuforias site. For example they say that I should import prefab model to my gameobject area target as a child and then go to window -> AI -> navigation and then press bake. Now that option is no longer there
Okay thank you (and thank you for the patience. lol.)
if(Input.GetMouseButtonDown(0))
{
Plane plane = new Plane(Vector3.up,Vector3.zero);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float entry;
if(plane.Raycast(ray,out entry))
{
dragStartPosition = ray.GetPoint(entry);
}
}```
Basically this piece of code, but modified so the Plane is at camera.forward * 200 and points towards the camera
theres also this version of raycast.. that u can just create a plane in ur code
Thank you guys, seriously 🙂
Then once you hit it, you have the point, and can rotate the player towards (hit.point - player.position)
Yeah, I knew I had all the code (more or less), was just translating it to be 'forward' instead of up which was boxing my noggin. lol.
uh huh, really shouldn't be doing this stuff after 12 hours of fluid simulation maths. lol.
Can sm1 explain to me for a second why its not generating a maze kind of just lines with stops in them sometimes? I thought i was careful to make sure that each direction and wall match now im confused.
https://hastebin.com/share/zevikunele.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hello im fairly new to this, can someone explain why the capsule wont fit in the hitbox in green?
Check the pivot points, and not in center mode
not code question
Have you looked up the unity docs for navmeshes
Yes I did. The problem is that every tutorial was based on that and I can't even get to the point where the navmesh would be just the floor. It creates a navmesh through the entire office meaning floors, walls, desks...
that's how the old system would have worked, too
you can set the NavMeshSurface to only care about physics colliders
you can also add NavMeshModifier components to make some objects produce non-walkable areas
this would be appropriate for a desk, for example
this is a code channel, this question belongs in #💻┃unity-talk
The CharacterController has its own collider, you do not need to add one - it looks like you have one as a child, remove it.
read the channel topics 😄
Plane playerPlane = new Plane(Vector3.forward * 200f, Camera.main.transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0f;
if (playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
dogMiniGun.transform.LookAt(targetPoint);
}
Sorry fells, am I being monumentally dense about this? Can't seem to get this to work at all. 😦
in what way does it "not work"?
My weapon doesn't rotate
that Plane constructor looks very wrong to me
You're passing weird stuff to that plane
it takes a normal vector and a position
the plane cuts through the camera
you probably meant to do new Plane(-Camera.main.transform.forward, Camera.main.transform.position + Camera.main.transform.forward * 200f);
this plane's normal vector faces towards the camera, and it passes through a point 200 meters in front of the camera
Okay, thank you.
your plane's normal vector faces in the +Z direction and it passes through the camera
Yeah that fixed it, thank you so much.
When declaring an RGB color, is there a way to change the format from 0-1 to 0-255 or do I just have to divide everything by 255?
I am using this script to resume my game from a button but once I resume the game and all my inputs and controls stop working
divide by 255f
there could be so many reasons for this. i don’t think we could help with that unless we went through all your code base, which we won’t do.
I though so. kinda inconvinient, but ok
you could use Mathf.Lerp and Mathf.InverseLerp if it's more clear to write it that way
note that if you're making a Color, the values should be in the [0, 1] range
Yeah. kinda odd when the default mode for colors in the inspector is 0-255
That's just how most people are used to thinking about colors
since that's how you'd edit 8-bit-per-channel RGB
Nothing here affects inputs or controls
I want to create a List of transform arrays, is it better to use List of Lists?
depends
is the size of the list going to change at runtime?
do you want a list of lists, or a list of arrays
To put the precise example. The player can select between different attack formations of 4 determined positions
So I imagined the best thing is that all the formations are included in a List and the positions in those formations are in different Transform arrays
you can do Lists of arrays as Carwash said, if you have constant size of Arrays inside the List.
Oh okay
but it is also okay to use List of Lists no big diff on performance if u use only 4 transfroms in list.
Can you represent the formation mathematically instead of storing every position? That seems better and scales more sanely.
got it, Thanks bro!
probably better to ask in #🏃┃animation as that doesn't really sound like a code question, for this code channel
Sorry, I must have overseen it, as I had looked. Thanks!
best delete from here before posting there, otherwise you'll probably get told off for crossposting
i have these editor stats and when i change a bool in editor;runtime it resets to its value that it had when i started, same with string mat and price,but when i add/remove an element it works, someone knows why, code is nothin thats changing it
because changes in the inspector at runtime aren't saved
what happens with time.timescale in multiplayer
i mean in runtime, when i change it flicks instantly back to its value like a code saying e.g. price = 0 every frame, while runtime
it continues to exist
xd
i mean like when my turs 0 after pressing a button what will happen with oither players
Unless you change the value, it does not change
oh, I see now. It will only do that if code is doing it, or perhaps a timeline
I dont think I am, I'm parenting it to an empty for my 'hands'
Depending entirely on how you're handling multiplayer and any timescale changes, this could be literally any result
hm okay, ill recoard and send a short vid so you can see
🤔
how can i make a List of Lists?
public List<Transform> positions = new List<Transform>();
List<positions>?
The same way you make a list of Transform
Just put the type in the <>
In this case, your type is a List<something>
List<List<Transform>>?
calculation in HandleSpeed calculates how much force to add to reach speed limit, problem with it is that it doesnt add the force in the slopeMoveDirection because slopeMoveDirection is only used in the targetVelocity calculation and not in the final calculation, so the force doesnt get added in the direction of the slope but just forward which causes my character to bounce when walking down a slope since the force is added forward and not down for example with the slope angle
Handle Input - Update ```x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
moveDirection = orientation.forward * y + orientation.right * x;
slopeMoveDirection = Vector3.ProjectOnPlane(moveDirection, slopeHit.normal);```
Handle Speed - Update ```Vector3 targetVelocity = slopeMoveDirection.normalized * moveSpeed;
Vector3 velocityDifference = targetVelocity - rb.velocity;
slopeMoveVelocity = new Vector3(velocityDifference.x, 0, velocityDifference.z);```
Handle Movement - Fixed Update rb.AddForce(slopeMoveVelocity * acceleration);
basically what i need to do is to include the slopeMoveDirection.normalized in the final calculation to add the force in the direction of the slope instead of just straight as its doing now because slopeMoveDirection.normalized is not involved
I cannot change the permissions of a method from the child class right? Like if I make this (parent//child) these are two different methods or what?
you must use the override keyword if you want to override the parent function, otherwise it will be treated like a new function
They're two different methods unless you use override
Doesn't the virtal makes so I don't have to override?
virtual makes it so you can have a base implementation that you can override
if i create an interface for Interact() can i just use that on any object that uses a script i reference the method Interact() in, but in that script i specify what it does?
public class PlayerInteract : MonoBehaviour
{
[Header("Inspector Variables")]
[SerializeField] public new Camera camera;
[SerializeField] public float rayDistance;
[SerializeField] public TextMeshProUGUI objText;
// SCRIPT ENABLED VARIABLES
AudioSource pickupSound;
Rigidbody itemRb;
void Start()
{
objText.gameObject.SetActive(false);
objtext = null;
}
void Update()
{
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, rayDistance))
{
if (hit.collider.CompareTag("Interactable"))
{
objText.gameObject.SetActive(true);
objText.text = hit.collider.gameObject.GetComponentInChildren<TextMeshProUGUI>().text;
if (Input.GetKeyDown(KeyCode.E))
{
Interact();
}
else
{
objText.text = ("Can't Pick Up")
}
}
else if (hit.collider.CompareTag("Untagged") || hit.collider == null)
{
objText.gameObject.SetActive(false);
}
}
}
}
If you have a MonoBehaviour that implements an interface, calling GetComponent with that interface as the type will get any behaviour that implements it
So you can get whatever behaviour implemetns your Interact method
sorry im really confused on interfaces and stuff could you give an example maybe
If you made an interface, IInteractable, and gave it an Interact method, then calling GetComponent<IInteractable>() would get any behaviour on that object that implements the interface
and then you could call Interact on it
would i call GetComponent<IInteractable>() on that script i just sent?
You would call it on whatever object you want to get the component from
on whatever script is on the object i want?
What object do you want to get an IInteractable from
one i can interact with like a cube i can pick up
How do you intend to know which object that is
by sticking a script on there calling IInteractable?
How are you going to decide which IInteractable to call the function on
idk
randomly of course
then you're going to have to figure that out
what do you mean which one?
I mean which one
You could put an IInteractable on every single object if you want
yeah that was my plan
how are you intending to know which one you want to interact with
in general, when you GetComponent<IInterface>(), you want to find a unique answer, OR you want to call GetComponents<IInterface>() to get an array, and call your method on all of them
setting a GameObject variable that is set when i click E on it i think
So then that would probably be what you call GetComponent on
To get the IInteractable component
so variable.GetComponent<IInteractable>().Interact(); ?
yes
alright cheers 👍
how can I resize my main camera?
get a bigger monitor
I mean, instead of a rectangular size, I want a square
there's a resolution dropdown at the top left of the play mode window
or apply black marker to the left and right sides of your existing monitor
anyone?
if your game has a resolution of 1024x768, you can realize that 768 is 3/4 of 1024. So, if you change the width dimension to .75, 1024 will become 768 and the view will be square. However, the view will now be off center. To fix this, change the x value to 0.125
someone help i think i messed up my project, i was makign siome changed to my character and...??? everything got displaced? i panicked a bit and then ctrl + z a little too much and now i think i ended up removing waaayyy to much but the character is still messed up??? all of its sprites r like in one position...
now i cntrl + y everythign back cuz i remebered that i made a change to the player perfab itself but like how do i reverse that? and it looks fine i nthe prefab editor but not in the scene... help this stresses me out
maybe send screenshots
i think its because i moved everything udner a new parent called body
well not eveyrthing but yea
cuz some parts werent part of the prefab
maybe i should have updated the prefab and added thsoe parts
if the prefab is fine but the version in teh scene isn't you can just delete it pull the prefab back in
Revert changes also works
but.. all the connection the prefab has to the other scene objects
ud have to fill in the references
do u mean somehting other than cntrl + z?
yea, at the top of the prefab (when u click the scene) at the top if theres overrides u can revert them back to w/e the prefab has set up
but i think thats when u change stuff of the prefab (in the scene)
not in the prefab window
like here.. on this prefab ive changed all those things (in the scene)
if i hit revert.. it'll all go back to whats the prefab view has
if i hit apply.. it'll change the prefab to w/e the scene version has
In an RPG game, my team of characters should be a List?
i stil ldotn get where this is
its at the top of the inspector.. when u click the prefab in the scene view..
if its not there.. ur prefab stuff has already been saved.. and it is wat it is
but i dont htink ishould override cuz i got something i didnt save i nthe prefab
is there just no way to revert the prefab change itself
without override
there two different things... override is when u force the prefab to take on the changes of the version you have in the scene..
the revert is the opposite.. it forces the prefab in the scene to take the settings u have of the prefab version
how can i improve on this```float targetMagnitude = moveSpeed;
float forceMagnitude = targetMagnitude - rb.velocity.magnitude;
Vector3 force = slopeMoveDirection.normalized * forceMagnitude;
rb.AddForce(force * acceleration);```
the movement works
but it feels slippery
add a physics material.. with higher friction..
i already have that
then adjust the forces that you'll need to overcome the new friction
well make it higher
its already at 0.9
here is the thing:
In scene there are important things not part of the prefab attached to it. But everything under the players body took a new position due to a perfab change.
in the prefab the character looks right at least, but doesnt have some of the important stuff attached
am i.... cooked?
if its that bad off and u cant just apply or cancel the settings ur gonna have to manually fix it
u can try to add a damping force..
when theres no input it'll dampen the velocity and slow it down a bit faster
will... the animations be fine at least?
no clue.. u can unpack the prefab in ur scene..
that way u can have both versions of it.
in order to fix it
it'll make it a regular object
lol what i just unparented everythign under the body and dleted it in the prefab and... everythign went back to normal? i think
lmao idk man.. ¯_(ツ)_/¯
gotta pay more attention man
fair enough..
i suppose i should update the prefab now
to add the new stuff
so in case i need to override i nthe future
also.. am i tripping or do i just not have a override
thats the prefab view...
Override only shows for prefab instances in hierarchy,
^ when u select the prefab from the scene (the regular inspector)
is where ur override / revert stuff is
u have prefabs inside prefabs btw
im on the newest version of unity going through one of the unity pathways and i cant see the option for any of the mircrogames it is telling me to do anyone know why or how to fix?
Use the same version as the pathway is for
also, this is a code channel..
delete and ask in #🏃┃animation
Oh sorry I didn't see that channel, I tried looking.
If you can't find a relevant channel, then #💻┃unity-talk is the place to ask.. not a random channel!
okay so just to be sure, "APply all" takes whatever i made in the hierchy and adds it to the prefab?
Yes, it will apply all changes in hierarchy to base prefab
Hello ! here is my script that works well, when i click the bfa1 buttons its color changes to green. But i want two more things :
I want the default color of the button be red if a bool is false, and green if a bool is true,
and I want to switch these colors on click (make button red if it was green, and make it green if it was red). For the moment, on click (CaseFA1) the color is changed to green.
How should i do ?
I tought i could check the value of bool on start, and check it on click too. But i'm not sur how great it would work to copy/paste the last block of Code. Maybe should i create a changetored function and a changetogreen fonction ? does it works if not affiliated to any object ?```using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;
public class SaveData : MonoBehaviour
{
public AchievementsInventory inventory = new AchievementsInventory();
public Color green;
public Button bfa1;
public void Start()
{
LoadFromJson(); //loads the bool value
}
public void CaseFA1() // on click
{
inventory.fa1 = !inventory.fa1; //switch the bool
SaveToJson();
ColorBlock ccbfa1 = bfa1.colors;
ccbfa1.normalColor = green;
ccbfa1.highlightedColor = green; //changes color to green
ccbfa1.pressedColor = green;
ccbfa1.selectedColor = green;
bfa1.colors = ccbfa1;
}```
In an RPG Game the Team of characters should be a list?
thanks
You really need to work on naming your variables properly
But the method you are doing seems fine i guess?
On the onclick method of the button just add similar block for whatever color you want the button to turn into
This seems to be a vague question. Different characters would probably be prefabs, but you can store them in a list inside some static game manager script if that helps you. You probably need to expand more on your question tho
Although I would extract method and change colors from there for clarity purposes
yeah, you are right, I simply wanted to know if the party of characters should be a List
what would the context be?
for example take FF7
if you are often going to run code that is related to all the chacarters in a party, then yea adding them all to a list would probably be beneficial
Imagine a charcter isnt on the party any more
so i do
if bool = true
ColorBlock ccbfa1 = bfa1.colors;
ccbfa1.normalColor = green;
ccbfa1.highlightedColor = green;
ccbfa1.pressedColor = green;
ccbfa1.selectedColor = green;
bfa1.colors = ccbfa1;
else
ColorBlock ccbfa1 = bfa1.colors;
ccbfa1.normalColor = red;
ccbfa1.highlightedColor = red;
ccbfa1.pressedColor = red;
ccbfa1.selectedColor = red;
bfa1.colors = ccbfa1;
ccbfa1 stands for colorchangebuttonforceachievement1 x)
Yeah I guess? But again, I would extract the methods first so
If(condition)
ChangeColor(green)
Else
ChangeColor(red)
See how clean that looks?
Less redundancy
yes but why i don't do that is because it actually changes the color of only the bfa1 button
so i'd have to make a function for each button ?
No you can pass in the button in parameter too if that's what you want
ChangeColor(Button, Color)
id say u would need to provide more context
but yea u probably do need a list to create a group/party
idk i havent done that yet, perhaps a more experienced game dev can take over
In the end how you want to store your party characters entirely depends on your use case
should i be clamping velocity in fixed update or can it be in update?
Vector3.ClampMagnitude
One message removed from a suspended account.
This is not a problem of your script
There's an object named "Input Manager" in your scene, and it's missing a script. It has a faulty component, see the Inspector
You deleted some scripts while they were still attached to some gameObjects
For fixing that, do what Spr2 said and when you find the missing script, just delete the reference from the GameObject
One message removed from a suspended account.
- Do you have any compile errors
- Does the file name match the class name
Which script are you trying to attach? Are there errors in the console?
Looks like you renamed your script from PlayerContol (from the warning and file name) to Example
One message removed from a suspended account.
One message removed from a suspended account.
For maximum compatibility, the class name and file name must match
How would i go about using tweens to animate this item from being on the ground to the players hand?
item.transform.SetParent(camera.transform);
item.transform.localPosition = new Vector3(0.79f, -0.53f, 1f);
i already have everything else setup i just need this animation, im using DOTween
Instead of setting the position directly, use MoveTowards to move the position towards the destination
One message removed from a suspended account.
What is a CharacterControl, do you have a class named that
With tweening, use DoLocalMove() after parenting
item.transform.DoLocalMove(x, x, x); ?
Seems like you did some sort of class Example : CharacterControl instead of class CharacterControl : MonoBehaviour?
Okay so i have this problem, and.. i dont know how to really describe it but ill try:
I am trying to make my player be able to parry some projectiles, the approach that i have is that there would be an invisible hitbox that makes a list and adds all the parryable projectiles in it (on trigger enter 2d) and removes them if they are no longer in range. The reason i have made it this way rather than a gameObject that gets enabled/disabled when the player parries is because i only want the player to able to parry (play the animation and such) if there is a parryable object in range. The player sort of "kicks" the projectile away rather than some approach games have where you just shield and whatever touches it well gets blocked or whatever, or you can hit with ur sword and if nothing is there then well nothing happens.
The problem with this is... since the hitbox is under the player parent, when it comes in contact with this hitbox it counts it as hitting the player as well, and i dont want that to happen.
I could spend a whole lot of time splitting the player into two parents.. and making a paarent for those two, then redistributing the scripts correctly.. and all that jazz.
I have also though of going to the script that handles the players collisions and change it make all methods ignore collision if it also collides with the parry hitbox... but...
- idk which solution to choose
and - maybe there is a 3rd better solution?
One message removed from a suspended account.
Read the documentation for the usage of that method
alright thanks
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
i need to add opposite forces in the direction which the rigidbody is moving, how do i do that? ```cs
float targetMagnitude = moveSpeed;
float forceMagnitude = targetMagnitude - rb.velocity.magnitude;
Vector3 force = slopeMoveDirection.normalized * forceMagnitude;
//If input keys are pressed
if(isWalking)
{
rb.AddForce(force * acceleration);
}
else
{
//If the player is moving
if(rb.velocity.magnitude > 0)
{
//Add force to stop player
rb.AddForce();
}
}```
here
Velocity times -1
everythings works well thanks for your answers :)
how can i only clamp velocity of a rigidbody excluding the y?
Get a copy of the vector with zero y, then clamp it
then copy the old y over and set velocity to that
This would reset the y velocity to 0. If that's what you want, sure.
how do i make the serialefield stuff
the what
parenthesis?
ye
you type them
no these one
they're right there next to the enter key
what ones
Square brackets
yep
For attributes
for seriale field
I have no idea what layout that is
Yes that's an attribute
ah forget it
they're right htere.. just figure out the key u need to push to get it
ye
But it looks like you just press the keys
< [ { (
ok thx
Try combinations of the key with Alt, Shift, Ctrl, Fn (if laptop) and it'll eventually input the right ones
thats not a regular english keyboard
press those keys

MB it was a french canadian one srry for forgeting it :(
i just checked
Press these buttons, without any modification, and send whatever it is they type
idk they usually work but wathever i do they dont
I mean you don't know the layout of your own keyboard? It's tied to where in the world you bought the computer
If you enter the text box here in discord and press those buttons, what comes out
^^ ¸¸ alone
^^¨¨with shift
Okay, so, I guess the bottom left theory is out. I have no idea how your keyboard works, but you probably should. Find whatever key combination types the bottom left symbol on your keys
Do you have an "Alt Gr" key on there? On the right of the space bar. You might need to use that
🤯
lmao... soo confusing searching around for that.. every thread saying something different lol
Apparently it's Alt Graph (IBM says alternate graphic), but it just sounds like an angry alt key to me
Alt 😠
i didnt realize how many different keyboard layouts there are
i knew about qwerty vs azerty but apparently theres even sub-types
Yep I have to use that for these on my layout: ~{[|\@]}. Makes typing more inconvenient when programming
any1? 😔
any idea why when i drop my item whilst its being picked up with a tween animation it phases out of existence? i tried using a coroutine and yield new waitforseconds to make the player wait for the animation to be over before he is able to drop it but that didnt work.
Most likely because the tween on the local position is still in progress when the object gets unparented. The frame of reference of the object suddenly changes (the local position is identical to the world position when an object has no parent), but the tween continues applying modifications to the local position. You'll probably find your objects near the world origin (0, 0, 0) when you make the bug happen.
that would make sense
Solution: kill the tween if the object is dropped before it's completed
alright ill have a crack nice one
Hello everyone. I have a question about Images & RawImages and I don't know WHY it works that way...
Basically, when I run this code :
public Image image; // Ref set in editor
public void SetImg() { image.sprite = Resources.Load("Sprites/MyFileName") as Sprite; }
It sets the Image to none instead of the correct one
However, when I do the exact same with a RawImage instead :
public RawImage rawImage; // Ref set in editor
public void SetRawImg() { rawImage.texture = Resources.Load("Sprites/MyFileName") as Texture; }
It works properly and as intended.
I would appreciate an explanation as I can't really put my finger on it. Thanks
Log what the resource loaded. If it's null, it wasn't successful.
This method returns the asset at path if it can be found and if its type matches the requested generic parameter type, otherwise it returns null.
https://docs.unity3d.com/ScriptReference/Resources.Load.html
Can a .png resource be loaded as a Texture and not as a Sprite ? Because it's the exact same one I'm loading in both cases. Except if I'm missing something, it should work as intended
A sprite isn't a raw image
I know, I'm loading as a Sprite for Image and as Texture for RawImage
It works when I load it as a Texture for RawImage. Why doesn't it work for Image when I load it as Sprite ?
Same exact file
A png isn't a sprite
Ok so. For Image, when I drag and drop it on the "Source image" thing, it works. Why ? 
What source image thing?
If you want to create a sprite dynamically, use https://docs.unity3d.com/ScriptReference/Sprite.Create.html
Source Image The Texture that represents the image to display (which must be imported as a Sprite).
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Image.html
It was probably imported as the correct type for you when you added the image to the project - I'm not sure, I do not see your assets.
The one to the left is a Texture2D and the one to the right is a Sprite
So do we agree that loading this as a Sprite should work ?
I don't know what you're saying but bolt is unknown and the source image expects a sprite according to the docs.
How would I make a script where the UV of any white colored vertex group gets controlled by the movement of a bone
Raw png files are not sprites.
Ooh, interesting.
You'd use a shader probably
I know what the doc says and I also know what you're saying. It's okay, thanks for trying to help 🙂
how would i make a shader do all that
You could ask in #archived-shaders
I'm not well versed with them.
im trying to make a walljumping code like the one in ultrakill and how would i go about it
how do i instantiate a object under a specific object
when i mean under i mean like it spawns as a child of a specific object
i am aware of what you meant. did you read the docs?
yes im still confused
did you see how most of the overloads for Instantiate take a parent parameter to specify the parent of the object being instantiated?
yeah but why is it a transform not a gameobject
why would it be a GameObject type? but also why does that really matter? every GameObject has a transform and every Transform has a gameObject
idk i guess it being a transform threw me off a bit
bro what was rick tryin to do
how do i convert a array to a new type so for example i want to convert it from gameobject to text objects each gameobject has a text component
text is just a component of a gameobject, so cycle through your game objects and grab each of their text components and stick em in a container
You can't just "convert" the array.
A GameObject is not a TMP_Text
apparently with linq u can
It doesn't matter that the game object happens to have a text component on it
It's not a text component
i cant make a new array and have it equal all the text components from the gameobject in the other array
You can iterate over a bunch of game objects and try to get a TMP_Text from each one, sure
But it's very important that you understand that this is not just "converting" the game objects into something else
You can make a new array. .Select(g => g.GetComponent<TMP_Text>()).ToArray();
see ^ magic
and I also have to wonder why you can't just reference the text components from the start 🤔
NetworkClient[] networkClients = NetworkManager.Singleton.ConnectedClientsList.ToArray();
players.Select(networkClients => networkClients.GetComponent<NetworkObject>().OwnerClientId).ToArray();
so smth like this or no
networkClients on line 1 has nothing to do with networkClients on line 2
if you right click where the underline is at the error, VS will fix it for you (implement interface methods or something along that line)
players.Select(networkClients => networkClients.GetComponent<NetworkObject>().OwnerClientId)
For each player, this tries to get a NetworkObject from the player, then gets OwnerClientId from the NetworkObject
players.Select(player => player.GetComponent<NetworkObject>().OwnerClientId)
a better-named rewriting
this doesn't make sense, though
Then you haven't configured your !ide, as has been requested multiple times
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
what does player equal though
Did you consider doing all of the other steps too
!ban 1145389547350413323 rabid homophobia in bio
el_conquistador____79724 was banned.
👋 cya fucko
A well, that took care of that
L + no ide + homophobia in bio
player => player
this is an anonymous function that has one argument
the argument is named player
this function just returns whatever you give it
public List<int> Foo() {
return players.Select(player => player.id).ToList();
}
public List<int> Bar() {
return players.Select(GetId).ToList();
}
public int GetId(Player player) {
return player.id;
}
Foo and Bar do the same thing.
The pattern would be: (argument) => statement;
you don't need parens for a single-argument anonymous function.
but yes, you, more generally, use parentheses for the parameter list
Where yours would be (player) => player.GetComponent<NetworkObject>().OwnerClientId
Was simply being explicit
aight thanks
Select is a LINQ extension method. You add using System.Linq; to access it.
It works on any enumerable thing: lists, arrays, etc.
for each item in the enumeration, it runs the method on it
List<int> numbers = new() { 1, 2, 3 };
List<int> doubled = numbers.Select(x => x * 2).ToList();
ToList() makes a new list out of the sequence
Relative to what Mao said #💻┃code-beginner message , it'd look something like this if you aren't using linqcs Text[] texts = new Text[gameObjects.Length]; for(int i = 0; i < gameObjects.Length; ++i) texts[i] = gameObjects[i].GetComponent<Text>();With the above, the new array would have a bunch of nulls wherever a component wasn't present. A List implementation would look something like thiscs List<Text> texts = new List<Text>(gameObjects.Length); foreach(GameObject go in gameObjects) if(go.TryGetComponent(out Text text)) texts.Add(text);
{
Debug.Log("You Win!");
}```
This is my trigger code, I have rigidbody2D, I have 2 objects only, a player and a box, both with colliders, the trigger is on for the box and for some reason the trigger refuses to go off when colliding. Im using the input system as well, with some code for movement if that effects much (im extremely new, apologies)
Movement code:
private Vector2 movement;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void OnMovement(InputValue value)
{
movement = value.Get<Vector2>();
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
}```
How to post !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.
Show the inspector for both objects
Does this object have a collider as well?
Is this object a ui element?
The one above seems to have a canvas renderer and a rect transform rather than a standard tranform component.
Mixing 2d and 3d?
Thank you both
https://hatebin.com/gwwtooejgp
I was trying to code a script where the white vertex color has its UV moved according to a bone's position. I got it to target the color, but the only problem is that it cycles through random colors of the texture and does not follow the bone
Vertex colors are unrelated to uvs.
I am using vertex colors so the script knows where to control the UVs
It is one mesh so the eyes are not separated
Also the eyes are flat
Okay, well, you're only changing the uvs, so it just samples different positions of the texture.
How would I make it move based on the position of the selected bone and have a limit of how strong the movement is?
Wdym by "make it move"?
Uvs are in range of 0 to 1. Using bone position to calculate gonna result in some unrelated numbers.
In the first place mapping bone position to uvs sounds like a crazy idea. What are you trying to achieve?
What I mean by making it move?
Well the eye is included in the body's texture, so I'd like to move the uv of it up and down based on the bone's x and y position.
Okay, I see...🤔
It would be a bit more clean to contain the face model in one game object, so if I were to change materials on it I can easily do that without having to apply it to the eye too
You'll need to define the uv positions range of the eyes and maybe use a Lerp to map bone local positions to uv coordinates.
With your approach its gonna be pretty performance heavy though. Normally custom shaders are used for this kind of stuff.
So I have a class, ClassA, and ClassA contains a field of the type ClassB. Each instance of ClassB is a field of an instance of ClassA, and no instance of ClassB is assigned to multiple instances of ClassA. I’m trying to make it so that if you take any given instance of ClassB, it can reference the ClassA it’s a field of. My issue is that I can’t edit ClassB, as I got it from a library. The only idea I’ve come up with is looping through every instance of ClassA and checking if the field contains that specific instance of ClassB, but I feel like that’s really inefficient. Any better ideas?
i'm a little confused, i have the variables defined publicly but it only lets me use isGrounded?
and i have saved the script for the controller
Ideally, you'd have eyes as a separate mesh rendered by a separate material.
If they're a part of a bigger mesh, you'd need to pass in additional data(probably a float2 would do) to your shader describing the position of the eyes as well as a mask texture defining the area of the eyes. In the fragment shader you would then sample the mask to see if the pixel is in it and if it is, shift the sampling position by an amount calculated from the passed in eye position data.
Have a dictionary mapping instances of the classes to each other.
If classB is extendible, you can extend it and add a field to reference classA too.
What does the error say?
CC has it's own isGrounded
wait
It's likely not referring to your isGrounded you posted above
Where do you have is walking defined?
i uh, forgot that unity has its own character controller
oops
yeah, that's why
i changed it to my script and it works fine now, sorry lol
!docs
I am still getting this error: Unity CS2012: Cannot open 'Assembly-CSharp.dll' for writing. This happens when I edit and compiling scrips and this would always pop up. I have moved my files out of OneDrive and put them in Desktop (not connected to OneDrive) but I am still getting that error. I tried to delete the library folder but it won't allow me because Windows swears Assembly-CSharp.dll is being used by something. I was told it was an Antivirus situtation but, its still not allowing me after I made the file clear of any viruses. Is there any other solutions?
Restart the computer
Take a screenshot of the whole error.
Also, your desktop was under one drive if I remember correctly. That's why I suggested moving the project to C root.
The error is gone... at least for now
im on my first project atm, been trying to find a guide on 2d tilemap chunk load as the player moves but cant find anything on youtube, anyone found a guide for this ?
Does the tilemap not handle a lot of that for you already?
hi can anyone please help me
I am working on a 2d platformer game and i have made c# scripts for healthbar and health so the problem is that my script's are not giving any error, I have made a private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
TakeDamage(1);
}
this
in my health script
so when ever i press E
one heart will turn black but when i am testing it out in unity all my hearts are turning black at once and also my player stopped jumping
there is no error showing up in unity either
First of 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.
Second of all, show more of it, specifically the TakeDamage method
First you'd have to send it
using UnityEngine;
public class Health : MonoBehaviour
{
[SerializeField] private float startingHealth;
public float currentHealth { get; private set; }
private void Awake()
{
currentHealth = startingHealth;
}
public void TakeDamage(float _damage)
{
currentHealth = Mathf.Min(currentHealth - _damage, 0, startingHealth);
if (currentHealth > 0)
{
// player hurt
}
else
{
// player dead
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.E))
TakeDamage(1);
}
}
once again, !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.
this is for health
i don't understand
Please share your code properly
```cs
// Code here
```
Also you're calling Mathf.Min(currentHealth - _damage, 0, startingHealth);
Which will just take the lowest value
Which is 0, then -1 on the next call
You probably want Clamp, not Min
That's another issue
If your player is now damaged properly, then debug what's going on when you're trying to jump
First update your code if you haven't yet and check if everything is fine
Show the code for jumping and attacking
yes
