#💻┃code-beginner
1 messages · Page 442 of 1
changing the material doesn't do anything, I just tried
it works just fine, you probably did it wrong...
you need to add it all the way down the inheritance chain
that's normally the case
{
[SerializeField] Renderer playerRenderer;
[SerializeField] Texture2D[] backgroundTextures = new Texture2D[2];
void Start()
{
int random = Random.Range(0, 2);
Debug.Log(random);
playerRenderer.material.mainTexture = backgroundTextures[random];
}
}```
what are you showing me ? this is changing texture not material
by swap material I mean make the material already with texture you want then just swap material on renderer
that's what the unity thing you sent told me to do
I just added it to all these and still nothing :/
You asked about swapping textures , but I suggested swapping material is easier
ah
the issue is I have texture2D's and idk how to make a material
huh? you just drop the texture in the material.
thats how textures are displayed
unless you're doing UI ig
it's not ui
Just to make sure, you're not doing this for like a 2D sprite are you?
I am
I put texture2D so that shouldn't be an issue
why can i destroy the gameobject on the update function but not in destr function, the script is in a prefab (its the pipes in flappy bird)``` cs void Update()
{
transform.position = transform.position + (Vector3.left * PipeSpeed) * Time.deltaTime;
if (transform.position.x < DeadZone)
{
Destroy(gameObject);
}
}
public void Destr()
{
Destroy(gameObject);
}
depends how you call Destr
Did you add it to PlayerBaseState
i call it in another func in the players script
yeah
That is cropped. PlayerBaseState does not inherit from anything, right?
Also, do you have ANY errors in the console? Not necessarily errors related to these classes, but ANY
using UnityEngine;
[System.Serializable]
public abstract class PlayerBaseState
{
public abstract void EnterState(PlayerStateMachine playerStateMachine);
public abstract void UpdateState(PlayerStateMachine playerStateMachine);
public abstract void OnCollisionEnter(PlayerStateMachine playerStateMachine);
}
clean as a whistle
Maybe it's not working because I instantiate them directly from the script?
Might be an issue of doing new() in the initializer? Not sure
so did you put Debug.Log in the method to see if thats actually calling it
I'll just assume it's a unity bug and work around it
yeah it does execute it but i get an error saying destroying assets is not permitted to avoid data loss
just dont understand why i could do it in the update func and not in destr func
then you are calling Destr on the prefab not on the instantiated game object
yes sounds like you're trying to destroy the prefab not the instance
how do i destroy the copy
call that function on the instance
references
var myInstance = Instantiate(etc..
...
myInstance.Destr()
idk what you're trying to achieve so it depends, you might even store it as a field or in an list?
just destroying all the copies on the screen
all at once?
store all the spawned copies in a List then loop through to destroy them all when needed
That would destroy all spawned copies not the ones just on the screen however
oh if they mean literally within screenbounds, i suppose to can check that too if its within bounds of screen
Anybody with some knowledge in the kinematic character controller done by philippe ?
I need to know the correct way of moving an AI character smoothly, it just teleports atm
yeah im making a revive mechanic and all i have to do left is to destroy the obstacles on screen so that the player doesnt hit them while hes static for 3s
should be easy enough. You can even use a trigger probably.
Overlaps can also be an option
positioning check probably being most performant but takes a bit of math
I have an Enemy object that flips directions by multiplying his transform.localScale.x by -1.
The enemy has a child object (healthbar) that I don't want to be affected by the parent's change of localScale. How can I do this?
instead of direct parenting use a Constraint component maybe and just use it for positioning
so im making a game where chess pieces are enemies so i want the knight piece to dash at the player
so do i add force and make him go in the players direction?
its an option sure
ok
I don't think unity will serialize an abstract class to a value... You can use a [SerializeReference] attribute on the field, but your abstract class itself does not have any serializable members, so I don't think there'd be anything for Unity to draw to the inspector except for an empty drawer
This is what they were trying to show
#💻┃code-beginner message
So it is a non-abstract child class
Oh I see 👍
I guess then the question becomes "Does MovingState have any serializable members?"
I've made a package with a custom inspector that allows you to do [SerializeReference, TypePicker] private IInterface/AbstractClass field; and it'll show nicely in inspector and give you a picker to select concrete instance and fill its stuff: https://github.com/pulni4kiya/unity-editor-tools
I use this all the time in all my projects, because it's very convenient to be able to serialize interface/abstract class
(what's the policy on sharing one's packages when they're kinda relevant to the context? 😅 )
that's not really going to matter if there is nothing to serialize in the object
Mathf.Clamp returns the clamped value, it doesn't do it in place
i have to do currentGas = before it
damn
my game is coming together well
i want to thank you guys for helping if i didnt have ur help i would have been like my friend yassin we dont really talk about him
THis is a bit baffling to me
https://gyazo.com/eba7cc5f32189d57f0ce62c8a2982323
Color [] colourMap = new Color [width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
colourMap [y * width + x] = Color.Lerp(Color.black, Color.white, noiseMap [x, y]/10f);
}
}
colourMap [0] = Color.red;
colourMap [12] = Color.yellow;
texture.SetPixels(colourMap);
texture.Apply();
The red pixel, upper right corner of the plane (index in the setpixels of 0) is landing in the opposite corner I'd expect. Couldn't find anything in docs stating the setpixels array is like this.
Actually hte docs do state the exact opposite of what is occurring: colors must contain the pixels row by row, starting at the bottom left of the texture. The size of the array must be the width × height of the mipmap level.
Hey so can I ask questions in this channel?
Yes, but you're limited to 1 and you just used it up
okay lol
So, i stg I just took a class on Function but for the LIFE of me I can't get them right lol I mess them up EVERY time. This is Python script.
This isn't a channel for any code help, it's specific for unity. The function is just returning whatever you pass in though, and the "str + x" line is doing nothing.
And the print line is out of scope of the function as well
And you never call the function
The code doesn't really make any sense
Oh, sorry i saw "beginner code" and was like "that's where I gotta go." lol I see, so I need to play the Print function within in the Function right?
Depends on what your code is trying to accomplish, I'm not sure exactly what you want.
That being said you'll get better targeted help for Python in any Python related discord. I cannot send any invite links but it's very easily googleable.
To the best of my knowledge, python isn't really used in Unity aside from automation
Fair, alrighty thanks for the help!
Hi guys, Ive got aproblem in which I have 3 menus that show three different types of objects but the information display in each of them shares some data like the name or the description of the different objects, however, there are some things that they don´t share, for example, weapons have damage quantity but resources don´t, any ideas of what should I do code-wise?
my idea is to click a Slot and show the information on the different menus, the problem is that not all the menus show the same information
#1265813900037853255 message is am currently with the issue of increase my counter and have it persist across scenes and runtime, since I don't know how to fix that so the number in the stage selection can be increased from touching the muon objects in the other stage scenes
i know this is a stupid question but its late and my brain is not functioning the problem here is that its looping
so its keeps going in the z rotation -10 then 10 then -10 then 10
Is it okay to check if an interaction (with unity events) has been executed in the update method?
What do you mean by, "with Unity events?"
Assuming these objects are all in the same inheritance hierarchy, you might add a property or method to the base type to retrieve a collection of the relevant statistics, and override it in the subtypes. Then the menus could just ask the thing for it's stats and print out whatever it spits out
something like this
Imagine an inventory with three tabs, weapons, resources and key objects. The weapons tab may show a damage stat that the key objects tab doesn´t
i think i might be cooking nvm
I don't see where InteractAction is invoked, but to check when it has, subscribe a method to it that sets a bool variable . . .
If that bool variable is true, then the event was invoked . . .
I myself would aim to keep the inventory UI generic, such that you're not building different UI specifically for different types of inventory items. It kind of sucks to add a new stat to some type, or an entirely new type, and have to tweak the UI each time.
If the items themselves are capable of providing a list of their relevant stats, then the UI's only job is to display that list, and it will inherently work for all items.
Oh okay but, if I am using Unity InputSystem and have a PlayerInput controller (imagine I configure it so that "E" is the interaction Input), how could I check I am in range in the Player Input script
public void Interact(InputAction.CallbackContext context)
{
}
How could I check that the event object is there if I am checking that in this Interactable script
So is it better just to have one tab with all objects and have only ONE manager for that tab that has all of that information???
That's a design decision - your call. But I think tabs and filters are always nice.
All I'm saying is that instead of creating code to implement different menu for each type of item, I would try to create a single implementation that doesn't care that there are different types of items or know about which specific stats it needs to display. It just displays whatever it's given.
and have only ONE manager
I would only have one controller or manager here, yeah - at least, if all of these items are in the same inventory. If multiple tabs aren't simultaneously being displayed on screen at once, then all a tab is doing is filtering the items which are to be displayed. One UI controller feels convenient and intuitive to me, but you could certainly implement it with multiple.
Thanks a lot for this precious help
could you help me with this other thing I was talking about earlier?
This
So you want to invoke InteractAction here when the player's in range and hits some key?
yes
but the InRange check is done in the object so Im a little bit messed up
You wouldn't. The interactable should subscribe to the "E" input event in your player actions. When pressed, the subscribed method can check if inRange is true. If so, run whatever code you need . . .
Hmm I see, however, how is this translated to code?
I basically wrote it out. The "E" input should have an event that the interactable script can subscribe to. Inside of the method (located in the interactable script), check if "inRange" is true . . .
is that event "eventadata"??
Hi, just wanted to know, is there any better way to do something like this? Cause rn it setactive(false) all game objects and then it only setactive(true) the one I wanna keep but that means the one I want to keep are setactive(...) twice
public void HideEverything(){
gameMenu.SetActive(false);
textLogo.SetActive(false);
levelModeExtraButtons.SetActive(false);
levelSelectionMenu.SetActive(false);
coinsCount.SetActive(false);
gameHUD.SetActive(false);
lastChance.SetActive(false);
deathScreen.SetActive(false);
nextLevelButton.SetActive(false);
}
public void ShowGameHUD(bool debug = true){
HideEverything();
gameHUD.SetActive(true);
}
public void ShowLevelSelectionMenuHUD(){
HideEverything();
levelSelectionMenu.SetActive(true);
}
public void ShowMainMenuHUD(){
HideEverything();
gameMenu.SetActive(true);
textLogo.SetActive(true);
}
public void ShowLevelModeDeathScreen(bool extra = false){
HideEverything();
deathScreen.SetActive(true);
levelModeExtraButtons.SetActive(true);
if(extra){
nextLevelButton.SetActive(true);
}
}
public void ShowInfiniteModeDeathScreen(bool extra = false){
HideEverything();
deathScreen.SetActive(true);
if(extra){
lastChance.SetActive(true);
}
}
Invader's describing something like:
public InputActionReference InteractInputAction;
void Start() {
InteractInputAction.action.performed += HandleInteraction;
}
void HandleInteraction(InputAction.CallbackContext _) {
if (!InRange)
return;
InteractAction.Invoke();
}
void OnDisable() {
InteractInputAction.action.performed -= HandleInteraction;
}
I've not worked with PlayerInput, so your actual implementation might vary depending on your Input System workflow. But this maybe illustrates the general idea.
is it better to use the unity built in animation tools? or to do it all with coding?
ive heard you can do either
but im not sure what is better practice
well im just referring to a 2d platformer
for the player movement
like walk,idle,jump
please finish a thought before pressing enter
mate you sent 6 messages in the span of 2 minutes. that could have all been one or two messages at most. see #📖┃code-of-conduct
I did, but you're assuming I didnt finish thinking before pressing enter
but I got you I dont mind doing paragraphs either
here you go doing it again
There is no better practice. You either like using Unity's animation tools, or you prefer to control the animation manually (through code) . . .
It is not about what you mind. It is the rules of the server 🤷♂️
But yes, it is about what you prefer and are comfortable with in terms of the question
Coding it can be quite powerful, but get fairly complex
Sounds good thank you!
u can also animate in 3d modelling programs like blender
and/or use tweening libraries + code if thats the kind of animation u mean
hi guys, quick question
do u guys usually use one object for both Warper and SpawnLocation (for landmark) or one for each?
for example, when i exit the room through the red door, i want my player to go back through that red door (just like how real life works)
actually, better question:
can i have a door that has some kind of extension in which it sets a spawn point? like, some button to "addSpawnLocation" and then i can drag that spawn location to a spesific coordinate
so like the screen fades in and out and you're somewhere else, in front of the red door?
yes, but i want to make it flexible, so i want to be able to modify the spawnlocation of each door
wsg, how do i make 3d character controller movement more snappy. right now if i walk, and then let go of w, it takes a second before the player stops moving. whats the solution to this weird problem?
I would have a DDOL object that holds a vector3 variable for the position you should go into for that scene
When you enter the door, update that value.
Perhaps a dictionary or list of classes
GetAxisRaw instead of GetAxis
welp that was simple, thanks lol
god but now my animations are not smoothly transitioning because they dont have time to transition
let me attach a video hold up
its really clear when crouching
what else can i show to help solve this
ok, so heres what i understand
DDOL is runtime storage of data, in which it stores data only across scenes, but not after you close the game
PlayerPrefs are stored between game restarts, so it's ideal to be used as save points
https://www.youtube.com/watch?v=swOfmyJvb98&ab_channel=Mike'sCode
Im following this tutorial and for whatever reason it looks like this groundcheck is not working. I put it exactly where he put it in the tutorial, at the bottom of my player. and followed the steps to make sure the correct empty was put as the variable and the correct plane was put as the ground mask. Yet when I start my game I fall for a second, underneath my plane and then the collision starts working like it should a few feet higher. I'm getting a warning in the console that says my variable "isMoving" is assigned but its value is never used even though my code is exactly like the tutorial. I don't think it is related to that though
#unity #fps #tutorial
In this series, we are going to create a first-person shooter game in unity.
We will learn how to develop all the different features that are common in FPS games.
From basic movement to shooting modes, impact effects, animating the weapon models, ammo management, enemy ai, and more.
Full FPS Playlist:
https://www.youtube...
theres an extra collider in that picture.
ohhh i see what youre talking about i understand the issue now idk why i didnt pay attention to that
is there a way to get rid of that? as I already have another collider on the player
or is that the only collider and I need to align it to the player
I aligned it to the player all is working fine
DDOL is a scene, that persists when other scenes are unloaded
Basically yes on both counts though.
I strongly recommend against playerprefs for anything other than game settings like resolution and volume though. JSON or Binary is preferred (that way you can have multiple files, formatted for more complex data, and honestly a lot easier to set up, plus not saved in appdata!)
even though it is working fine its kind of annoying I am getting the warning about my bool variable "isMoving" being assigned but not used even though it is "used" in an if statement. If I am getting that warning does that mean I have bad code? can I fix it? is it like a falty warning or something?
ur just setting isMoving ur not technically using it there..
thats the only time it is referenced besides the top of the file where I just wrote bool isMoving;
the if conditional uses the lastPosition, transform, and isGrounded
since I am getting the warning does that mean there could be an issue down the line I should fix now? or as long as it is working I shouldnt worry about it?
it just means isMoving isn't utilized yet... u havent used it.. u could delete isMoving = true; and isMoving = false; and the code wouldnt change any.
okay thank you for the help I appreciate it
np, i have a few of those as well
i intend on using em eventually
Hello can anyone help me solve this error, ive watched countless tutorials and still cannot find a solution. Im a complete beginner with around 20 days of coding. This is the code that the error brings me to for line 20. I'm trying to make a script that holds the prefab of this obstacle that moves up and down but then i found out that the references of scripts on my prefab dont carry over, so then I tried to reference the game objects and im met with my error. One thing i think it could be is that on start up the things in the canvas of my game are disabled but i dont know what to do.
Your use of GameObject.Find is incorrect
the error is clear
it didn't find any object with that name
that's all
Ok i understand that but the names are correct, is this error happening because the object is disabled inside of my hiearchy?
Tes your objects are disabled and therefore cannot be found with Find
make a script on an object that ISN'T disabled which referneces those texts, find that, and interact through that
this is all bad practice
reaching out to random objects and directly modifying them in once place like that
Hi can someone help me solve my problem? When I parent my player to a GameObject, the player doesn't follow the parent's movement
It only slightly moves in the direction the parent's moving
It depends what components are on your player. A dynamic Rigidbody, CharacterController, or a custom script could easily cause this
Oh yeah I'm using a charactercontroller for my player
But shouldn't it only move when I use my mouse and keyboard?
No. It tracks its own position
Oh I see, thank you
I have another problem though, when I repeatedly change the MeshRenderer material of my GameObject, for some reason my cpu usage for unity drops from 20% to 5%, and the charactercontroller follows the GameObject when it's parented to it
But that only happens when I repeatedly change the MeshRenderer for that one specific GameObject
I have other objects in my game where I repeatedly change the MeshRenderer but my game doesn't get laggy
I made a new script that holds the references but now what do i say to connect those two scripts to know that those objects exist
Wdym by laggy? How do you confirm it? Did you try profiling the game?
While learning Draggable Item on yt, I'm kind of struggle trying to move the "item" to another "slot" while it keep snapping right back to my original slot, does anyone know what am I missing here?
Hi! I'm struggling with writing PlayMode tests.
I have a script that calls Screen.height.
It works in the editors Play Mode, but not in Play Mode tests.
There it gives a null.
I'm loading a scene in {Setup] with SceneManager.LoadScene("TestScene", LoadSceneMode.Single). Why is Screen null?
Show the actual error, this is a static int so it really cant just be null
The error is just
NullReferenceException: Object reference not set to an instance of an object.
The line in question is top = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height - 100, 0)).y. @eternal needle
theres a lot more on that line than Screen.height. Did you debug what was null specifically?
theres only one thing i see here that could be, the Camera.main
I created an empty scene with a camera and loaded it with SceneManager.LoadScene. Is that not sufficient?
🤷♂️ not sure how thats related at all. Do some debugging and actually see whats null instead of assuming
So, Camera.main is returning null in my test. How do I rectify this? Do you have a beginner tutorial for Play Mode test writing?
i havent done this myself, but this just means your code is running before the main camera actually exists
or you dont have the right tag on the camera
Thanks, @eternal needle . I want to pull back the curtain on the workings of Unity. It's black magic to me right now. Can you recommend resources?
ive never really used play mode tests so I cant suggest myself. Really everything is just trial and error, and looking into specifics related to the next game mechanic that you want to create. Also proper debugging skills, like of what happened above. Once you realize Camera.main is null, you can look into why
Can you recommend resources for getting better at debugging? I'm still learning all of this.
its really just trial and error. the most basic way with Debug.Log and seeing what value is what. Solving null problems is ALWAYS the same. Find out what specifically is null, then you find out why. And most of the time you'll realize very quickly why something is null if you wrote the code
Theres also the debugger with VS (and i think rider) where you can pause execution and actually hover over the variables in your IDE to see what they are at that moment. theres a ton of features
you could look into tutorials for the debugger specifically, but the actual skill is just something you get with time
Thanks.
I couldn't solve this last time but how can I spawn a bullet on my player and not have my player die from the collision detection. like how do I say "Only kill the player if the bullet came from the enemy"
Check if the other colliding object is not your player🤷♂️
how would I code that?
this is as far as I got last time but I just made myself confused
what is FirePoint?
The fire point is the player position but Im not sure if I did it right
Since the thing you are detecting is a bullet, and not the enemy itself, you will need the bullet to have some script on it (or perhaps a tag) that you can check. If the check is false, do not call destroy 🤷♂️
Something as simple as other.CompareTag("EnemyBullet"); would work, or as 'complex' as if (other.GetComponent<Bullet>().fromEnemy) (fromEnemy being a bool you toggle when shooting the bullet)
No, you did not do it right, because that variable does not exist
FirePoint is nothing, that is what I was getting at. It is not declared anywhere
Compare it to Player, which IS declared
Also note that = is an assignment. Lower in the script in that if statement, you want to COMPARE it, with ==
Lastly, instead of whatever that IgnoreCollision call is supposed to do, you can just return
Okay i will try to fix the code and be back in half an hour
is this because of that i'm stupid over a simple thing so no one care enough to help me or no one know what is the problem ?
I generally skip over videos honestly. I see you even showed the CODE in the video, which is awful hahaha.
Try sharing the code properly and see if anyone can help
!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.
here is the code in my previous video, i hope this could be more clear
Draggable Item
public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[Header("UI")]
public Image image;
[HideInInspector] public Transform parentAfterDrag;
public void OnBeginDrag(PointerEventData eventData)
{
parentAfterDrag = transform.parent;
transform.SetParent(transform.root);
transform.SetAsLastSibling();
Debug.Log("Begin Dragging");
image.raycastTarget = false;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
Debug.Log("Dragging");
}
public void OnEndDrag(PointerEventData eventData)
{
transform.position = parentAfterDrag.position;
transform.SetParent(parentAfterDrag);
Debug.Log("End Dragging");
image.raycastTarget = true;
}
}
Inventory Slot
public class InventorySlot : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData eventData)
{
GameObject dropped = eventData.pointerDrag;
DraggableItem draggableItem = dropped.GetComponent<DraggableItem>();
if (transform.childCount != 0)
{
GameObject current = transform.GetChild(0).gameObject;
DraggableItem currentDraggable = current.GetComponent<DraggableItem>();
currentDraggable.transform.SetParent(draggableItem.parentAfterDrag);
}
draggableItem.parentAfterDrag = transform;
}
}
if your bullet prefab is same for both player and enemy agents, you can do init in bullet's script. Something like that:
private GameObject owner;
public void Init(GameObject owner){
this.owner = owner;
}
and then check if collided object is owner or not.
Chuck in a Debug.Log() for your OnDrop() handler as well, to see if that's getting called and the order of events here.
I suspect OnEndDrag() is called before OnDrop(), so the item does not get parented to the new slot nor repositioned
I'm pretty new to unity (like, very new to it) and I need to have a file explorer pop up so you can select a .wav file, I got that part all set up with an audio source plugged in, but I can't seem to find the right way to make that file you choose get plugged in as an audio clip into the audio source, but I'm getting help from some other people and they're kinda just throwin code at me hahaha, I don't really understand what it's all doing, in the vid I saw to set up UnityStandaloneFileExplorer they let you open a .obj and it turned it into text in a textmeshpro game object, but doesn't really explain how to do something useful with it lol, and I'm struggling to figure it out for audio stuff
#if UNITY_WEBGL && !UNITY_EDITOR
// WebGL
[DllImport("__Internal")]
private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
public void OnClickOpen() {
UploadFile(gameObject.name, "OnFileUpload", ".wav", false);
}
// Called from browser
public void OnFileUpload(string filepath) {
StartCoroutine(OutputRoutineOpen(filepath));
}
#else
// Standalone platforms & editor
public void OnClickOpen()
{
string[] paths = StandaloneFileBrowser.OpenFilePanel("Open File", "", "wav", false);
if (paths.Length > 0)
{
StartCoroutine(OutputRoutineOpen(new System.Uri(paths[0]).AbsoluteUri));
}
}
#endif
private IEnumerator OutputRoutineOpen(string filepath)
{
UnityWebRequest www = UnityWebRequest.Get(filepath);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("WWW ERROR: " + www.error);
}
else
{
}
}
}```
ik it's gotta go in the else section of the OutputRoutineOpen block
but idk what I need to do or where to look to figure it out
so replace all the UnityWebRequest with UnityWebRequestAudio and then replace .Get with .GetAudioClip?
I would definitely not recommend telling beginners to use AI
If people wanted AI help they'd ask AI, not here
yeah I was gonna say, I typically tend to avoid that if I can
when I added Debug.Log() for my OnDrop() handler, it seem to not show up the debug whatever i try to drop it into another slot, so is it because of my code or in the unity scene that i setup ?
so I can figure it out before actually tossing it to the misinformation bot
Follow the example here https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestMultimedia.GetAudioClip.html
my lack of math education is showing, apologies,
If I have a pool of rarities, how can i convert a 0-100% value into a rarity in the context of that pool (is this even possible)
eg.
- Pool is
1,1 - I have
50% - Result is
2
You mean mapping the percentage chance to a corresponding rarity?
I would definitely not recommend telling
Do to guest coming over I cant work on it right now but I will as soon as I can
Hmm... I haven't actually ever implemented this myself, but maybe something is still blocking the still blocking the raycast or something 🤔. I'll dig around a bit and see if I can glean any leads
Stop
I hate doing this but <@&502884371011731486>
!mute 804862024525021215 1d don't post here if you don't want to contribute meaningfully. We have no off-topic.
shadowisbetter was muted.
meh
my frame rates were low and when looking in task manager my cpu usage dropped from 20 to 5
but for some reason it isnt happening anymore
its fine now
look at the actual profiler, not your task manager
Not really a great response, especially as the first one to all the suggestions, with the more important suggestions seemingly ignore completely
Did you fix the Collision error?
yeah, but like i have another error, #💻┃unity-talk if u wana help
Do you guys reccomnd using svg instead of PNG? I've heard GPU's arent made to render SVGs
Anyone encountered anything like this using SetPixels() on a textture? #💻┃code-beginner message
Does Unity even support SVG
shouldn't your for loops be the other way round? First x then y
i heard theres a package
not something I've come across. Perhaps ask in #🔀┃art-asset-workflow
@cold ruin After much digging and a small effort to replicate the problem - I cannot :/ . My drop events are triggered in a simplified hierarchy.
I think something in your scene has to be intercepting the raycast/event, but I'm not entirely sure how you might go about debugging that. Watching the Event System preview window thingy might be a good place to start
Still not a code question but anyway,
GPU's are very much better at rendering SVG's than PNG's. It's why they were developed in the first place. Monitors, however cannot deal with vector graphics so must have a GPU to preprocess the data
I swaped them around same result, so no that doesm't have an impact
did you also change your position calculation
what should it be instead of x + y * width?
btw it's a square
just, checked, that should be correct
yea I've researched it a little bit, but coming up sorta empty, I beleive it's either a bug or at hte very least improperly documented. Possibly why I find so many people asking how to flip a texture responses
I've just checked my production code and it is identical to yours however I did notice that the forward on your texture is along the Y of the texture wheras mine is along world Z. This maybe the reason for the strange result
is that using setpixels? if so can you try adding colorMap[0] = color.red to color just the 0th element as red?
mine is on a 3d plane, so not sure of the connection between hte 2
https://gyazo.com/1788cd9205d8989204a0e97c008c7753 THis is with the for loops completely commented out and no rotation applied to a stock plane
making the 0th element in the upper right, instead of the bottom left per the docs
what I'm suggting is that Unity is rotating the texture when applying it to the plane, try just using a Sprite Renderer with the same texture.
Sorry I cannot alter my code, it is production code
if then, I wonder if the screen space - overlay and the canvas Scaler actually does involved in my issue of not be able to run onDrop normally
Not by default, but there are packages with dubious functionality.
Still experimental/preview
Limited support by the looks of it
I tried relatively recently to get an SVG in and it wasn't worth the effort/potential bugs, I just rasterized what I needed and used that instead.
Oh sorry it seems he already linked that
I was actually responding to his question, cross platform SVG support is always going to be tricky
Having issues with Vector3.SignedAngle, doesn't seem to return the correct angle when you are facing the object with your back.
If i'm standing in front of the object with my back turned, the result is angle=120. Need help
Vector3 targetPosition = mainCamera.WorldToScreenPoint(TargetObject.transform.position);
float angle = Vector3.SignedAngle(Vector3.up, targetPosition, Vector3.forward);
did you debug what these vectors are? because this doesnt make a ton of sense imo
yes, I made a sanity check. Vector3.up, Vector3.forward, TargetObject are all the correct values
After watching this tutorial up to 7:55
https://www.youtube.com/watch?v=Qxs3GrhcZI8
When ever i diel the angle it acts rely sensitive.
Video demo: https://drive.google.com/drive/folders/17OZNDa0erUUIYB1FWAjKwl7OjM21keHD?usp=drive_link
A tutorial showing how to implement the projectile movement formulas and functions in Unity Engine and why are they useful, what can you use it for.
The tutorial covers C# implementation.
Support me on Patreon: https://www.patreon.com/abitofgamedev
Follow me on Twitter: https://twitter.com/steffonne
Follow me on Instagram: https://www.instagram...
you mean targetPosition? because https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html i really dont see how this would ever make sense to compare the screen point to (0,1,0)
I have a question about inheritance and virtual variables (or a workaround) in Unity
Basically, can I change the type of an inherited variable in a subclass, in Unity?
public class Card : MonoBehaviour
{
[SerializeField] protected CardScriptableObject cardScriptableObject;
and
public class PlayingCard : Card
{
[SerializeField] PlayingCardScriptableObject playingCardScriptableObject;
So a base Card class, with variants (playing cards, tarot cards, pokemon cards, whatever). The base class just knows it needs an image.
The sub classes have more information, which depends on the type. Playing cards have suits and numbers, some cards could have names and costs and abilities, etc.
Is it possible to change the type of inherited variable in Unity? Generic C# answers started talking about fields vs properties, but I'm not sure that works in Unity's ScriptableObjects.
Should I just make the base class abstract?
also the method you're using doesnt care at all what way you're facing. Its literally just taking in 2 positions and getting the angle between them
No, but you can override it with "new". Wouldn't suggest doing that though.
can I change the type of an inherited variable in a subclass, in Unity?
you cannot override a field, this doesnt matter if its in unity or not. this is c#
what are you trying to do with these scriptable objects though? because typically you would just be reading information from them and not return it to anything
also new just hides it, doesnt override
I think I need to watch a proper tutorial about this, hopefully that answers my questions.
hi, someone know how to make a sprite move using the touchscreen like if i want to move to the left i have to drag the finger to left and press?
I basically want to be able to use ScriptableObjects to define card data. 5 of Spades, 2 of Diamons, Joker, whatever. The SO would know the image it needs to use, and the suit and the value.
no matter what you do, the PlayingCard class is gonna need to know it requires a PlayingCardScriptableObject or you'll never be able to access anything related to it. You'd only be able to access the type that you store it in
However, I'm looking into this as a way to learn how to program card game mechanics, so I'm aiming to do a generic system that could be expanded to the needs of different card games.
I think making the Card class abstract helps quite a bit, but I'm facing other issues, so as I said I'm going to check out some tutorials and examples to see how other people have implemented this.
One thing that comes to mind is you could store it as CardScriptableObject and then in some method (maybe awake) you could try casting it to the PlayingCardScriptableObject. If the cast fails, throw an error because someone plugged in the wrong SO. Then you read all the information you need
Thanks, that sounds like it'd answer my initial question.
So I shouldn't try to override it, but I can check if it's the correct type.
yea, you could even try casting in OnValidate which would prevent you from plugging in wrong values in the first place
how make jump
the gravity is set to -200 because otherwise my body falls really slow
playerbody.velocity tells Unity which direction the character is moving.
One way to do a jump is to add an up-force to the velocity, at each frame. However, then you'd have to manually change the amount of up-force each frame.
Currently, you replace the velocity with a new velocity each frame, so you have to add more stuff to it to make sure it "remembers" that it's supposed to keep moving up
If you just add direction += transform.up; , spacebar becomes a jetpack boost that constantly pushes the character up
Which tutorials about basic movement have you watched so far?
i went to jupiter
It's 10 per frame
You may want to learn about Time.deltaTime
10 per frame is a lot.
10 * Time.deltaTimeis ten meters (ten Unity units) per second
i watched an introductory video to teach me about unity then ive just been:
walking till i hit a wall, go to the documentation, learn how to scale the wall; keep going
i made a simple topdown shooter game to learn the engine basics now im going to actually start developing the game i want to
and i figured out the movement on my own lol
You don't know what you need to know, so I think it's good to watch a few more basic tutorials. Movement systems have lots of parts into them. I recommend making a few more practice projects first.
i mean this is all practice, might even start a new project if this one gets too spaghetti code-like
Smooth movement, jumping, dashes that don't go through walls, and then you get into stuff like coyote timers.
im gonna build the game upto where my knowledge with my practice game ends
deltaTime, too. Have you noticed that your character currently moves waster diagonally than straight? Holding down WD is faster than W or D
my game wont have any of that, just a regular jump , walking and running
mostly, the game is gonna be a walking sim lol
i mean not really just the run will be pretty detrimental
still usable just, better keep it for running away from mutants
Still, I do recommend watching some tutorial about basic movement. You need to know when you're touching the ground, otherwise the jump will allow infinite air jumps.
Any way, one super simplified way to do a super simple jump is like this:
// GetKeyDown() is only true for one frame, not all the time
// the player can only jump again once they're not jumping
if (Input.GetKeyDown(KeyCode.Space) && isJumping == false )
{
isJumping = true;
jumpTimer = 0f;
}
if (isJumping = true)
{
// push upwards at specific speed
direction += transform.up * jumpForce;
// jumpTimer variable knows how many seconds have passed since the jump started
jumpTimer += Time.deltaTime;
// once the jump has pushed up for a specific time, it's over and the character falls down again
if (jumpTimer > jumpBoostTime)
{
isJumping = false;
}
}
However, there are several issues with this.
The character will basically have an invisible jetpack pushing them up at a constant speed, and when it stops, they are instantly falling down at maximum fall speed. So it's not a smooth jump arc, but a very uncomfortable, sudden motion.
The player can keep spamming space to jump constantly, even in the air. You'd need to add another condition to the initial if, && IsGrounded() , and make a function that returns a true or a false value, and checks whether the player was touching the ground when the jump button was pressed
Can seomeone explain this? From what I understand its grabbing the current rotation and lerping to the target rotation. But isnt the current rotation and target rotation the same?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSway : MonoBehaviour {
[Header("Sway Settings")]
[SerializeField] private float speed;
[SerializeField] private float sensitivityMultiplier;
private void Update()
{
// get mouse input
float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityMultiplier;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityMultiplier;
Quaternion rotationX = Quaternion.AngleAxis(-mouseY, Vector3.right);
Quaternion rotationY = Quaternion.AngleAxis(mouseX, Vector3.up);
Quaternion targetRotation = rotationX * rotationY;
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, speed * Time.deltaTime);
}
}
so it would be better to have it accelerate upwards?
forgive me if its simple, I can't grasp my mind around queternions
There are better ways to do it, but that's better explained in video tutorials.
and ofc im gonna need something to check if the character is grounded
i dont really like tutorials, most of them just tell you how to do it not how it works
Debug the code and find out. Also that is not the way Slerp should be used
I got the code from YT
the code is working
i just dont understand it
At the moment, you don't know how to do it or how it works.
After a tutorial like that, you'll know how to do it, and can start figuring out how it works.
As usual, YT is wrong
While that's not the way Slerp is supposed to be used, I'm not sure if that's an objectively bad way of doing things
All of this
transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, speed * Time.deltaTime);
ill try to figure it out on my own using unity docs, but if i cant ill go watch a tutorial
i skimmed through the doc rq, whats wrong?
LERP and SLERP are basically ways to transform value from A to B, by changing a third value.
LERP is supposed to, for example, transform from 0 to 1, or from 50 to 80, in a specific way.
SLERP is supposed to, for example, transform from forward to up, or from (0, 50, 180) to (-100, 50, 0), in a specific way.
Slerp and Lerp are
current = start, end t
you are doing
current = current, end , ?
That functions seems to use SLERP to change an initial value a little bit, but not all the way, so it's using SLERP in a way that it wasn't mean to be used. But if it works, and SLERP isn't super slow, it's not... horribad.
Just not elegant
so lerp are values, and slerp are vector3s
Yup, and they're meant to transform from start value A to end value B by using a third variable
but the example doesn't use the same A and B, so it's not actually doing that
If you like math, I have a video about that stuff
i dont get the 3rd variable part
do u mean, it keeps adding a 3rd variable
oh ok
0% to 100%
The way it's meant to be used, A and B don't change, but the T (time / mix factor) does
hmm got it
so that way works, but isn't the way it was meant to be used
does hte problem have smthing to do with the speed * Time.deltaTime
Not really. That just means the change is happening constantly at a given small percentage.
The weird part is that A value is changing every frame.
ohhhh
If you want to watch a video explaining this through math, you can check this https://www.youtube.com/watch?v=LSNQuFEDOyQ
a journey through decay and delta time (I had to learn differential equations for this oh boy)
Slides: https://www.patreon.com/posts/105228270 for my patreon supporters 💞
The slides are much nicer in person!! like, the AV team on site had me lower the refresh rate on my laptop because we couldn't get it to work otherwise, and on top of that, vi...
But it's not needed to use lerp functions, it just goes into detail about the math side
is there any problem with using this method?
I don't know any
like for example if the users FPS is really low, then the t value would be higher than 1 i asssume
then it just snaps to B position instantly
oh ok thats very good!
any way, most likely it rotates something so it sways a little bit behind some other thing
just a visual delay
it just feels dirty
using LERP/SLERP this way is, arguably, something that feels dirty
but it works more or less
any way, as the video explains, lerp and slerp give different results on different framerates
so they should only be used for visual stuff that doesn't affect gameplay mechanics
watching rn
anyway, I wanted some help understanding this
wait I think I get it
nvr mind I don't
cause isnt the pistol always at the desired position?
Im a couple minutes in, but doesn't multiplying by delta time fix the issue of different framerates?
for movement yes, but for lerp/slerp no
I meant the code I sent earlier
well if they multiplied speed by deltaTime shouldn't it fix the problem?
sorry if I'm being dumb
wait nvr mind I'm dumb
8:00 or so, it says that yes, it works
what causes this >_>
@drowsy totem Could u help me interprete this?
last sentence
wait let me see
oh
what xD
u arab ?
yes
me too
egyptian?
damn hello brother
Guys, if you want to chat, do it in DM's, this is not a social server
ok
This is still using transform.rotation
i removed it and the line above it
can someone at least explain to me how this line works?
that is adding the rotationX to the rotationY
so like adding vectors together?
wait can i use transform.position = Vector2.MoveTowards(transform.position, Player.transform.position, speed *Time.deltaTime);?
and i remove the RigidBody2D
kinda, yes
also I don't get why transform.localRotation isnt the same as targetRotation
but the only problem is that i want the enemy to be next to the player i dont want him to be inside the player and push him
thats the only other part I don't understand
so maybe keep moving until he collides with the player?
Sure, if you put it in a loop in a coroutine or update for example
You wont get collisions without a rigidbody but if you use the ray to check collision anyway then maybe it is fine
the enemy and play have colliders tho
why would it be localrotation is how the transform is rotated, targetRotation is based on the mouse position
I use input actions way too complex, is there a one liner for reading the value of a button? I cant find anything online or in docs 😭
like what value do I want to read??
buttonValue = InputAction.Map.Action.ReadValue</*???*/>();
Sure but that doesn't affect how you move it with transform.position. Colliders affect rigidbodies
OOOOOH
i think I get it
so the player will still get knockbacked
targetRotation is not trying to get the rotation to (0, 0, 0) [Which is my desired rotation]
its making it lag a bit behind which is a bit proportional to the mouse movement
what data type do you expect to get back from a button?
I was thinking bool like Input.GetKey, but that's apparently not the case
also ik I said my last question was the last, but why is it that many scripts set mouseY to negative?
if you look at your action map it will tell you exactly what is being passed
@verbal dome i have a problem the enemy keeps going in the player
they both have colliders?
yes
and bec he keeps going in the player
he is pushed and appears on the oppisite side
sounds like ur using the wrong type of movement on something
for example translation.. (setting the transform.position directly) will cause something like that.. it doesn't respect physics
what can i do
you either have to write code/logic for ur own collisions, or use rigidbodies for movement
but if i use rigid bodies they will push eachother
and writing my own logic will probably take forever
only got 6 hours left in the jam
use physics layers..
enemy doesnt interact with enemy
but enemy interacts with player
so the enemy will push the player?
yes, if u use a rigidbodys
this would make enemies ignore other enemies.. but still collide w/ player
once u assigned the layer to the GameObjects
no no other enemies are not rigid body this one is
the problem i have is the playr
he has a rigid body
wait
other types dont this one yes
i can make enemy not collide with other enemies later
but my player is a rigidbody
yes, thats what all this is#💻┃code-beginner message
wait i can maybe use a character controler 2d?
this will stop the player from pushing the enemy and the enemy from pushing the player?
theres no such thing as a character controller 2d component.. ud need to build it or copy one online
with a character controller it wont be able to push or get pushed
excellent
unless u code it in urself
i think i can still switch i got time
yea, theres plenty of basic ones online
what do i search for?
are you using 2D ?
Unity 2D Character Controller
but its not a built-in component so i can't say how they would act.. it'd just depend on the person coding it
a 3D Character Controller acts as i said.. but 2D doesn't have one out of the box
so if my player doesnt have rigid body it wont be able to push right?
correct
unless u make ur own code to detect when ur touching something.. and push it like that
a rigidbody = physics
https://github.com/Brackeys/2D-Character-Controller theres one i see alot @long jacinth
follow his video to figure out how to set it up
uses rigid body 2d
ok scrap this
ya, b/c rigidbody is the most common way to move things around.. (takes less work)
whatcha gonna do?
i might do the feature not bug
there is no way to disable rb right?
what u mean by disable it?
disable the componenet through script
you could freeze its position unless ur giving it input
void FixedUpdate()
{
Vector2 direction = (player.position - transform.position).normalized;
float distanceToPlayer = Vector2.Distance(player.position, transform.position);
// If the enemy is too close to the player, stop moving
if (distanceToPlayer > 1f)
{
rb.velocity = direction * speed;
}
else
{
rb.velocity = Vector2.zero;
}
}``` you could just do something like this
also i cant build my scene bec of this silly thing
u shouldnt call the class SceneManager
wait i can actually do that
it confuses it
ok
This should be in a thread really
Prevent RigidBody 2D from pushing Eachother
still problems
i found something
i can try making it static then dynamic
i kind of did it
uh, why does the force sometimes not want to get added?
i have an if statement taht runs, but for some reason just when adding the force to an object it doesnt run
but the rest of it does??
and its inconsistent, sometimes it works sometimes it doesnt
Break the problem down. Does the if statement work as expected (it must work 100% of the time it's expected to work)
it works but it doesnt
theres multiple things in the if statement
and one allways works but specifically the one that adds force doesnt
So it doesn't work - the if statement.
but even then its inconsistent
It needs to always work when expected
okay then no
So the addition of force shouldn't be the focus but rather the reasons why the if statement might not be working. You should provide some !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.
wait let m try something
Is there anyway to use box colliders without the physical touch? Like if the player goes through or in the object, an event will then occur.
Set the collider to "is trigger"
ok nvm that if statement works, a different one doesnt
currently, the box is colliding with something tagged "ground" and grounded which is a bool is false
it doesnt change it to true
does the collider only work on the first collision?
does it not check continuously wether its colliding or not?
Maybe you're changing it back to false immediately
The above code doesn't show us when the if statement would be executed
Is OnCollisionEnter2D still available?
gimme a sec
Or is trigger must be turned off for it to work
On Trigger Enter 2d
Alr ty
wait 0 is smaller than 0.1 right?
this is the only code that resets it
right now rage is = 0
which should be smaller than that value right?
meaning its not being set to false again
last time i checked
so its not setting it to false??
and all the conditions in the if are correct so why isnt it setting it to true?
You need to properly provide !code
Those small snippets do not show us enough of what's going on.
📃 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.
those small snippets are everything thats going on lol
If the statement grounded = true was executed, grounded will be true.
but grounded is NOT true
its currently false
which is one of the conditions
the other condition
is wether or not the bodies are colliding
Your concern was that it doesn't change to true. If the statement was reached, it will be true.
Your problem most definitely lies whatever
and they currently are, my only assumption is if the collision only checks if its collided not if its currently colliding
single collision instead of constant collision something
We cannot tell you unless you show more code
You aren't providing enough info
On Collision Enter would only be called when a collision occurred - the first time.
thats what im saying
how do i constantly check if its colliding?
just oncollison?
Try the other message ||Stay||
void Update(){
if (CanMove){
HandleMovementInput();
HandleMouseLook();
ApplyFinalMovements();
// Enable Jump
if (ShouldJump)
HandleJump();
// Enable Crouch
if (canCrouch)
HandleCrouch();
}
// Enable stamina system
if (IsRunning){
EnableStamina();
}
// Disable stamina system
else if (stamina < maxStamina){
DisableStamina();
}
}
Is it ok to have this in Void Update?
Cus im not sure what the (rules) are in unity on what not to use in void update
When my character dies, the scene is supposed to reset but when my character does die. The scene resets BUT in the hierachy it states "SampleScene (is lost)"
This way of doing target rotation worked fine until i start rotation the model. Does anyone know why there is none tutorials on how to do this.
You might be loading the scene additively to your old scene, you would want to load it single
SceneManager.LoadSceneAsync(index, LoadSceneMode.Single);
SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
Question, I have objects in my "Assets/Resource" path and im trying to load them, works flawleslly in editor but not in an exported build(Windows). Any ideas how could i fix it?
string objectPath = (objectsPath).Replace("Assets/Resources/", "") + "/" + d.Name + "/" + f.Name.Replace(".prefab", "");
GameObject tempItem = (GameObject)Resources.Load(objectPath);
not sure you need the starting "/" in the path
Where are you even getting objectsPath from in the first place?
private void OnEnable()
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
DirectoryInfo info = new DirectoryInfo(objectsPath);
DirectoryInfo[] dirs = info.GetDirectories();
foreach (DirectoryInfo d in dirs)
{
DirectoryInfo subInfo = new DirectoryInfo(d.ToString());
FileInfo[] files = subInfo.GetFiles("*.prefab");
if (noneOption)//--------------
{
GameObject emptyElement = Instantiate(itemUiElemnt, transform);
Sprite itemIconEmpty = null;
emptyElement.GetComponent<ChangeText>().ChangeTextFunc("None", "0", itemIconEmpty);
emptyElement.GetComponent<RetriveIten>().pathToObject = removeItem;
emptyElement.GetComponent<ChangeText>().imageIcon = null;
}
//------------
foreach (FileInfo f in files)
{
GameObject element = Instantiate(itemUiElemnt, transform);
string objectPath = (objectsPath).Replace("Assets/Resources/", "") + "/" + d.Name + "/" + f.Name.Replace(".prefab", "");
GameObject tempItem = (GameObject)Resources.Load(objectPath);
int itemAmaunt = LoadItemAmaunt(tempItem);
Sprite itemIcon = LoadCorrectIcon(tempItem);
element.GetComponent<ChangeText>().ChangeTextFunc(GetItemName(tempItem), itemAmaunt.ToString(), itemIcon);
element.GetComponent<RetriveIten>().pathToObject = objectPath;
element.GetComponent<ChangeText>().imageIcon = null; //idk how
}
}
}
```this is the whole code
this doesn't answer the question of where objectsPath is coming from in the first place
its probably really clunky written but what it does, it bassicly make a virtual arsenal, similar to arma 3
Assets/Resources/Items/Primary -this is one of them, there is also secondary and so on
Then you should use https://docs.unity3d.com/ScriptReference/Resources.LoadAll.html with Resources.LoadAll("Items/Primary")
get rid of all the filesystem code
They will not exist once you build the game
Resources doesn't work that way
your approach here is fundamentally broken.
It will not work, you should rethink it
ig ill leave this project behind than, coded way to much to pull myself out
sounds stupid ye, but the whole thing built relaying on those folder names + it was more or less a testing one
can you not even contemplate changing a few folder names and access methods?
oofsicle 🍭
the code got way to messy... xD
it happens..
was thinking of quiting this project bc of bad FPS framework i built so this is just a nail in the coffin
good opportunity to 'un-mess' it then
tis called refactoring ^
thanks for the feedback, will keep in mind for the future projects
I mean, it takes little effort to move from folder names to just a scriptable object that can scan/populate an array that stores a folder name + prefabs in itself when you build the game/press a button in a custom editor.
Then you'd just read from that SO instead
Then you wouldn't even need resources at all
hi guys, i got an object called player and theres a script on it that instances a prefab called hand. I need to reference the player inside a hand's script, can i pass the player object as a variable to the hand somehow?
thats confusing
yes, no problem
Make a method in the hand script with a player script param
And pass this after instantiating the hand
public Hand prefab; / set in inspector
...
Hand hand = Instantiate(prefab);
hand.player = this;
assuming being run in Player script
guess im not doing it right
Look at my code, I'm not using GameObject
oh
Neither hand nor player should be GameObject
public class Hand : MonoBehaviour
{
private Player m_player
public void Init(Player player)
{
m_player = player
}
}
public class Player : MonoBehaviour
{
[SerializeField] private Hand m_handPrefab;
private void InitHand()
{
Hand handInstance = Instantiate(m_handPrefab);
handInstance.Init(this);
}
}```
For clarity I suppose
Here Player references the script, right?
the class i created to code this
The Hand class instance, yes
And a Hand prefab
If there's a Hand component directly on your prefab, you can drag and drop it into a Hand field in the inspector
can i somehow make scripts broadcast messages that other scripts listen to so i dont have to acces both components every time? or is the latter just easier
Player is the player script
Hand is the hand script
wdym "access both components every time"?
You can use UnityEvent or C# events if you want events
Instantiating it will instantiate the whole prefab and you already have a reference to the Hand component, which has the needed method
so like lets say my character jumps and i want to forward that to the gui
You can use events for this yes
do i have to acces both the character script and the text component to change that or is there an easier way
and im doing this in the character script
note that events don't really save you from references, they just invert the dependency. I.e. instead of the Player script referencing the UI, the UI will reference the player in order to listen to the event.
Again i have no idea what you mean by "acces both the character script and the text component"
in my code i have to reference them both as an object i think and im just wondering is that really the best way to go about it
whats the site we use to post a long code here?
In which code
you will need references somewhere
in the character script
!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.
in the update() function
Ok so like I said, no you don't need to reference the ui in the character script. You can use events.
Options are:
- Use a UnityEvent on the player and assign it to a function on the UI in the inspector
- Use a C# event on the player and have the Ui reference the player to listen to it
- Use a static C# event on the player class and have the UI script just subscribe to the static event
Where do i add this code? Within update?
am i doing it right?
no you're still doing GameObject handPrefab;
and GameObject player
i mean, am i posting the code in the right way?
Yes, but why post the old code at all?
Fix it and THEN post it
yes
No, you use what you need to in the place where you currently reload the scene. Those are the 2 different types of how you CAN load a scene
cause if i replace the GameObject for my script i can't instantiate it
i hate language barrier lol
almost using google translator
This is not correct. Yes you can Instantiate the handMovement directly.
So if I simply want to reset the scene entirely, i would use single no?
would you say unity events or c# events are preferred in my case
Kind of personal preference, but I prefer C# events for this.
why so?
ask yourself, do you want them exposed in the inspector or not
ok it says i can't convert handMoviment into GameObject
prob because im trying to instantiate the script not the prefab lol
that may be helpful but i cant say for sure, is that the main difference?
ok, so change the return type of the Instantiate
basically, yes,
Incorrect. If you give it the type of a component it still instantiates the whole object, it just returns that component instead of the GameObject
Change the variable on line 7 AND the return type on line 18
You need to change BOTH
OH now i see that
i feel i was refusing to think
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i replaced GameObject for var idk why
but it wont change anything i guess
what i don't understand is how am i instantiating a script?
who is writing your code? You or some other entity?
is there a site with all the naming conventions specifically the ones like ``m_, g_ or __name`
me
Did you remove the instantiate call?
then why dont you know what you are doing?
i want to understand their purpose so i can read the docs better
Depends on the conventions you want to follow. Microsoft of course has their own
If you google "c# naming conventions" it will come up with them
guess ik what im doing just can't use the right english words
thanks
to tell you guys what im doing
Did you remove the instantiate call?
no i just change the types
"idk why"
What line is instantiate on now then. I do not see it in your most recent code
wdym, it stills line 18
Ah my bad. I'm on my phone so it was off screen and I just missed it
What is the current issue then?
When you change the type of a variable set in the inspector, it forgets its previous value, you'll need to assign it again
when i drag the player, it says the type mismatches, since the type of the player referenced on the hand script is playerMovement (the script) should i drag the instead script?
no it doesn't work
yep, single unloads all other scenes
Does the object you're dragging in have a playerMovement script on the root of the prefab? If it's a child object it won't work
help why is it giving me errors 😭 i have no idea whats happening
the object im dragging (the player) isn't a prefab
its an object on the scene
Are you trying to drag it into a prefab?
yes
you have a private declaration inside a methed
i can turn it in a prefab
Prefabs cannot reference objects in the scene. You will need to set that value on the instance that is created in the scene
oh.
i understand now but all these random errors just dont make sense
then you need to spend some time to learn c#
They're not random. You just dropped a class-level structure in the middle of a function. The compiler is going to get confused
You essentially cut your function in half by putting that there
and the first half has no ending braces, while the second half has no start
Hence all the other errors
oh
thxx guys
everything is working now
so, when i instantiate the script instead of the prefab itself im instatiating the prefab if thats inside the root of it?
thats what i understand
you got it
is it possible to a script to be inside more than one object?
i mean
more than one prefab
sure
then if i try to instantiate a script inside two prefabs what will happen?
the inspector will accept any prefab that has that script on it
what
you can only assign one prefab in the inspector, wdym by 2 prefabs?
oh i drag one prefab to the inspector so it won't have to choose one since i've already done
nvm
ok i get it
thx
what do i replace index with?
is the rigidbody component toggleable through a script?
I'm trying to make a ball turn on its physics when I enter a trigger box but the toggle I'm supposed to work with per the tutorial I'm following isn't there for rigidbody specifically
you can only toggle if its Kinematic or not
there is no enable/disable directly per se
if you are in 2D afaik there is actually one to disable it , turn off Simulated
I'm doing the bonus scene in the fundamentals tutorial, adding a trigger for it in the kid's room
so it's a 3D scene
okay so the kinematic toggle kinda "pauses" the object's simulations as long as it's checked?
yes. Are you in 2D or 3D ?
3D
kinematic stops all velocity / outside forces from affecting it
and that's workable then
my other Idea was gonna be an invisible bowl to cradle the ball that I would disable on trigger lol
oh so it's still gonna fall if the object starts out in mid-air?
why would it fall if no velocity is present
or affected by outside forces (gravity)
The build index of your scene
No
Gravity is an outside force
okay fair enough, I'm gonna test that out once I write out the script
it's like ontriggerenter into rigidbody.kinematic toggle or something along those lines I figure
I'll figure it out now that I know what property to manipulate
what doesn't is the number counter not going up when i touched a game object from other scenes, since I don't know how to make it persistent
is it the title of the scene?
just wanted to confirm, does this event still get invoked if the Video Player is not set to Loop?
https://docs.unity3d.com/ScriptReference/Video.VideoPlayer-loopPointReached.html
If you go to Build Settings and add the currently opened scene, you should see the scene in build on top and the index on the right side
Hey, how do I get info from project settings? Like gravity in project
Is it ok to name value same as enum name? it wont cause any problems right?
As in the number order of the scenes?
yep that's the build index
Not typically, but for readability I would give one or the other a different name
okay thanks
Alr thanks man
I like to use current[enum name]
So currentRarity for example
If it's public it'd be CurrentRarity
ill mostly likely use WeaponRarity
Yeah depends on what you need it for
Oh, it was Physics.gravity.
If the enum is called WeaponRarity, I would probably make the variable called rarity
In state enums, I usually just put current in front of the Enum name (currentMoveState)
enum is Rarity, its gonna be used everywhere, not only weapons
and its not state
I know it is not a state. That was clear from the name. That was just an aside in addition to the previous statement
okay, thanks!
I think I'm missing something
the console tells me it couldn't find the namespace for rigidbody
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallPhysicsTrigger : MonoBehaviour
{
//new classes to store properties of RigidBody component
public RigidBody rb;
public bool isKinematic = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
// Check if the object entering the trigger is the player (or another specified object)
if (other.CompareTag("Player")) // Make sure the player GameObject has the tag "Player"
{
if (rb != false)
{
//turn off the Kinematic property and enable physics
rb.isKinematic = false;
}
}
}
}
You spelled Rigidbody incorrectly.
In your code you wrote RigidBody
!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.
oh ffs yeah
now it's whining about the output directory for the build, I don't know what that's about
do you have a configured IDE ? it should show you all the correct names
idk the autocorrect worked fine for the other scripts, probably typed it all the way in autopilot mode
the trigger works now tho
did it not underline red in editor when you wrote it wrong?
nope Visual Studio even gave me full green bars on the left side
I've always had beef with custom classes, we go way back
can you screenshot your visual studio rq
That's an indicator of file changes, not syntax or errors 🙃
make sure it says Assembly-CSharp up top. not miscellaneous
yeah not configured
retyped it wrong on purpose
double check these steps !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)
also closing VS n clicking the Regen project files button after
alright yea I was just using the virgin configuration of VS I as using for normal programming
yeah its gonna make your coding better when you can pullup all the proper classes and whanot
what's weird is that it did give me the suggestions for the autocomplete, but not the red underlines
at least you will know it compiles with no errors, even the code doesn't work as expected sometimes lol
I think it was just giving the common used items you had already, not the actual Unity classes
I did update VS recently and noticed it seems to have introduced an AI autocomplete of some variety
nope it gave me the proper list from the namespaces
I barely used VS before this
let alone the 2022 version
well right now its not lol so I'd take care of that first
alright
gotta love the random grunt work you'd have never thought you needed to do in order to not go insane 100 hours down the line
huh
it's all already there
same goes for the Unity hub & editor side
I did run an update in VS tho, maybe it was just a version conflict
there are more steps to it
That is just one step
And having a checkmark doesn't mean it was installed necessarily
I checked all the steps in here
Ok, and did you regenerate the project files as navarone said?
okay I didn't know what that meant so my eyes kinda skipped over that part
No worries. It makes sense to do it at the very end anyways
It is just a button in external tools. Only the top one or two checkboxes need clicking. That's all I do at least, I am still unclear on which are necessary. Definitely not all of them though
okay where do you go for that
In external tools. The same place in the guide where you selected visual studio as the external tool
It is in unity
#🤝┃introductions 🤷♂️🤦♂️
okay did that, it finally works now
Fix up your name/profile if you want to use this server.
celebrations are in order indeed
it's like 30 degrees C right now
I'm gonna double dip the ice cream after dinner 🫠
Come on.....
🤦
!ban 920336052231749652 Shitty human being
7moodyxd was banned.
{
if (DisplayVar != null)
{
string FormatTime(float time)
{
var minutes = (int)time / 60;
var seconds = (int)time % 60;
return $"{minutes:00}:{seconds:00}";
}
val += Time.deltaTime;
System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(val);
DisplayVar.text = timeSpan.ToString(@"hh\:mm\:ss");
}
else
{
val = 0;
}
}```
its not updating
Weird place for a local function 🤔
why did you make the function local
outside of Update
the same place you declared the other ones
You're also not actually calling said function
alrght how do i call it tho
i literally showed you verbatim where to place it & how to call it lol
kek
myFunctionOrMethodName(andItsArguments);
you're confusing declaring vs calling @long jacinth
i mean how and where
I would highly recommend a beginner C# course.
So you can get a grasp of functions/methods, variables and the like
You also combined two solutions. Delete the timespan stuff
i just need to finish this jam
Are you even "finishing" it if you need people to spoon feed the code to you?
Right, were giving you the solution but you don't know how to implement it
Sounds like you're asking us to finish this jam for you
So you're having the crowd do it for you
{
var minutes = (int)time / 60;
var seconds = (int)time % 60;
return $"{minutes:00}:{seconds:00}";
}
void Update()
{
if (DisplayVar != null)
{
val += Time.deltaTime;
DisplayVar.GetComponent<TextMeshProUGUI>().text = FormatTime(val);
}
else
{
val = 0;
}
}```
You won't properly learn anything if you're copying and pasting
or at very least know what you are copying & what it does
im panicking really my eyes are rolling all over the screen
im gonna try to learn
we dont have to know any of that. write a journal
What is this jam for? Your life?
no a special discord role and a youtuber playing my game
Are you working on this by yourself?
sadly
actually thats a good thing my friend is convinced i should stop learning unity bec ai can do everything for me
Your friend is delusional.
WORKS THANKS GUYS!!!!
it's alright bro it's easy to get overwhelmed if you don't have any coding background
hell, I do and sometimes it's hard for me to follow references and inheritances too
just take things one step at a time and get creative with the stuff you look up
Your friend, I'm sorry to say, is very incorrect and steered you wrong. This is laughable thinking
They clearly don't know anything about unity or ai
In the western world we call them a "Hater"
well he isnt a hater he tried learning unity too he just thinks that ai will improve to the point where u just tell it to make a game and it makes the game
Then your friend is a fool
Or a grifter
or both
he left that ideology thankfully
lmao
maybe in a thousand years
but we wont be around to know
in the meantime, your friend is still delusional
when AI gets good enough to do X, everyone can do X, so doing X will become meaningless.
unless someone here is immortal or a lich.
Yes, go get your discord role
{
bossTransform = animator.transform;
playerTransform = GameObject.Find("Player").transform;
monoBehaviour = animator.GetComponent<MonoBehaviour>();
initialWidth = UnityEngine.Random.Range(1.5f, 3f);
initialLength = UnityEngine.Random.Range(2f, 4f);
monoBehaviour.StartCoroutine(Trigger(animator));
animator.SetTrigger("Return");
}
IEnumerator Trigger(Animator animator)
{
for (int i = 0; i < UnityEngine.Random.Range(3, 5); i++)
{
yield return new WaitForSeconds((i) * Random.Range(.15f, .3f));
// monoBehaviour.StartCoroutine(Fire(widthMultiplier, lengthMultiplier));
Debug.Log("HI");
widthMultiplier *= Random.Range(1.5f, 2f);
lengthMultiplier *= Random.Range(1.5f, 2f);
}
}```
Could someone help me with this? I'm trying to make it so when I enter the state I start a coroutine that happens independently and I call SetTrigger("Return") to go back to the preivous state the next frame. Problem is it seems to be waiting for the coroutine to finish before returning to the previous state.
The coroutine allows you to call the method without blocking the update calls
but still is technically "synchronous"
So would the workaround be to call SetTrigger inside the OnStateUpdate?
Problem is it seems to be waiting for the coroutine to finish before returning to the previous state.
What makes you think that? There's a lot missing from the code you shared. Where does returning to the previous state happen?
btw:
i < UnityEngine.Random.Range(3, 5) you should really do this before the for loop otherwise it's generting a new int each iteration of the loop
e.g.
int count = UnityEngine.Random.Range(3, 5);
for (int i = 0; i < count; i++)```
ok wait thats really dumb mb ty for catching that
monoBehaviour.StartCoroutine(Trigger(animator));
animator.SetTrigger("Return");
The coroutine will only run up until the first yield before proceeding to the animator.SetTrigger() call, and the coroutine will not advance until the next frame... There should be no delay.
You could chuck some Logs in there to verify
https://gamedev.stackexchange.com/questions/211548/how-can-i-increase-my-counter-and-have-it-persist-across-scenes-and-runtime using tis website instead
basically when I return to the previous state the boss sprite the animator is in starts moving, but the " Debug.Log("HI");" line runs before the sprite starts moving
you sure that's because of the coroutine and not because your animator transitions have an exit time or something?
I alr made sure all of the transitions dont have exit times
there's nothing in this code that waits for the coroutine to finish
unless widthMultiplier etc. are properties for example?
nah their just private variables
Are you sure you always have only one Counter script in the scene?
You have this, which makes it the instance:cs Instance = this;
But can the scene you loaded already have a Counter in it?
If yes, you should handle destroying duplicate singletons
actually, the counter is for the gameplay scenes at first it was used to collect coins
while MuonCounter is a different thing where it counts how many muon objects you have touched
Well then my question stands but for MuonCounter instead of Counter
Are you sure that only one MuonCounter is instantiated during the game and when switching scenes?
what do you mean only one MuonCounter?
Thread
How would I make a method run on a perfab when its instantiated
MonoBehaviour.Start() gets called when an object is instantiated and active for the first time.
So start is when it spawns in
Awake is when it spawns in
Awake and OnEnable will have run by the time Instantiate returns.
Start will run later, just before its first monobehaviour lifecycle function runs (FixedUpdate/Update, etc)
Start is when it is "alive", awake/enable are more technical/local events, you'd pick and choose depending on what you want to do.
I often refer back to this page in the manual when I need to sort out execution order
Oh dang. That is good to know. I never knew that (about awake and onenable completing before instantiate returns) 🙏
this isn't entriely guaranteed, if you instantiate an inactive prefab awake/enable will not get called
Yeah fair. I get that part, but thanks for the clarification
Okay thanks a lot
i find that to be a very useful property when constructing complex objects or as part of a save-system.
Yeah, lotta control over the execution flow that way
you can basically inject your own lifecycle by hacking around these events
How would I change the rotation of an object to face another in 2d?
transform.right = other.position - transform.position;
get the direction from that object to the other (direction is (endPoint - startPoint).normalized) and assign it as the transform.up or transform.right depending on its non-rotated orientation
Set transform.right or transform.up or whatever direction serves as "forward" on your sprite to the direction between the two objects
Thank you a lot never knew it was so simple
"YouTUbe tutorial makers hate this one simple trick!"
I watched Codeer’s video on how to make a procedural animation. I need a bit of help with the second step of the video, which involves anchoring/fix the the bottom of the foot to the ground.Thanks!
not exactly sure what you mean. do you mean positioning the model so that the bottom of the model is in contact with the ground? or do you mean using IK constraints to detect the ground
Yes i mean :do you mean using IK constraints to detect the ground.
https://www.youtube.com/watch?v=e6Gjhr1IP6w
are you looking at this video?
I tried to explain procedural animation in 10 steps.
Check out my twitter: https://twitter.com/CodeerDev
Yes!
im not sure what your setup looks right now but is your model positioned such that one leg is on the ground already?
how would I go about finding out which child has been hit in code?
The parent gameObject that is highlighted has a rigidbody and the script I'm using. OnCollisionEnter (Collision) seems to only have members that can get me a reference to the sword that hit it, but not areference to the body part I've hit
how do I say "if the bullet spawns on the player don't do OnTriggerEnter " in code.
which gameobject has oncollisionenter?
The training_dummy
assign your player the Player tag.
within OnTriggerEnter, check if the gameobject does not have the player tag.
do this check in your sword instead
Yes the foot is on the ground here is where i am Rn:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walker : MonoBehaviour
{
public Transform Target;
public float maxDistance = 0.9f;
public float moveSpeed = 2f;
public float arcHeight = 2f;
private Vector3 startPosition;
private Vector3 endPosition;
private Vector3 arcMidpoint;
private float arcProgress = 0f;
private bool isArcing = false;
void FixedUpdate()
{
if (isArcing)
{
PerformArcMovement();
}
else
{
CheckDistanceToTarget();
}
}
void CheckDistanceToTarget()
{
float distance = Vector3.Distance(transform.position, Target.position);
if (distance > maxDistance)
{
// Börjar gå
startPosition = transform.position;
endPosition = Target.position;
arcProgress = 0f;
isArcing = true;
// Calculerar var mitten är på Y axlen
Vector3 midPointBetween = (startPosition + endPosition) / 2;
arcMidpoint = new Vector3(midPointBetween.x, midPointBetween.y + arcHeight, midPointBetween.z);
}
}
void PerformArcMovement()
{
// Hur snabbt ska det gå
arcProgress += Time.deltaTime * moveSpeed / Vector3.Distance(startPosition, endPosition);
if (arcProgress >= 1f)
{
// gör klart animationen
transform.position = endPosition;
isArcing = false;
return;
}
// Slerp från början till slut
Vector3 positionToMid = Vector3.Slerp(startPosition, arcMidpoint, arcProgress);
Vector3 positionToEnd = Vector3.Slerp(arcMidpoint, endPosition, arcProgress);
transform.position = Vector3.Lerp(positionToMid, positionToEnd, arcProgress);
}
}
!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.
Oh thanks
I was hoping to avoid that if at all possible. Are my hands tied here or?
unfortunately your hands are tied here
best to do the check in the sword now so when you have multiple targets later your sword code easily carries over
I don't think so?
Unless I missed it
But so be it ig
collision.GetContact(0).???, let me check
OnTriggerEnter is a method, not a variable. You cannot assign or compare it. No idea why you have return there . . .
checking rn
sorry I just know a bit of coding from learning from unity courses. How would I do that?
It does, there's otherCollider and thisCollider!
So as long as the Rigidbody is on the dummy object and the children have colliders, collision events will get reported bubbled up to the Rigidbody meaning you only need the script in one place, where the rigidbody is
when you tag an object. you can easily check the tag of the object later on in case you wanna do stuff. Here, since we want to tag our player with the Player tag we don't have to do more checks.
https://www.youtube.com/watch?v=D2lLNZgCu6k
#JIMMYVEGAS In this Mini Unity Tutorial we explain why tags are vital in game development and how you can use them to manipulate your game.
✦ Subscribe: http://bit.ly/JimmyVegasUnityTutorials
✦ Patreon: http://patreon.com/jimmyvegas/
✦ FREE Assets: http://jvunity.com/
✦ Facebook: https://www.facebook.com/jimmyvegas3d/
✦ Twitter: https://twitter...
very short video on this
I strongly recommend you to learn c# before you start coding in unity, have solid foundations
Pepper = gameObject.transform.GetChild("Object Preview");
i want get child object of my gameObject with his name someone can help me 🙂
for some people they did dive straight into unity, that's also an approach. but for me I started learning a lot faster and understood a lot of things by learning programming(c++) before diving into unity